@vindral/web-sdk 4.2.0-1-g70011111 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/legacy.umd.js CHANGED
@@ -47,7 +47,7 @@ void main() {
47
47
  }
48
48
  `,FC={width:256,codedWidth:256,height:144,codedHeight:144},kC={preserveDrawingBuffer:!1,alpha:!1,depth:!1,stencil:!1,antialias:!1,premultipliedAlpha:!1},yt=class yt extends ie{constructor(){super();s(this,"canvas",document.createElement("canvas"));s(this,"context",DC(this.canvas,kC));s(this,"pixelShader",os(this.context,this.context.FRAGMENT_SHADER,pC));s(this,"vertexShader",os(this.context,this.context.VERTEX_SHADER,yC));s(this,"buffer",SC(this.context,yt.SQUARE_VERTICES));s(this,"program",ja(this.context,this.vertexShader,this.pixelShader));s(this,"textures",{y:ii(this.context),u:ii(this.context),v:ii(this.context)});s(this,"textRenderer");s(this,"size",FC);s(this,"modelLocation",null);s(this,"conversionLocation",null);s(this,"cachedScaleX",0);s(this,"cachedScaleY",0);s(this,"cachedTransformMatrix",null);s(this,"texturesNeedRealloc",!0);s(this,"onContextLost",e=>{this.textRenderer=void 0;const t=new Error(e instanceof WebGLContextEvent?e.statusMessage:"webgl context lost");this.emit("context lost",wh(t)),e.preventDefault()});s(this,"onContextRestored",()=>{this.emit("context restored"),this.context=DC(this.canvas,kC),this.pixelShader=os(this.context,this.context.FRAGMENT_SHADER,pC),this.vertexShader=os(this.context,this.context.VERTEX_SHADER,yC),this.buffer=SC(this.context,yt.SQUARE_VERTICES),this.program=ja(this.context,this.vertexShader,this.pixelShader),this.textures={y:ii(this.context),u:ii(this.context),v:ii(this.context)},this.load()});s(this,"load",()=>{this.context.useProgram(this.program),this.setupPositionVertexAttributes(),this.texturesNeedRealloc=!0,this.setSize(FC),this.modelLocation=this.context.getUniformLocation(this.program,"model"),this.conversionLocation=this.context.getUniformLocation(this.program,"conversion"),this.context.uniform1i(this.context.getUniformLocation(this.program,"y_texture"),0),this.context.uniform1i(this.context.getUniformLocation(this.program,"u_texture"),1),this.context.uniform1i(this.context.getUniformLocation(this.program,"v_texture"),2),this.setConversionMatrix(yt.REC709)});s(this,"unload",()=>{var t;this.setSize({width:1,height:1,codedHeight:1,codedWidth:1}),[this.textures.y,this.textures.u,this.textures.v].forEach(g=>this.context.deleteTexture(g)),this.context.deleteShader(this.pixelShader),this.context.deleteShader(this.vertexShader),this.context.deleteProgram(this.program),this.context.deleteBuffer(this.buffer),this.canvas.removeEventListener("webglcontextlost",this.onContextLost),this.canvas.removeEventListener("webglcontextrestored",this.onContextRestored),(t=this.context.getExtension("WEBGL_lose_context"))==null||t.loseContext()});s(this,"resetSize",()=>{this.setSize({width:this.size.width/2,height:this.size.height/2,codedHeight:this.size.codedHeight/2,codedWidth:this.size.codedWidth/2})});s(this,"render",(e,t)=>{if(this.context.useProgram(this.program),this.setSize({width:e.width,height:e.height,codedWidth:e.codedWidth,codedHeight:e.codedHeight}),this.setModelMatrix(this.size.width/this.size.codedWidth,this.size.height/this.size.codedHeight),this.context.activeTexture(this.context.TEXTURE0),this.updateTexture(this.textures.y,this.size.codedWidth,this.size.codedHeight,e.data[0]),this.context.activeTexture(this.context.TEXTURE1),this.updateTexture(this.textures.u,this.size.codedWidth/2,this.size.codedHeight/2,e.data[1]),this.context.activeTexture(this.context.TEXTURE2),this.updateTexture(this.textures.v,this.size.codedWidth/2,this.size.codedHeight/2,e.data[2]),this.texturesNeedRealloc=!1,this.context.drawArrays(this.context.TRIANGLE_STRIP,0,4),this.textRenderer){const g=t.style.getPropertyValue("--vindral-subtitle-offset")||t.style.getPropertyValue("--vindral-control-bar-offset"),n=parseInt(g||"0",10),o=Number.isNaN(n)?0:-n;this.textRenderer.render({canvasWidth:this.size.width,canvasHeight:this.size.height,containerWidth:t.clientWidth||this.canvas.clientWidth||this.size.width,bottomPadding:o})}});s(this,"updateTexture",(e,t,g,n)=>{const a=this.context.LUMINANCE,B=this.context.UNSIGNED_BYTE;this.context.bindTexture(this.context.TEXTURE_2D,e),this.texturesNeedRealloc?this.context.texImage2D(this.context.TEXTURE_2D,0,a,t,g,0,a,B,n):this.context.texSubImage2D(this.context.TEXTURE_2D,0,0,0,t,g,a,B,n)});s(this,"setupPositionVertexAttributes",()=>{const e=this.context.getAttribLocation(this.program,"position");this.context.enableVertexAttribArray(e),this.context.vertexAttribPointer(e,2,this.context.FLOAT,!1,0,0)});s(this,"setSize",e=>{e.width===this.size.width&&e.height===this.size.height&&e.codedWidth===this.size.codedWidth&&e.codedHeight===this.size.codedHeight||(this.size=e,this.texturesNeedRealloc=!0,this.canvas.setAttribute("width",e.width.toString()),this.canvas.setAttribute("height",e.height.toString()),this.context.viewport(0,0,e.width,e.height),this.setModelMatrix(e.width/e.codedWidth,e.height/e.codedHeight))});s(this,"setModelMatrix",(e,t)=>{(this.cachedScaleX!==e||this.cachedScaleY!==t||!this.cachedTransformMatrix)&&(this.cachedScaleX=e,this.cachedScaleY=t,this.cachedTransformMatrix=this.transformMatrix(e,t)),this.context.uniformMatrix4fv(this.modelLocation,!1,this.cachedTransformMatrix)});s(this,"setConversionMatrix",e=>{this.context.uniformMatrix4fv(this.conversionLocation,!1,e)});s(this,"transformMatrix",(e,t)=>[2/e,0,0,0,0,-2/t,0,0,0,0,2/1,0,-1,1,0,1]);this.canvas.addEventListener("webglcontextlost",this.onContextLost),this.canvas.addEventListener("webglcontextrestored",this.onContextRestored,!1),Va(this.canvas)}getTextRenderer(){return this.textRenderer||(this.textRenderer=new fh(this.context)),this.textRenderer}};s(yt,"SQUARE_VERTICES",new Float32Array([0,0,0,1,1,0,1,1])),s(yt,"REC709",[1.16438,0,1.79274,-.97295,1.16438,-.21325,-.53291,.30148,1.16438,2.1124,0,-1.1334,0,0,0,1]),s(yt,"REC601",[1.16438,0,1.59603,-.87079,1.16438,-.39176,-.81297,.52959,1.16438,2.01723,0,-1.08139,0,0,0,1]);let za=yt;class Yn{constructor(A,e,t,g){s(this,"keySystem");s(this,"licenseServerUrl");s(this,"certificate");s(this,"headers",{});s(this,"queryParams",{});r(this,Qi);r(this,Ei);E(this,Qi,e),this.keySystem=A,this.licenseServerUrl=t,this.certificate=g}get statistics(){return{keySystem:I(this,Qi).keySystem,licenseServerUrl:this.licenseServerUrl,mediaKeySystemConfiguration:I(this,Qi).getConfiguration()}}getMediaKeys(){return c(this,null,function*(){return I(this,Ei)?I(this,Ei):(E(this,Ei,yield I(this,Qi).createMediaKeys()),I(this,Ei))})}requestLicense(A){return c(this,null,function*(){const e=new URL(this.licenseServerUrl);for(const[n,o]of Object.entries(this.queryParams))e.searchParams.append(n,o);const t=yield fetch(e,{method:"POST",body:A,headers:f({"Content-Type":"application/octet-stream"},this.headers)});if(!t.ok)throw new Error(`Failed to fetch license: ${t.statusText}`);return yield t.arrayBuffer()})}}Qi=new WeakMap,Ei=new WeakMap;function RC(i){const A=window.atob(i.replace(/-/g,"+").replace(/_/g,"/"));let e="";for(let t=0;t<A.length;t++)e+=("0"+A.charCodeAt(t).toString(16)).substr(-2);return e}function Dh(i){let A="";for(let e=0;e<i.length;e+=2)A+=String.fromCharCode(parseInt(i.substr(e,2),16));return window.btoa(A).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Sh(i,A){if(i.byteLength!==A.byteLength)return!1;const e=new Uint8Array(i),t=new Uint8Array(A);for(let g=0;g<e.length;g++)if(e[g]!==t[g])return!1;return!0}class ph extends Yn{constructor(e,t){super("clearkey",e,"");r(this,Vg);E(this,Vg,t)}handleLicenseRequest(e){const t=new Uint8Array(e),g=String.fromCharCode(...t),n=JSON.parse(g),o=[];for(let C=0;C<n.kids.length;C++){const Q=n.kids[C];if(Q){const h=RC(Q).toLowerCase(),d=I(this,Vg)[h];d&&o.push({kty:"oct",alg:"A128KW",kid:Q,k:Dh(d)})}}const a=JSON.stringify({keys:o,type:n.type});return new TextEncoder().encode(a)}}Vg=new WeakMap;const GC={playready:["150","2000","3000"],widevine:["SW_SECURE_CRYPTO","SW_SECURE_DECODE","HW_SECURE_CRYPTO","HW_SECURE_DECODE","HW_SECURE_ALL"],fairplay:[""],clearkey:[""]},_a={initDataTypes:["cenc"],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42c01f"'}]},yh={fairplay:{keySystem:"com.apple.fps",supportedConfig:{initDataTypes:["sinf"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42c01f"'}]}},playready:{keySystem:"com.microsoft.playready",supportedConfig:_a},widevine:{keySystem:"com.widevine.alpha",supportedConfig:_a},clearkey:{keySystem:"org.w3.clearkey",supportedConfig:_a}},UC=(i,A)=>c(null,null,function*(){return navigator.requestMediaKeySystemAccess(i,[A]).catch(()=>{})}),bC=(i,A,e,t,g,n)=>c(null,null,function*(){let o;for(const a of t){const B=e==null?void 0:e.map(Q=>V(f({},Q),{robustness:a,contentType:n?`${g==="audioCapabilities"?"audio/mp4":"video/mp4"}; codecs="${n}"`:Q.contentType}));if(!(yield UC(i,{initDataTypes:A,[g]:B})))break;o=B}return o}),Fh=(i,A,e,t)=>c(null,null,function*(){const{keySystem:g,supportedConfig:n}=yh[i],{initDataTypes:o,videoCapabilities:a,audioCapabilities:B}=n,C=t==null?void 0:t[i],Q=(C==null?void 0:C.videoRobustness)||GC[i],h=(C==null?void 0:C.audioRobustness)||GC[i],[d,u]=yield Promise.all([bC(g,o,a,Q,"videoCapabilities",A),bC(g,o,B,h,"audioCapabilities",e)]);return!d&&!u?void 0:yield UC(g,{initDataTypes:o,videoCapabilities:d,audioCapabilities:u})}),kh=(i,A,e,t)=>c(null,null,function*(){let g;for(const n of i)if(g=yield Fh(n,A,e,t),g)return{keySystem:n,mediaKeySystemAccess:g}});class Rh extends Yn{constructor(A,e,t){super("fairplay",A,e,t)}}const Gh=i=>{var a,B,C,Q;const A=String.fromCharCode(...new Uint16Array(i)),e=new window.DOMParser().parseFromString(A,"application/xml"),t=e.getElementsByTagName("HttpHeaders")[0];let g={};if(t){const h=t.getElementsByTagName("name"),d=t.getElementsByTagName("value");for(let u=0;u<h.length;u++){const m=(a=h[u])==null?void 0:a.childNodes[0],p=(B=d[u])==null?void 0:B.childNodes[0];m!=null&&m.nodeValue&&p&&p.nodeValue&&(g[m.nodeValue]=p.nodeValue)}}const n=e.getElementsByTagName("Challenge")[0];let o;return n&&((C=n.childNodes[0])!=null&&C.nodeValue)&&(o=window.atob((Q=n.childNodes[0])==null?void 0:Q.nodeValue)),e.querySelector("parsererror")&&(g={"Content-Type":"text/xml; charset=utf-8",SOAPAction:'"http://schemas.microsoft.com/DRM/2007/03/protocols/AcquireLicense"'},o=i),{headers:g,message:o}};class Uh extends Yn{constructor(A,e){super("playready",A,e)}requestLicense(A){return c(this,null,function*(){lA(this.licenseServerUrl,"No license server URL set");const e=new URL(this.licenseServerUrl);for(const[n,o]of Object.entries(this.queryParams))e.searchParams.append(n,o);const t=Gh(A),g=yield fetch(e,{method:"POST",headers:f(f({},t.headers),this.headers),body:t.message});if(!g.ok)throw new Error(`Failed to fetch license: ${g.statusText}`);return yield g.arrayBuffer()})}}class bh extends Yn{constructor(A,e){super("widevine",A,e)}}const Nh=5e3;class NC{constructor(A,e,t={}){r(this,wA);r(this,iA);r(this,ci);r(this,tt);r(this,pe,new _);r(this,Ke);r(this,UA);r(this,Ft,new Map);r(this,kt);r(this,Jo,qa());r(this,hs);r(this,Zg,A=>{if(I(this,iA).info("Received DRM data",{drmData:A}),window.clearTimeout(I(this,hs)),I(this,UA)){const e=l(this,wA,UE).call(this,A)[I(this,UA).keySystem];e&&(I(this,UA).licenseServerUrl=e)}I(this,pe).resolve(A)});r(this,Xg,A=>{I(this,iA).info("Encrypted event received",{event:A}),l(this,wA,pE).call(this,A)});r(this,Mo,A=>{var n,o;I(this,iA).debug("Session message received",{event:A});const e=A.target,t=A.message;if(!I(this,Ft).get(e)){I(this,iA).error("No active session found for event",{event:A});return}I(this,iA).debug("Requesting license for session",{sessionId:e.sessionId,licenseServerUrl:(n=I(this,UA))==null?void 0:n.licenseServerUrl}),(o=I(this,UA))==null||o.requestLicense(t).then(a=>{I(this,iA).debug("License received for session",{sessionId:e.sessionId}),e.update(a).catch(B=>{l(this,wA,Gn).call(this,{message:"Failed to update session with license",isFatal:!1,error:B})})}).catch(a=>{l(this,wA,Gn).call(this,{message:"Failed to request license",isFatal:!1,error:a})})});r(this,vo,A=>{const e=A.target;I(this,iA).debug("Key status changed for session",{sessionId:e.sessionId}),e.keyStatuses.forEach((t,g)=>{const n=RC(window.btoa(String.fromCharCode(...new Uint8Array(g))));I(this,iA).debug("Key status",{base64kid:n,status:t})})});r(this,Ho,A=>c(this,null,function*(){const e=l(this,wA,GE).call(this,A);I(this,iA).debug("Prioritized key system list",{keySystemList:e});const t=yield kh(e,A.videoCodec,A.audioCodec,{widevine:I(this,Ke).widevine,playready:I(this,Ke).playready});if(!t)return I(this,iA).warn("No supported key system found"),null;I(this,iA).debug("Supported key system found",t.mediaKeySystemAccess.getConfiguration());const{keySystem:g,mediaKeySystemAccess:n}=t;let o=null;return g==="clearkey"?(lA(A.clearkeys,"No clearkeys found"),o=new ph(n,A.clearkeys)):g==="playready"?(lA(A.playreadyLicenseUrl,"No playreadyLicenseUrl found"),o=new Uh(n,A.playreadyLicenseUrl)):g==="widevine"?(lA(A.widevineLicenseUrl,"No widevineLicenseUrl found"),o=new bh(n,A.widevineLicenseUrl)):g==="fairplay"&&(lA(A.fairplayLicenseUrl,"No fairplayLicenseUrl found"),lA(A.fairplayCertificate,"No fairplayCertificate found"),o=new Rh(n,A.fairplayLicenseUrl,A.fairplayCertificate)),o&&(o.headers=I(this,Ke).headers||{},o.queryParams=I(this,Ke).queryParams||{}),o}));E(this,ci,A),E(this,iA,e),E(this,Ke,t),I(this,ci).on("received drm data",I(this,Zg))}static isSupported(){return!!navigator.requestMediaKeySystemAccess}attach(A){E(this,tt,A),I(this,iA).info("Media element attached"),I(this,tt).addEventListener("encrypted",I(this,Xg))}getStatistics(){var A,e;return!I(this,pe).resolved&&!((A=I(this,UA))!=null&&A.statistics)?null:f(f({},I(this,pe).resolved),(e=I(this,UA))==null?void 0:e.statistics)}unload(){var A;I(this,iA).info("Unloading EncryptedMediaExtensions"),I(this,ci).off("received drm data",I(this,Zg)),(A=I(this,tt))==null||A.removeEventListener("encrypted",I(this,Xg)),I(this,Ft).forEach((e,t)=>{t.close()}),I(this,Ft).clear(),E(this,kt,void 0),E(this,UA,void 0)}set headers(A){I(this,Ke).headers=A,I(this,UA)&&(I(this,UA).headers=A)}set queryParams(A){I(this,Ke).queryParams=A,I(this,UA)&&(I(this,UA).queryParams=A)}onChannelSwitch(){if(!I(this,pe).resolved){I(this,iA).debug("DRM is not used, skipping channel switch handling");return}wc()&&I(this,Jo).platform.safariVersion<18&&l(this,wA,Gn).call(this,{message:"DRM channel switch not supported on Safari < 18",isFatal:!0}),window.clearTimeout(I(this,hs));const A=I(this,pe).resolved;E(this,pe,new _),E(this,hs,window.setTimeout(()=>{I(this,pe).resolve(A)},Nh))}}iA=new WeakMap,ci=new WeakMap,tt=new WeakMap,pe=new WeakMap,Ke=new WeakMap,UA=new WeakMap,Ft=new WeakMap,kt=new WeakMap,Jo=new WeakMap,hs=new WeakMap,Zg=new WeakMap,Xg=new WeakMap,wA=new WeakSet,pE=function(A){return c(this,null,function*(){try{yield l(this,wA,yE).call(this),I(this,iA).debug("Media keys initialization completed"),yield l(this,wA,FE).call(this,A.initData,A.initDataType)}catch(e){l(this,wA,Gn).call(this,{message:"Failed to handle encrypted event",isFatal:!0,error:e})}})},yE=function(){return c(this,null,function*(){var e;I(this,iA).debug("Initializing media keys");const A=yield I(this,pe).promise;if((e=I(this,tt))!=null&&e.mediaKeys){I(this,iA).debug("Media keys already set on media element");return}if(I(this,kt)){I(this,iA).debug("Media keys initialization already in progress, waiting for completion"),yield I(this,kt);return}E(this,kt,c(this,null,function*(){const t=yield I(this,Ho).call(this,A);I(this,iA).debug("CDM obtained",{cdm:t}),lA(I(this,tt),"No media element found"),lA(t,"No CDM found");const g=yield t.getMediaKeys();t.certificate&&(yield l(this,wA,RE).call(this,g,t.certificate)),I(this,iA).debug("Setting media keys on media element"),yield I(this,tt).setMediaKeys(g),E(this,UA,t)})),yield I(this,kt)})},FE=function(A,e){return c(this,null,function*(){lA(I(this,UA),"No CDM manager found");const t=yield I(this,UA).getMediaKeys();if(!A||!l(this,wA,kE).call(this,A)){I(this,iA).debug("Duplicate initData, no need to create new session",{initData:A});return}const g=t.createSession();I(this,iA).debug("Creating new session",{session:g}),g.addEventListener("keystatuseschange",I(this,vo)),g.closed.then(n=>{I(this,iA).info("Session is closed",{reason:n})}),g.addEventListener("message",I(this,Mo)),I(this,Ft).set(g,A),I(this,iA).debug("Generating request for session",{session:g,initDataType:e,initData:A}),yield g.generateRequest(e,A)})},kE=function(A){for(const[e,t]of I(this,Ft))if(Sh(A,t))return!1;return!0},Mo=new WeakMap,vo=new WeakMap,RE=function(A,e){return c(this,null,function*(){try{I(this,iA).debug("Setting server certificate",{certificate:e}),(yield A.setServerCertificate(e))||I(this,iA).warn("Server certificates are not supported by the CDM.")}catch(t){I(this,iA).error("Failed to set server certificate",{error:t})}})},Gn=function(A){const{message:e,isFatal:t,error:g}=A;I(this,iA).error(e,{error:g}),I(this,ci).emit("error",fC(e,t,g))},Ho=new WeakMap,GE=function(A){const e=[];return A.clearkeys&&e.push("clearkey"),A.playreadyLicenseUrl&&e.push("playready"),A.widevineLicenseUrl&&e.push("widevine"),A.fairplayLicenseUrl&&A.fairplayCertificate&&e.push("fairplay"),e},UE=function(A){return{fairplay:A.fairplayLicenseUrl,playready:A.playreadyLicenseUrl,widevine:A.widevineLicenseUrl,clearkey:void 0}};const Lh=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],LC=(i,A)=>{const e=Lh.indexOf(A);if(e===-1||i<1||i>8||i===7)return;const t=2,g=new ArrayBuffer(2),n=new Uint8Array(g),o=i===8?7:i;return n[0]=t<<3|e>>1,n[1]=(e&1)<<7|o<<3,g},Jh=7,Mh=8,vh=i=>{const A=i.getUint32(0,!1),e=i.getUint8(0)<<16|i.getUint16(1,!1);let t=0;return e===1?t+=3:A===1&&(t+=4),t},Hh=i=>vh(new DataView(i,0))!==0,JC=(i,A=0)=>{for(let e=A;e<i.byteLength-4;e++){const t=i.getUint32(e)===1,g=(i.getUint8(e)<<16|i.getUint16(e+1))===1;if(t||g)return{position:e,nalPrefixSize:t?4:3}}},qh=i=>i&31,Kh=(i,A)=>{const e=new DataView(i,0);let t=JC(e);for(;t;){const{position:g,nalPrefixSize:n}=t,o=JC(e,g+4),a=o?o.position-g-n:void 0;if(!A(new DataView(i,g+n,a),n))return;t=o}},MC=i=>{const A=[],e=[];if(!Hh(i)){const t=new DataView(i,0),g=t.getUint8(5)&31;let n=6;for(let a=0;a<g;a++){const B=t.getUint16(n);A.push(i.slice(n+2,n+2+B)),n+=B+2}const o=t.getUint8(n);n+=1;for(let a=0;a<o;a++){const B=t.getUint16(n);e.push(i.slice(n+2,n+2+B)),n+=B+2}return{sequenceParameterSets:A,pictureParameterSets:e}}return Kh(i,t=>{const g=t.byteOffset+t.byteLength;switch(qh(t.getUint8(0))){case Mh:e.push(t.buffer.slice(t.byteOffset,g));break;case Jh:A.push(t.buffer.slice(t.byteOffset,g));break}return!0}),{sequenceParameterSets:A,pictureParameterSets:e}},Th=i=>{var m;const A=new DataView(i),e=A.getUint8(1),t=A.getUint8(2),g=A.getUint8(3),n=new ts(i,32);n.readUnsignedExpGolomb();let o=1;switch(e){case 100:case 110:case 122:case 244:case 44:case 83:case 86:case 118:case 128:case 138:case 144:{if(o=n.readUnsignedExpGolomb(),o===3&&n.readBits(1),n.readUnsignedExpGolomb()+8,n.readUnsignedExpGolomb()+8,n.readBit(),n.readBit()){for(let y=0;y<(o!=3?8:12);y++)if(n.readBit()){const N=y<6?16:64;let U=0,K=8,W=8;for(let Z=0;Z<N;Z++)W!=0&&(U=n.readSignedExpGolomb(),W=(K+U+256)%256),K=W==0?K:W}}break}}n.readUnsignedExpGolomb();const a=n.readUnsignedExpGolomb();if(a==0)n.readUnsignedExpGolomb();else if(a==1)throw new Error("Unhandled case");n.readUnsignedExpGolomb(),n.readBit();const B=n.readUnsignedExpGolomb(),C=n.readUnsignedExpGolomb(),Q=n.readBit();Q===0&&n.readBit(),n.readBit();let h=B+1,d=C+1;if(d*=2-Q,d*=16,h*=16,n.readBit()){const p=o==1?1:0,k=1<<(o==1||o==2?1:0),N=2-Q<<p,U=n.readUnsignedExpGolomb()*k,K=n.readUnsignedExpGolomb()*k,W=n.readUnsignedExpGolomb()*N,Z=n.readUnsignedExpGolomb()*N;h-=U+K,d-=W+Z}let u={numerator:1,denumerator:1};return n.readBit()&&n.readBit()&&(u=(m=Yh[n.readBits(8)])!=null?m:{numerator:0,denumerator:0}),{width:h,height:d,pixelAspectRatio:u,profileIdc:e,constraintFlags:t,levelIdc:g}},Yh=[{numerator:0,denumerator:0},{numerator:1,denumerator:1},{numerator:12,denumerator:11},{numerator:10,denumerator:11},{numerator:16,denumerator:11},{numerator:40,denumerator:33},{numerator:24,denumerator:11},{numerator:20,denumerator:11},{numerator:32,denumerator:11},{numerator:80,denumerator:33},{numerator:18,denumerator:11},{numerator:15,denumerator:11},{numerator:64,denumerator:33},{numerator:160,denumerator:99},{numerator:4,denumerator:3},{numerator:3,denumerator:2},{numerator:2,denumerator:1}],Ph=184549376;function xh(i){const A=new Je(i),e=Wh(A);(e.flags&Ph)!==0&&Oh(A);const t=Vh(A);if(String.fromCharCode(...t.frameId)==="TXXX"){const n=new Je(A.readBytes(t.size));return{header:e,txx:Zh(n)}}}function Wh(i){const A=i.readBytes(3),e=i.readUint8(),t=i.readUint8(),g=i.readUint8(),n=i.readUint32();return{id:A,majorVersion:e,minorVersion:t,flags:g,size:n}}function Oh(i){const A=i.readUint32();return i.readBytes(A-4),{}}function Vh(i){const A=i.readBytes(4),e=i.readUint32(),t=i.readUint16();return{frameId:A,size:e,flags:t}}function Zh(i){const A=i.readUint8(),e=i.readUtf8String(),t=i.readUtf8String();return{encoding:A,description:e,value:t}}function vC(i){let A=i.readUint32();const e=String.fromCharCode(i.readUint8(),i.readUint8(),i.readUint8(),i.readUint8());return A===1&&(A=i.readUint64()-8),{size:A-8,type:e}}function Xh(i,A){const e=vC(A),t=new Je(A.readBytes(e.size));if(e.type!==i.type)throw new Error(`invalid error type: ${e.type}, expected ${i.type}`);const g=i.decodeData(t);return t.readRemaining(),g}function ve(i){const A=i.readUint8(),e=i.readUint24();return{version:A,flags:e}}const ds=class ds{constructor({timescale:A,presentationTime:e,presentationTimeDelta:t,schemeIdUri:g,value:n,eventDuration:o,id:a,data:B}){s(this,"type",ds.type);s(this,"timescale");s(this,"presentationTime");s(this,"presentationTimeDelta");s(this,"schemeIdUri");s(this,"value");s(this,"eventDuration");s(this,"id");s(this,"data");this.timescale=A,this.presentationTime=e,this.presentationTimeDelta=t,this.schemeIdUri=g,this.value=n,this.eventDuration=o,this.id=a,this.data=B}static decodeData(A){const{version:e}=ve(A);switch(e){case 1:{const t=A.readUint32(),g=A.readUint64(),n=A.readUint32(),o=A.readUint32(),a=A.readUtf8String(),B=A.readUtf8String(),C=A.remaining(),Q=A.readBytes(C);return new ds({timescale:t,presentationTime:g,eventDuration:n,id:o,schemeIdUri:a,value:B,data:Q})}case 0:{const t=A.readUtf8String(),g=A.readUtf8String(),n=A.readUint32(),o=A.readUint32(),a=A.readUint32(),B=A.readUint32(),C=A.remaining(),Q=A.readBytes(C);return new ds({timescale:n,presentationTimeDelta:o,schemeIdUri:t,value:g,eventDuration:a,id:B,data:Q})}default:throw new Error(`unsupported version ${e}`)}}};s(ds,"type","emsg");let Pn=ds;const jg=class jg{constructor(A){s(this,"type",jg.type);s(this,"data");this.data=A}static decodeData(A){const e=A.readRemaining();return new jg(e)}};s(jg,"type","mdat");let xn=jg;const zg=class zg{constructor(A,e,t){s(this,"type",zg.type);s(this,"extra");s(this,"byteOffset");s(this,"baseMediaDecodeTime");this.extra=A,this.byteOffset=e,this.baseMediaDecodeTime=t}static decodeData(A){const e=ve(A),t=A.byteOffset();let g=0;return e.version===1?g=A.readUint64():g=A.readUint32(),new zg(e,t,g)}};s(zg,"type","tfdt");let Wn=zg;const jh=1,zh=2,_h=8,$h=16,Ad=32,_g=class _g{constructor(A,e,t,g){s(this,"type",_g.type);s(this,"extra");s(this,"defaultSampleDuration");s(this,"defaultSampleSize");s(this,"defaultSampleFlags");this.extra=A,this.defaultSampleDuration=e,this.defaultSampleSize=t,this.defaultSampleFlags=g}static decodeData(A){const e=ve(A);let t,g,n;return A.readUint32(),(e.flags&jh)>0&&A.readUint64(),(e.flags&zh)>0&&A.readUint32(),(e.flags&_h)>0&&(t=A.readUint32()),(e.flags&$h)>0&&(g=A.readUint32()),(e.flags&Ad)>0&&(n=A.readUint32()),new _g(e,t,g,n)}};s(_g,"type","tfhd");let On=_g;const cA=class cA{constructor(A,e,t){s(this,"type",cA.type);s(this,"dataOffset");s(this,"firstSampleFlags");s(this,"samplesCount");s(this,"sampleDurations",[]);s(this,"sampleSizes",[]);s(this,"sampleFlags",[]);s(this,"sampleCts",[]);this.dataOffset=e,this.firstSampleFlags=t,this.samplesCount=A}is_sync_sample(A){const e=cA.FLAG_SAMPLE_FLAG_IS_NON_SYNC|cA.FLAG_SAMPLE_DEPENDS_YES,t=this.sampleFlags[A];if(typeof t!="undefined")return(t&e)===0;if(A===0&&this.firstSampleFlags)return(this.firstSampleFlags&e)===0}static decodeData(A){const{flags:e}=ve(A),t=A.readUint32();let g,n;e&cA.TRUN_DATA_OFFSET&&(g=A.readUint32()),e&cA.TRUN_FIRST_SAMPLE_FLAGS&&(n=A.readUint32());const o=new cA(t,g,n);for(let a=0;a<t;a++)e&cA.SAMPLE_DURATION&&o.sampleDurations.push(A.readUint32()),e&cA.SAMPLE_SIZE&&o.sampleSizes.push(A.readUint32()),e&cA.SAMPLE_FLAGS&&o.sampleFlags.push(A.readUint32()),e&cA.SAMPLE_CTS&&o.sampleCts.push(A.readUint32());return o}};s(cA,"TRUN_DATA_OFFSET",1),s(cA,"TRUN_FIRST_SAMPLE_FLAGS",4),s(cA,"SAMPLE_DURATION",256),s(cA,"SAMPLE_SIZE",512),s(cA,"SAMPLE_FLAGS",1024),s(cA,"SAMPLE_CTS",2048),s(cA,"FLAG_SAMPLE_FLAG_IS_NON_SYNC",65536),s(cA,"FLAG_SAMPLE_DEPENDS_NO",33554432),s(cA,"FLAG_SAMPLE_DEPENDS_YES",16777216),s(cA,"type","trun");let Rg=cA;const $g=class $g{constructor(A,e,t){s(this,"type",$g.type);s(this,"tfhd");s(this,"tfdt");s(this,"trun");this.tfhd=A,this.tfdt=e,this.trun=t}static decodeData(A){let e,t,g;for(;A.remaining()>0;){const n=Be(A);n instanceof On&&(e=n),n instanceof Wn&&(t=n),n instanceof Rg&&(g=n)}return new $g(e,t,g)}};s($g,"type","traf");let Vn=$g;const AI=class AI{constructor(A){s(this,"type",AI.type);s(this,"traf");this.traf=A}static decodeData(A){let e;for(;A.remaining()>0;){const t=Be(A);t instanceof Vn&&(e=t)}if(!e)throw new Error("No traf found");return new AI(e)}};s(AI,"type","moof");let Zn=AI;const eI=class eI{constructor(){s(this,"type",eI.type)}static decodeData(A){return new eI}};s(eI,"type","mvhd");let Xn=eI;const tI=class tI{constructor(A){s(this,"type",tI.type);s(this,"fourCC");this.fourCC=A}mediaType(){switch(this.fourCC){case"vide":return"video";case"soun":return"audio";case"sbtl":return"text";default:throw new Error("Unknown media type")}}static decodeData(A){ve(A),A.readUint32();const e=String.fromCharCode(...A.readBytes(4));return new tI(e)}};s(tI,"type","hdlr");let jn=tI;const ls=class ls{constructor(A,e,t,g){s(this,"type",ls.type);s(this,"creationTime");s(this,"modificationTime");s(this,"timescale");s(this,"duration");this.creationTime=A,this.modificationTime=e,this.timescale=t,this.duration=g}static decodeData(A){const{version:e}=ve(A);if(e===1){const a=A.readUint64(),B=A.readUint64(),C=A.readUint32(),Q=A.readUint64();return new ls(a,B,C,Q)}const t=A.readUint32(),g=A.readUint32(),n=A.readUint32(),o=A.readUint32();return new ls(t,g,n,o)}};s(ls,"type","mdhd");let zn=ls;const iI=class iI{constructor(A,e,t,g,n){s(this,"type",iI.type);s(this,"av01");s(this,"avc1");s(this,"mp4a");s(this,"opus");s(this,"codec");this.avc1=A,this.av01=e,this.mp4a=t,this.opus=g,this.codec=n}mediaType(){return this.avc1||this.av01?"video":"audio"}width(){var A;return(A=this.avc1)==null?void 0:A.width}height(){var A;return(A=this.avc1)==null?void 0:A.height}static decodeData(A){ve(A);const e=A.readUint32();let t,g,n,o,a;for(let B=0;B<e;B++)for(;A.remaining()>0;){const C=Be(A);switch(C.type){case"avc1":t="h264",g=C;break;case"av01":t="av1",a=C;break;case"mp4a":t="aac",n=C;break;case"Opus":t="opus",o=C;break}}return new iI(g,a,n,o,t)}};s(iI,"type","stsd");let _n=iI;const sI=class sI{constructor(A){s(this,"type",sI.type);s(this,"stsd");this.stsd=A}static decodeData(A){let e;for(;A.remaining()>0;){const t=Be(A);t instanceof _n&&(e=t)}if(!e)throw new Error("No stsd found");return new sI(e)}};s(sI,"type","stbl");let $n=sI;const gI=class gI{constructor(A){s(this,"type",gI.type);s(this,"stbl");this.stbl=A}static decodeData(A){let e;for(;A.remaining()>0;){const t=Be(A);t instanceof $n&&(e=t)}if(!e)throw new Error("No stbl found");return new gI(e)}};s(gI,"type","minf");let Ao=gI;const II=class II{constructor(A,e,t){s(this,"type",II.type);s(this,"hdlr");s(this,"minf");s(this,"mdhd");this.hdlr=A,this.minf=e,this.mdhd=t}static decodeData(A){let e,t,g;for(;A.remaining()>0;){const n=Be(A);n instanceof jn&&(e=n),n instanceof Ao&&(t=n),n instanceof zn&&(g=n)}if(!e)throw new Error("No hdlr found");if(!t)throw new Error("No minf found");if(!g)throw new Error("No mdhd found");return new II(e,t,g)}};s(II,"type","mdia");let eo=II;const nI=class nI{constructor(A,e,t,g,n,o,a,B){s(this,"type",nI.type);s(this,"modificationTime");s(this,"creationTime");s(this,"trackId");s(this,"duration");s(this,"alternateGroup");s(this,"volume");s(this,"width");s(this,"height");this.modificationTime=A,this.creationTime=e,this.trackId=t,this.duration=g,this.alternateGroup=n,this.volume=o,this.width=a,this.height=B}static decodeData(A){const e=ve(A);let t=0,g=0;e.version===1?(t=A.readUint64(),g=A.readUint64()):(t=A.readUint32(),g=A.readUint32());const n=A.readUint32();A.readUint32();const o=A.readUint32();A.readUint32(),A.readUint32(),A.readUint16();const a=A.readUint16(),B=A.readUint16();A.readUint16(),new Array(9).fill(0).map(()=>A.readUint32());const C=A.readUint16();A.readUint16();const Q=A.readUint16();return A.readUint16(),new nI(t,g,n,o,a,B,C,Q)}};s(nI,"type","tkhd");let to=nI;const oI=class oI{constructor(A,e){s(this,"type",oI.type);s(this,"tkhd");s(this,"mdia");this.tkhd=A,this.mdia=e}static decodeData(A){let e,t;for(;A.remaining()>0;){const g=Be(A);g instanceof to&&(e=g),g instanceof eo&&(t=g)}if(!e)throw new Error("No tkhd found");if(!t)throw new Error("No mdia found");return new oI(e,t)}};s(oI,"type","trak");let io=oI;const aI=class aI{constructor(A,e){s(this,"type",aI.type);s(this,"mvhd");s(this,"traks");this.mvhd=A,this.traks=e}static decodeData(A){let e;const t=[];for(;A.remaining()>0;){const g=Be(A);g instanceof io&&t.push(g),g instanceof Xn&&(e=g)}if(!e)throw new Error("No mvhd found");return new aI(e,t)}};s(aI,"type","moov");let so=aI;const BI=class BI{constructor(A,e,t,g,n,o,a,B){s(this,"type",BI.type);s(this,"configurationVersion");s(this,"avcProfileIndication");s(this,"profileCompatibility");s(this,"avcLevelIndication");s(this,"lengthSizeMinusOne");s(this,"sequenceParameterSets");s(this,"pictureParameterSets");s(this,"bytes");this.configurationVersion=A,this.avcProfileIndication=e,this.profileCompatibility=t,this.avcLevelIndication=g,this.lengthSizeMinusOne=n,this.sequenceParameterSets=o,this.pictureParameterSets=a,this.bytes=B}static decodeData(A){const e=A.buffer(),t=A.readUint8(),g=A.readUint8(),n=A.readUint8(),o=A.readUint8(),a=A.readUint8()&3,B=A.readUint8()&31,C=[];for(let d=0;d<B;d++){const u=A.readBytes(A.readUint16());C.push(u)}const Q=A.readUint8(),h=[];for(let d=0;d<Q;d++){const u=A.readBytes(A.readUint16());h.push(u)}return new BI(t,g,n,o,a,C,h,e)}};s(BI,"type","avcC");let $a=BI;const rI=class rI{constructor(A,e,t,g,n){s(this,"type",rI.type);s(this,"avcC");s(this,"width");s(this,"height");s(this,"horizontalResolution");s(this,"verticalResolution");this.avcC=A,this.width=e,this.height=t,this.horizontalResolution=g,this.verticalResolution=n}static decodeData(A){A.readUint32(),A.readUint16(),A.readUint16(),A.readUint32(),A.readUint64(),A.readUint32();const e=A.readUint16(),t=A.readUint16(),g=A.readUint32(),n=A.readUint32();A.readUint32(),A.readUint16(),A.readBytes(32),A.readUint16(),A.readUint16();let o;for(;A.remaining()>0;){const a=Be(A);a.type==="avcC"&&(o=a)}if(!o)throw new Error("no avcC");return new rI(o,e,t,g,n)}};s(rI,"type","avc1");let AB=rI;const ed=i=>{for(let A=0;A<i.length-1;A++){if(i[A]!==5)continue;let e=0,t=0,g=A+1;for(;g<i.length&&t<4;){const a=i[g];if(e=e<<7|a&127,t++,g++,(a&128)===0)break}if(e<=0||t===4&&(i[g-1]&128)!==0)continue;const n=A+1+t,o=n+e;if(o<=i.length)return i.slice(n,o)}},CI=class CI{constructor(A){s(this,"type",CI.type);s(this,"decoderConfig");this.decoderConfig=A}static decodeData(A){var g;ve(A);const e=A.readRemaining(),t=(g=ed(e))!=null?g:new Uint8Array(0);return new CI(t)}};s(CI,"type","esds");let eB=CI;const QI=class QI{constructor(A,e,t){s(this,"type",QI.type);s(this,"channelCount");s(this,"sampleRate");s(this,"esds");this.channelCount=A,this.sampleRate=e,this.esds=t}static decodeData(A){A.readUint32(),A.readUint16(),A.readUint16();const e=A.readUint16();A.readUint16(),A.readUint32();const t=A.readUint16();A.readUint16(),A.readUint32();const g=A.readUint16();A.readUint16(),e===1?A.readBytes(16):e===2&&A.readBytes(36);let n;for(;A.remaining()>0;){const o=Be(A);o.type==="esds"&&(n=o)}return new QI(t,g,n)}};s(QI,"type","mp4a");let tB=QI;const EI=class EI{constructor(A,e,t,g,n,o,a){s(this,"type",EI.type);s(this,"version");s(this,"channelCount");s(this,"preSkip");s(this,"inputSampleRate");s(this,"outputGain");s(this,"channelMappingFamily");s(this,"channelMappingTable");this.version=A,this.channelCount=e,this.preSkip=t,this.inputSampleRate=g,this.outputGain=n,this.channelMappingFamily=o,this.channelMappingTable=a}static decodeData(A){const e=A.readUint8(),t=A.readUint8(),g=A.readUint16(),n=A.readUint32(),o=A.readUint16(),a=o>32767?o-65536:o,B=A.readUint8(),C=A.readRemaining();return new EI(e,t,g,n,a,B,C)}};s(EI,"type","dOps");let iB=EI;const cI=class cI{constructor(A,e,t){s(this,"type",cI.type);s(this,"dops");s(this,"channelCount");s(this,"sampleRate");this.dops=A,this.channelCount=e,this.sampleRate=t}static decodeData(A){A.readUint32(),A.readUint16(),A.readUint16();const e=A.readUint16();A.readUint16(),A.readUint32();const t=A.readUint16();A.readUint16(),A.readUint32();const g=A.readUint16();A.readUint16(),e===1&&(A.readUint64(),A.readUint64());const n=Xh(iB,A);return new cI(n,t,g)}};s(cI,"type","Opus");let sB=cI;const us=class us{constructor(A,e){s(this,"type",us.type);s(this,"ntpTimestamp");s(this,"mediaTime");this.ntpTimestamp=A,this.mediaTime=e}date(){const[A,e]=this.ntpTimestamp,t=A*1e3+e/2**32*1e3,g=new Date(Date.UTC(1900,0,1,0,0,0));return new Date(g.getTime()+t)}static decodeData(A){const{version:e}=ve(A);A.readUint32();const t=A.readUint32(),g=A.readUint32();if(e===1){const o=A.readUint64();return new us([t,g],o)}const n=A.readUint32();return new us([t,g],n)}};s(us,"type","prft");let go=us;class td{constructor(A,e){r(this,hI);r(this,dI);E(this,hI,A),E(this,dI,e.readBytes(A.size))}data(){return I(this,dI)}get type(){return I(this,hI).type}}hI=new WeakMap,dI=new WeakMap;const id={moov:so,trak:io,tkhd:to,mvhd:Xn,moof:Zn,traf:Vn,tfhd:On,tfdt:Wn,trun:Rg,mdat:xn,mdia:eo,hdlr:jn,minf:Ao,stbl:$n,mdhd:zn,stsd:_n,prft:go,avc1:AB,avcC:$a,esds:eB,mp4a:tB,Opus:sB,emsg:Pn};function Be(i){const A=vC(i),e=id[A.type],t=new Je(i.readBytes(A.size));if(!e){const n=new td(A,t);return t.readRemaining(),n}const g=e.decodeData(t);return t.readRemaining(),g}function sd(i){if(i.byteLength<8)throw new Error("Buffer too small");const A=new Je(i),e=new Map;for(;A.remaining()>0;){const n=Be(A);e.set(n.type,n)}const t=e.get("ftyp"),g=e.get("moov");if(!t)throw new Error("ftyp atom not found");if(!g||!(g instanceof so))throw new Error("moov atom not found");return{ftyp:t,moov:g}}function gd(i){if(i.byteLength<8)throw new Error("Buffer too small");const A=new Je(i),e=new Map,t=[];for(;A.remaining()>0;){const a=Be(A);a instanceof Pn&&t.push(a),e.set(a.type,a)}const g=e.get("moof"),n=e.get("mdat"),o=e.get("prft");if(!g||!(g instanceof Zn))throw new Error("moof atom not found");if(!n||!(n instanceof xn))throw new Error("mdat atom not found");if(o&&!(o instanceof go))throw new Error("invalid prft found");return{moof:g,mdat:n,prft:o,emsgs:t}}class Id{constructor(A){r(this,lI);r(this,uI);E(this,lI,A),E(this,uI,sd(A))}rawBytes(){return I(this,lI)}init(){return I(this,uI)}}lI=new WeakMap,uI=new WeakMap;const ar=class ar{constructor(A,e){r(this,OA);r(this,se);r(this,nA);E(this,OA,e),E(this,se,A),E(this,nA,gd(e))}clone(){return new ar(I(this,se),new Uint8Array(I(this,OA).buffer.slice(I(this,OA).byteOffset,I(this,OA).byteOffset+I(this,OA).byteLength)))}updateBaseMediaDecodeTime(A){const e=new DataView(I(this,OA).buffer,I(this,OA).byteOffset,I(this,OA).byteLength);if(I(this,nA).moof.traf.tfdt)if(I(this,nA).moof.traf.tfdt.baseMediaDecodeTime=A,I(this,nA).moof.traf.tfdt.extra.version===1){const t=Math.floor(A/4294967296),g=(A&4294967295)>>>0;e.setUint32(I(this,nA).moof.traf.tfdt.byteOffset-I(this,OA).byteOffset,t),e.setUint32(I(this,nA).moof.traf.tfdt.byteOffset-I(this,OA).byteOffset+4,g)}else e.setUint32(I(this,nA).moof.traf.tfdt.byteOffset-I(this,OA).byteOffset,A)}producerReferenceTime(){if(I(this,nA).prft)return I(this,nA).prft.date()}duration(){const A=I(this,nA).moof.traf.trun,e=I(this,nA).moof.traf.tfhd;if((A==null?void 0:A.sampleDurations.length)===0){const t=(A==null?void 0:A.samplesCount)||1;if(e!=null&&e.defaultSampleDuration)return(e==null?void 0:e.defaultSampleDuration)*t}return(A==null?void 0:A.sampleDurations.reduce((t,g)=>t+g,0))||0}baseMediaDecodeTime(){var e;const A=(e=I(this,nA).moof.traf.tfdt)==null?void 0:e.baseMediaDecodeTime;if(!A)throw new Error("no baseMediaDecodeTime");return A}startsWithKeyframe(){var t;const A=I(this,nA).moof.traf.trun,e=(A==null?void 0:A.firstSampleFlags)||(A==null?void 0:A.sampleFlags[0])||((t=I(this,nA).moof.traf.tfhd)==null?void 0:t.defaultSampleFlags);return e?(e&Rg.FLAG_SAMPLE_DEPENDS_NO)!==0:!1}compositionTimeOffset(A){var e;return(e=I(this,nA).moof.traf.trun)==null?void 0:e.sampleCts[A]}timescale(){const A=I(this,se).init().moov.traks[0];if(!A)throw new Error("no tracks");return A.mdia.mdhd.timescale}mediaType(){var e;const A=(e=I(this,se).init().moov.traks[0])==null?void 0:e.mdia.hdlr.mediaType();if(!A)throw new Error("no media type");return A}header(){return I(this,se)}fragment(){return I(this,nA)}samplesCount(){var A;return((A=I(this,nA).moof.traf.trun)==null?void 0:A.samplesCount)||0}sample(A){var p,y,k,N,U,K,W,Z,j,QA,NA,ee,qA,XA,jA,Xt;const e=(p=I(this,se).init().moov.traks[0])==null?void 0:p.mdia.minf.stbl.stsd.codec,t=((y=I(this,nA).moof.traf.trun)==null?void 0:y.samplesCount)||0,g=(k=I(this,nA).moof.traf.tfdt)==null?void 0:k.baseMediaDecodeTime;if(A>=t||typeof g=="undefined"||!e)return;const n=this.compositionTimeOffset(A),o=((N=I(this,nA).moof.traf.trun)==null?void 0:N.sampleDurations[A])||0,a=((U=I(this,nA).moof.traf.trun)==null?void 0:U.sampleDurations.slice(0,A).reduce((le,D)=>le+D,0))||0,B=g+a,C=((K=I(this,se).init().moov.traks[0])==null?void 0:K.mdia.mdhd.timescale)||1e3,Q=((W=I(this,nA).moof.traf.trun)==null?void 0:W.sampleSizes[A])||I(this,nA).mdat.data.byteLength,h=((Z=I(this,nA).moof.traf.trun)==null?void 0:Z.sampleSizes.slice(0,A).reduce((le,D)=>le+D,0))||0,d=I(this,nA).mdat.data.subarray(h,h+Q),u=((j=I(this,nA).moof.traf.trun)==null?void 0:j.is_sync_sample(A))||!1;if(this.mediaType()==="video"){const le=((QA=I(this,se).init().moov.traks[0])==null?void 0:QA.tkhd.width)||0,D=((NA=I(this,se).init().moov.traks[0])==null?void 0:NA.tkhd.height)||0;return{type:"video",codec:e,width:le,height:D,duration:o,isSync:u,timescale:C,timestamp:B,compositionTimeOffset:n,data:d}}const m=(ee=I(this,se).init().moov.traks[0])==null?void 0:ee.mdia.minf.stbl.stsd;return{type:"audio",codec:e,channels:((qA=m==null?void 0:m.opus)==null?void 0:qA.channelCount)||((XA=m==null?void 0:m.mp4a)==null?void 0:XA.channelCount)||0,sampleRate:((jA=m==null?void 0:m.opus)==null?void 0:jA.sampleRate)||((Xt=m==null?void 0:m.mp4a)==null?void 0:Xt.sampleRate)||0,duration:o,isSync:u,timestamp:B,compositionTimeOffset:n,data:d,timescale:C}}rawBytes(){return I(this,OA)}};OA=new WeakMap,se=new WeakMap,nA=new WeakMap;let gB=ar;class HC{constructor(A){r(this,ms);E(this,ms,new Id(A))}header(){return I(this,ms)}createFragment(A){return new gB(I(this,ms),A)}}ms=new WeakMap;function H(i){const A=new ArrayBuffer(i.length),e=new Uint8Array(A);for(let t=0,g=i.length;t<g;t++)e[t]=i.charCodeAt(t);return new Uint8Array(A)}const AA={ftyp:H("ftyp"),mvhd:H("mvhd"),moov:H("moov"),trak:H("trak"),tkhd:H("tkhd"),mdia:H("mdia"),mdhd:H("mdhd"),hdlr:H("hdlr"),minf:H("minf"),vmhd:H("vmhd"),smhd:H("smhd"),dinf:H("dinf"),dref:H("dref"),stbl:H("stbl"),stsd:H("stsd"),avc1:H("avc1"),av01:H("av01"),av1C:H("av1C"),avcC:H("avcC"),esds:H("esds"),colr:H("colr"),nclx:H("nclx"),mvex:H("mvex"),trex:H("trex"),udta:H("udta"),meta:H("meta"),ilst:H("ilst"),moof:H("moof"),mfhd:H("mfhd"),traf:H("traf"),tfhd:H("tfhd"),tfdt:H("tfdt"),trun:H("trun"),mdat:H("mdat"),mp4a:H("mp4a"),Opus:H("Opus"),prft:H("prft"),dOps:H("dOps"),emsg:H("emsg")},nd=1e3,re={vide:H("vide"),soun:H("soun"),videoHandler:H("VideoHandler\0"),soundHandler:H("SoundHandler\0"),url:H("url "),pasp:H("pasp"),btrt:H("btrt"),stts:H("stts"),stsc:H("stsc"),stsz:H("stsz"),stco:H("stco"),data:H("data"),mdir:H("mdir"),appl:H("appl")},Gg=H("iso6"),qC=new Uint8Array([0,0,2,0]),od=[Gg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([97,118,99,49]),new Uint8Array([109,112,52,49])],ad=[Gg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([97,118,48,49]),new Uint8Array([109,112,52,49])],Bd=[Gg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([109,112,52,49])];class KC{constructor(A){s(this,"writer");s(this,"moofOffset",0);this.writer=new Qc(A)}}const uA=(i,A,e)=>{i.writer.writeUint32(e+8),i.writer.writeBytes(A)},fA=(i,A,e,t,g)=>{uA(i,A,e+4),i.writer.writeUint8(t),i.writer.writeUint24(g)},IB=(i,A)=>{uA(i,AA.ftyp,Gg.byteLength+qC.byteLength+A.reduce((e,t)=>e+t.byteLength,0)),i.writer.writeBytes(Gg),i.writer.writeBytes(qC),A.forEach(e=>i.writer.writeBytes(e))},rd=2**32,Cd=2208988800,Qd=(i,A,e,t)=>{fA(i,AA.prft,20,1,0);const n=e/1e3,o=Math.floor(n),B=(n-o)*1e3*1e3*rd/1e6;i.writer.writeUint32(A),i.writer.writeUint32(o+Cd),i.writer.writeUint32(B),i.writer.writeUint64(t)},Ed=(i,A,e)=>{fA(i,AA.mvhd,96,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(e),i.writer.writeUint32(A),i.writer.writeUint32(65536),i.writer.writeUint16(256),i.writer.writeBytes(new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])),i.writer.writeUint32(2)},TC=i=>"sequenceParameterSets"in i,nB=i=>"sequenceHeader"in i,si=i=>i.type=="video",Ug=i=>i.type=="audio",cd=(i,A,e)=>{const t=i.writer.position();fA(i,AA.tkhd,0,0,3),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(A.trackId),i.writer.writeUint32(0),i.writer.writeUint32(A.duration*e/A.timescale),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint16(0),i.writer.writeUint16(Ug(A)?1:0),i.writer.writeUint16(Ug(A)?256:0),i.writer.writeUint16(0),i.writer.writeBytes(new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0])),si(A)?(i.writer.writeUint32(A.width*65536),i.writer.writeUint32(A.height*65536)):Ug(A)&&(i.writer.writeUint32(0),i.writer.writeUint32(0)),i.writer.writeUint32At(t,i.writer.position()-t)},hd=(i,A)=>{fA(i,AA.mdhd,20,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(A.timescale),i.writer.writeUint32(A.duration);const e=A.lang||"und",t=(e.charCodeAt(0)&31)<<10|(e.charCodeAt(1)&31)<<5|e.charCodeAt(2)&31;i.writer.writeUint16(t),i.writer.writeUint16(0)},dd=(i,A)=>{const e=i.writer.position();fA(i,AA.hdlr,0,0,0),i.writer.writeUint32(0),i.writer.writeBytes(si(A)?re.vide:re.soun),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeBytes(si(A)?re.videoHandler:re.soundHandler),i.writer.writeUint32At(e,i.writer.position()-e)},ld=i=>{const A=i.writer.position();uA(i,AA.dinf,0),fA(i,AA.dref,16,0,0),i.writer.writeUint32(1),fA(i,re.url,0,0,1),i.writer.writeUint32At(A,i.writer.position()-A)},ud=(i,A)=>{const e=i.writer.position();uA(i,AA.avcC,0),i.writer.writeUint8(1),i.writer.writeUint8(A.sequenceParameterSets[0][1]),i.writer.writeUint8(A.sequenceParameterSets[0][2]),i.writer.writeUint8(A.sequenceParameterSets[0][3]),i.writer.writeUint8(255),i.writer.writeUint8(224|A.sequenceParameterSets.length),A.sequenceParameterSets.forEach(t=>{i.writer.writeUint16(t.byteLength),i.writer.writeBytes(t)}),i.writer.writeUint8(A.pictureParameterSets.length),A.pictureParameterSets.forEach(t=>{i.writer.writeUint16(t.byteLength),i.writer.writeBytes(t)}),i.writer.writeUint32At(e,i.writer.position()-e)},md=(i,A)=>{var a,B;const e=i.writer.position();uA(i,AA.av1C,0);const{seqProfile:t,operatingPoints:g,colorConfig:n}=A.parsedSequenceHeader,o=g[0];i.writer.writeUint8(129),i.writer.writeUint8(t<<5|((a=o==null?void 0:o.seqLevelIdx)!=null?a:0)),i.writer.writeUint8(((B=o==null?void 0:o.tier)!=null?B:0)|(n.highBitDepth?1:0)|(n.bitDepth===12?1:0)<<5|(n.monoChrome?1:0)<<4|n.subsamplingX<<3|n.subsamplingY<<2|n.chromaSamplePosition&65535),i.writer.writeUint8(0),i.writer.writeBytes(A.sequenceHeader),i.writer.writeUint32At(e,i.writer.position()-e)},wd=(i,A)=>{const e=i.writer.position(),t=nB(A)?AA.av01:AA.avc1;uA(i,t,0),i.writer.writeUint32(0),i.writer.writeUint16(0),i.writer.writeUint16(1),i.writer.writeUint16(0),i.writer.writeUint16(0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint16(A.width),i.writer.writeUint16(A.height),i.writer.writeUint32(4718592),i.writer.writeUint32(4718592),i.writer.writeUint32(0),i.writer.writeUint16(1),i.writer.writeUint8(0),i.writer.writeBytes(new Uint8Array(31)),i.writer.writeUint16(24),i.writer.writeUint16(-1),TC(A)?ud(i,A):nB(A)&&(md(i,A),A.parsedSequenceHeader.colorConfig&&(uA(i,AA.colr,11),i.writer.writeBytes(AA.nclx),i.writer.writeUint16(A.parsedSequenceHeader.colorConfig.colorPrimaries),i.writer.writeUint16(A.parsedSequenceHeader.colorConfig.transferCharacteristics),i.writer.writeUint16(A.parsedSequenceHeader.colorConfig.matrixCoefficients),i.writer.writeUint8(A.parsedSequenceHeader.colorConfig.colorRange?1:0))),A.pixelAspectRatio&&(uA(i,re.pasp,8),i.writer.writeUint32(A.pixelAspectRatio.numerator),i.writer.writeUint32(A.pixelAspectRatio.denumerator)),A.bitrate&&(uA(i,re.btrt,12),i.writer.writeUint32(0),i.writer.writeUint32(A.bitrate),i.writer.writeUint32(A.bitrate)),i.writer.writeUint32At(e,i.writer.position()-e)},Io=(i,A,e)=>{let t=3;for(i.writer.writeUint8(A);t>0;t--)i.writer.writeUint8(e>>7*t|128);i.writer.writeUint8(e&127)},fd=(i,A)=>{const e=A.decoderConfig.byteLength>0?A.decoderConfig.byteLength+5:0,t=i.writer.position();fA(i,AA.esds,0,0,0),Io(i,3,21+e+5+1),i.writer.writeUint16(A.trackId),i.writer.writeUint8(0),Io(i,4,13+e);const g=A.codec==="mp3"&&A.sampleRate>24e3?107:64;i.writer.writeUint8(g),i.writer.writeUint8(21),i.writer.writeUint24(0),i.writer.writeUint32(A.bitrate||0),i.writer.writeUint32(A.bitrate||0),A.decoderConfig.byteLength>0&&(Io(i,5,A.decoderConfig.byteLength),i.writer.writeBytes(A.decoderConfig)),Io(i,6,1),i.writer.writeUint8(2),i.writer.writeUint32At(t,i.writer.position()-t)},Dd=i=>{switch(i){case"aac":case"mp3":return AA.mp4a;case"opus":return AA.Opus}},Sd=(i,A)=>{const e=i.writer.position();uA(i,AA.dOps,0),i.writer.writeUint8(0);const t=A.decoderConfig,g=new DataView(t.buffer,t.byteOffset,t.byteLength);i.writer.writeUint8(g.getUint8(9)),i.writer.writeUint16(g.getUint16(10,!0)),i.writer.writeUint32(g.getUint32(12,!0)),i.writer.writeUint16(g.getUint16(16,!0)),i.writer.writeBytes(A.decoderConfig.slice(18)),i.writer.writeUint32At(e,i.writer.position()-e)},pd=(i,A)=>{const e=i.writer.position();switch(uA(i,Dd(A.codec),0),i.writer.writeUint32(0),i.writer.writeUint16(0),i.writer.writeUint16(1),i.writer.writeUint16(0),i.writer.writeUint16(0),i.writer.writeUint32(0),i.writer.writeUint16(A.channelCount),i.writer.writeUint16(16),i.writer.writeUint32(0),i.writer.writeUint16(A.sampleRate),i.writer.writeUint16(0),A.codec){case"aac":case"mp3":fd(i,A);break;case"opus":Sd(i,A);break}A.bitrate&&(uA(i,re.btrt,12),i.writer.writeUint32(0),i.writer.writeUint32(A.bitrate),i.writer.writeUint32(A.bitrate)),i.writer.writeUint32At(e,i.writer.position()-e)},yd=(i,A)=>{const e=i.writer.position();uA(i,AA.stbl,0);const t=i.writer.position();fA(i,AA.stsd,0,0,0),i.writer.writeUint32(1),si(A)?wd(i,A):Ug(A)&&pd(i,A),i.writer.writeUint32At(t,i.writer.position()-t),fA(i,re.stts,4,0,0),i.writer.writeUint32(0),fA(i,re.stsc,4,0,0),i.writer.writeUint32(0),fA(i,re.stsz,8,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),fA(i,re.stco,4,0,0),i.writer.writeUint32(0),i.writer.writeUint32At(e,i.writer.position()-e)},Fd=(i,A)=>{const e=i.writer.position();uA(i,AA.minf,0),si(A)?(fA(i,AA.vmhd,8,0,1),i.writer.writeUint32(0),i.writer.writeUint32(0)):Ug(A)&&(fA(i,AA.smhd,4,0,0),i.writer.writeUint16(0),i.writer.writeUint16(0)),ld(i),yd(i,A),i.writer.writeUint32At(e,i.writer.position()-e)},kd=(i,A)=>{const e=i.writer.position();uA(i,AA.mdia,0),hd(i,A),dd(i,A),Fd(i,A),i.writer.writeUint32At(e,i.writer.position()-e)},Rd=(i,A,e)=>{const t=i.writer.position();uA(i,AA.trak,0),cd(i,A,e),kd(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Gd=(i,A)=>{fA(i,AA.trex,20,0,0),i.writer.writeUint32(A.trackId),i.writer.writeUint32(1),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(0)},Ud=(i,A)=>{const e=i.writer.position();uA(i,AA.mvex,0),A.forEach(t=>Gd(i,t)),i.writer.writeUint32At(e,i.writer.position()-e)},bd=(i,A,e,t)=>{const g=i.writer.position();uA(i,AA.moov,0),Ed(i,0,e),A.forEach(n=>Rd(i,n,e)),Ud(i,A),i.writer.writeUint32At(g,i.writer.position()-g)},Nd=(i,A)=>{const e=i.writer.position();fA(i,AA.tfhd,16,0,56),i.writer.writeUint32(A.trackId),i.writer.writeUint32(A.defaultDuration||0),i.writer.writeUint32(A.defaultSize||0),i.writer.writeUint32(A.defaultFlags||0),i.writer.writeUint32At(e,i.writer.position()-e)},Ld=(i,A)=>{const e=i.writer.position();fA(i,AA.tfdt,8,1,0);const t=Math.floor(A.timestamp/4294967296),g=(A.timestamp&4294967295)>>>0;i.writer.writeUint32(t),i.writer.writeUint32(g),i.writer.writeUint32At(e,i.writer.position()-e)},Jd=(i,A)=>{if(!A.samples[0])throw new Error("At least one sample must be provided");const e=A.samples.some(B=>!!B.compositionTimeOffset),t=oB(A.samples[0])!==A.defaultFlags,g=A.samples.length>1;let n=1;t&&(n|=4),e&&(n|=2048),g&&(n|=512,n|=256,n|=1024);const o=i.writer.position();fA(i,AA.trun,16,1,n),i.writer.writeUint32(A.samples.length);const a=i.writer.position();i.writer.writeUint32(0),t&&i.writer.writeUint32(oB(A.samples[0]));for(const B of A.samples)g&&(i.writer.writeUint32(B.duration),i.writer.writeUint32(B.data.byteLength),i.writer.writeUint32(oB(B))),e&&i.writer.writeUint32(B.compositionTimeOffset||0);i.writer.writeUint32At(a,i.writer.position()-i.moofOffset+8),i.writer.writeUint32At(o,i.writer.position()-o)},oB=i=>i.isSync?33554432:16842752,Md=(i,A)=>{const e=i.writer.position();uA(i,AA.traf,0),Nd(i,A),Ld(i,A),Jd(i,A),i.writer.writeUint32At(e,i.writer.position()-e)},vd=(i,A)=>{fA(i,AA.mfhd,4,0,0),i.writer.writeUint32(A)},Hd=(i,A)=>{const e=i.writer.position();uA(i,AA.moof,0),vd(i,A.sequenceNumber),Md(i,A),i.writer.writeUint32At(e,i.writer.position()-e)},qd=(i,A,e)=>{uA(i,AA.mdat,e);for(const t of A.samples){const g=t.data instanceof ArrayBuffer?new Uint8Array(t.data):t.data;i.writer.writeBytes(g)}},no=(i,A)=>{const e=new KC,t=i.filter(n=>si(n)&&TC(n)).length>0;return i.filter(n=>si(n)&&nB(n)).length>0?IB(e,ad):t?IB(e,od):IB(e,Bd),bd(e,i,nd),e.writer.buffer()},oo=i=>{var t;let A=0;for(const g of i.samples)A+=g.data.byteLength;const e=new KC(A+256);return((t=i.samples[0])==null?void 0:t.producerReferenceTime)!==void 0&&Qd(e,i.trackId,i.samples[0].producerReferenceTime,i.timestamp),e.moofOffset=e.writer.position(),Hd(e,i),qd(e,i,A),e.writer.bufferExact()},Kd=(i,A)=>{const e=i[0];if(!e)throw new Error("At least one sample must be provided");return oo({trackId:1,timestamp:e.timestamp,sequenceNumber:A,defaultSize:e.data.byteLength,defaultFlags:33554432,defaultDuration:e.duration,samples:i})},Td=(i,A,e,t)=>no([{type:"audio",codec:"aac",decoderConfig:i,channelCount:A,sampleRate:e,timescale:t,duration:0,trackId:1}]),YC=i=>{const{sequenceParameterSets:A,pictureParameterSets:e}=MC(i),t=A[0],g=e[0];if(!t||!g)throw new Error("No sps or pps provided");return Th(t)},Yd=(i,A)=>{const e=i[0];if(!e)throw new Error("At least one sample must be provided");return oo({trackId:1,timestamp:e.timestamp,sequenceNumber:A,defaultSize:e.data.byteLength,defaultFlags:e.isSync?33554432:16842752,defaultDuration:e.duration,samples:i})},Pd=(i,A)=>{const{sequenceParameterSets:e,pictureParameterSets:t}=MC(i),g=YC(i);return no([{type:"video",sequenceParameterSets:e.map(n=>new Uint8Array(n)),pictureParameterSets:t.map(n=>new Uint8Array(n)),width:g.width,height:g.height,timescale:A,duration:0,trackId:1}])},xd=(i,A,e)=>no([{type:"audio",trackId:1,channelCount:A,timescale:e,codec:"opus",decoderConfig:i,duration:0,sampleRate:48e3}]),Wd=(i,A)=>{const e=i[0];if(!e)throw new Error("At least one sample must be provided");return oo({trackId:1,timestamp:e.timestamp,sequenceNumber:A,defaultSize:e.data.byteLength,defaultFlags:33554432,defaultDuration:e.duration,samples:i})},Od=i=>{if(i.length<=78)return;let e=78;for(;e+8<=i.length;){const t=new DataView(i.buffer,i.byteOffset+e,8),g=t.getUint32(0),n=String.fromCharCode(t.getUint8(4),t.getUint8(5),t.getUint8(6),t.getUint8(7));if(g<8||e+g>i.length)break;if(n==="av1C")return i.slice(e+8,e+g);e+=g}},PC=i=>{const A=new ts(i);return A.peekBit()===1&&A.readBits(32),Xd(A),il(A)},Vd=i=>{let A=0,e=0;for(let t=0;t<8;t++){const g=i.readBits(8);if(A|=(g&127)<<t*7,e+=1,(g&128)!==128)break}return[e,A]},Zd=i=>{let A=0;for(;A<100&&i.readBit()===0;)A++;return A>=32?0:i.readBits(A)+(1<<A)-1},Xd=i=>{const A=i.remainingBits()/8,e=i.readBits(8);if((e>>7&1)!==0)return;const g=e>>3&15,n=e>>2&1,o=e>>1&1;n==1&&i.readBits(8);const[a,B]=o?Vd(i):[0,A];return{headerLength:1+n+a,type:g,obuSize:B}},jd=i=>{const A=i.readBits(32),e=i.readBits(32),t=i.readBit()!==0;let g=0;return t&&(g=Zd(i)+1),{timescale:e,equalPictureInterval:t,numUnitsInDisplayTick:A,numTicksPerPicture:g}},xC=2,aB=2,zd=1,_d=2,$d=2,Al=13,el=0,tl=2,WC=0,il=i=>{const A=i.readBits(3),e=i.readBit()!==0,t=i.readBit()!==0;let g,n=!1,o=!1,a=!1,B=0,C=0;const Q=[];if(t)i.readBits(5);else{if(o=i.readBit()!==0,o&&(g=jd(i),n=i.readBit()!==0,n))throw new Error("Not implemented");a=i.readBit()!==0;const L=i.readBits(5)+1;for(let z=0;z<L;z++){const F=i.readBits(12),b=i.readBits(5);let v=0;if(b>7&&(v=i.readBit()),n)throw new Error("decoderModelInfoPresentFlag==1");a&&i.readBit()!==0&&i.readBits(4),Q.push({tier:v,operatingPointIdc:F,seqLevelIdx:b})}}const h=i.readBits(4)+1,d=i.readBits(4)+1,u=i.readBits(h)+1,m=i.readBits(d)+1;let p=!1;t?p=!1:p=i.readBit()!==0,p&&(B=i.readBits(4)+2,C=i.readBits(3)+1);const y=i.readBit()!==0,k=i.readBit()!==0,N=i.readBit()!==0;let U=!1,K=!1,W=!1,Z=!1,j=!1,QA=!1,NA=!1,ee=xC,qA=aB,XA=0;t||(U=i.readBit()!==0,K=i.readBit()!==0,W=i.readBit()!==0,Z=i.readBit()!==0,j=i.readBit()!==0,j&&(QA=i.readBit()!==0,NA=i.readBit()!==0),i.readBit()!==0?ee=xC:ee=i.readBit(),ee>0?i.readBit()>0?qA=aB:qA=i.readBit():qA=aB,j?XA=i.readBits(3):XA=0);const jA=i.readBit()!==0,Xt=i.readBit()!==0,le=i.readBit()!==0;return{seqProfile:A,stillPicture:e,reducedStillPictureHeader:t,timingInfoPresentFlag:o,timingInfo:g!=null?g:{equalPictureInterval:!1,numUnitsInDisplayTick:0,timescale:0,numTicksPerPicture:0},decoderModelInfoPresentFlag:n,initialDisplayDelayPresentFlag:a,operatingPoints:Q,frameWidthBits:h,frameHeightBits:d,maxFrameWidth:u,maxFrameHeight:m,frameIdNumbersPresentFlag:p,deltaFrameIdLength:B,additionalFrameIdLength:C,use_128x128Superblock:y,enableFilterIntra:k,enableIntraEdgeFilter:N,enableInterintraCompound:U,enableMaskedCompound:K,enableWarpedMotion:W,enableDualFilter:Z,enableOrderHint:j,enableJntComp:QA,enableRefFrameMvs:NA,seqForceScreenContentTools:ee,seqForceIntegerMv:qA,orderHintBits:XA,enableSuperres:jA,enableCdef:Xt,enableRestoration:le,colorConfig:sl(i,A),filmGrainParamsPresent:i.readBit()!==0}},sl=(i,A)=>{const e=i.readBit()!==0;let t=8,g=!1;A===2&&e?t=i.readBit()!==0?12:10:A<=2&&(t=e?10:8),A===1?g=!1:g=i.readBit()!==0;const n=g?1:3,o=i.readBit()!==0;let a=_d,B=$d,C=tl,Q=!1,h=0,d=0,u=WC,m=!1;return o&&(a=i.readBits(8),B=i.readBits(8),C=i.readBits(8)),g?(Q=i.readBit()!==0,h=1,d=1,u=WC,m=!1,{highBitDepth:e,bitDepth:t,monoChrome:g,chromaSamplePosition:u,colorPrimaries:a,colorRange:Q,matrixCoefficients:C,numPlanes:n,separateUvDeltaQ:m,subsamplingX:h,subsamplingY:d,transferCharacteristics:B}):a===zd&&B==Al&&C==el?(Q=!0,h=0,d=0,{highBitDepth:e,bitDepth:t,monoChrome:g,chromaSamplePosition:u,colorPrimaries:a,colorRange:Q,matrixCoefficients:C,numPlanes:n,separateUvDeltaQ:m,subsamplingX:h,subsamplingY:d,transferCharacteristics:B}):(Q=i.readBit()!==0,A===0?(h=1,d=1):A===1?(h=0,d=0):t===12?(h=i.readBit(),h!==0?d=i.readBit():d=0):(h=1,d=0),h!==0&&d!==0&&(u=i.readBits(2)),m=i.readBit()!==0,{highBitDepth:e,bitDepth:t,monoChrome:g,chromaSamplePosition:u,colorPrimaries:a,colorRange:Q,matrixCoefficients:C,numPlanes:n,separateUvDeltaQ:m,subsamplingX:h,subsamplingY:d,transferCharacteristics:B})},gl=i=>{const A=PC(i);if(A)return{width:A.maxFrameWidth,height:A.maxFrameHeight}},Il=(i,A)=>{const e=i[0];if(!e)throw new Error("At least one sample must be provided");return oo({trackId:1,timestamp:e.timestamp,sequenceNumber:A,defaultSize:e.data.byteLength,defaultFlags:e.isSync?33554432:16842752,defaultDuration:e.duration,samples:i})},nl=(i,A)=>{const e=PC(i);if(!e)throw new Error("Failed to parse sequence header");return no([{type:"video",parsedSequenceHeader:e,sequenceHeader:new Uint8Array(i),width:e.maxFrameWidth,height:e.maxFrameHeight,timescale:A,duration:0,trackId:1}])},ol=i=>{const{codec:A,initData:e,timescale:t}=i;switch(A){case"h264":return Bl(e,t);case"av1":return rl(e,t);case"opus":return Cl(e,t,i.channelCount||2);case"aac":return Ql(e,t,i.channelCount||2);default:throw new Error(`Failed to initialize ${A} segment`)}},al=(i,A)=>{switch(i){case"h264":return YC(A);case"av1":return gl(A)}},Bl=(i,A)=>Pd(i,A),rl=(i,A)=>nl(i,A),Cl=(i,A,e)=>xd(new Uint8Array(i),e,A),Ql=(i,A,e)=>Td(new Uint8Array(i),e,A,A),El=(i,A)=>{if(!i[0])throw new Error("At least one sample must be provided");switch(i[0].codec){case"h264":return Yd(i,A);case"opus":return Wd(i,A);case"aac":return Kd(i,A);case"av1":return Il(i,A);default:throw new Error(`Unsupported codec ${i[0].codec}`)}},cl=i=>{if(!i)return;const A=i.channelMappingTable,e=new Uint8Array(19+A.byteLength),t=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set([79,112,117,115,72,101,97,100],0),t.setUint8(8,1),t.setUint8(9,i.channelCount),t.setUint16(10,i.preSkip,!0),t.setUint32(12,i.inputSampleRate,!0),t.setInt16(16,i.outputGain,!0),t.setUint8(18,i.channelMappingFamily),A.byteLength>0&&e.set(A,19),e},OC=(i,A)=>{if(i<1||i>2)return;const e=new Uint8Array(19),t=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set([79,112,117,115,72,101,97,100]),t.setUint8(8,1),t.setUint8(9,i),t.setUint16(10,3840,!0),t.setUint32(12,A,!0),t.setInt16(16,0,!0),t.setUint8(18,0),e},bg=i=>!!(i&1),hl=i=>!!(i&2),dl=i=>!!(i&4),ll=i=>!!(i&8),ul=i=>!!(i&16),ml=i=>{const A=new DataView(i,0),e=A.getUint8(0),t=A.getUint16(1),g=A.getUint8(3),n=A.getUint8(4),o=KA(new Uint8Array(i),5,12),a=A.getUint32(13),B=ul(g)?A.getInt16(17):void 0,C=i.slice(t);return{version:e,renditionId:n,flags:g,timestamp:o,timescale:a,payload:C,compositionTimeOffset:B}},wl="data:video/mp4;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAGF21kYXTeBAAAbGliZmFhYyAxLjI4AABCAJMgBDIARwAAArEGBf//rdxF6b3m2Ui3lizYINkj7u94MjY0IC0gY29yZSAxNDIgcjIgOTU2YzhkOCAtIEguMjY0L01QRUctNCBBVkMgY29kZWMgLSBDb3B5bGVmdCAyMDAzLTIwMTQgLSBodHRwOi8vd3d3LnZpZGVvbGFuLm9yZy94MjY0Lmh0bWwgLSBvcHRpb25zOiBjYWJhYz0wIHJlZj0zIGRlYmxvY2s9MTowOjAgYW5hbHlzZT0weDE6MHgxMTEgbWU9aGV4IHN1Ym1lPTcgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0xNiBjaHJvbWFfbWU9MSB0cmVsbGlzPTEgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz02IGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTI1MCBrZXlpbnRfbWluPTI1IHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NDAgcmM9Y3JmIG1idHJlZT0xIGNyZj0yMy4wIHFjb21wPTAuNjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCB2YnZfbWF4cmF0ZT03NjggdmJ2X2J1ZnNpemU9MzAwMCBjcmZfbWF4PTAuMCBuYWxfaHJkPW5vbmUgZmlsbGVyPTAgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAAAFZliIQL8mKAAKvMnJycnJycnJycnXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXiEASZACGQAjgCEASZACGQAjgAAAAAdBmjgX4GSAIQBJkAIZACOAAAAAB0GaVAX4GSAhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGagC/AySEASZACGQAjgAAAAAZBmqAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZrAL8DJIQBJkAIZACOAAAAABkGa4C/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmwAvwMkhAEmQAhkAI4AAAAAGQZsgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGbQC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm2AvwMkhAEmQAhkAI4AAAAAGQZuAL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGboC/AySEASZACGQAjgAAAAAZBm8AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZvgL8DJIQBJkAIZACOAAAAABkGaAC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmiAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpAL8DJIQBJkAIZACOAAAAABkGaYC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmoAvwMkhAEmQAhkAI4AAAAAGQZqgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGawC/AySEASZACGQAjgAAAAAZBmuAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZsAL8DJIQBJkAIZACOAAAAABkGbIC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm0AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZtgL8DJIQBJkAIZACOAAAAABkGbgCvAySEASZACGQAjgCEASZACGQAjgAAAAAZBm6AnwMkhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AAAAhubW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAABDcAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAzB0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAA+kAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAALAAAACQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAPpAAAAAAABAAAAAAKobWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAB1MAAAdU5VxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACU21pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAhNzdGJsAAAAr3N0c2QAAAAAAAAAAQAAAJ9hdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAALAAkABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAALWF2Y0MBQsAN/+EAFWdCwA3ZAsTsBEAAAPpAADqYA8UKkgEABWjLg8sgAAAAHHV1aWRraEDyXyRPxbo5pRvPAyPzAAAAAAAAABhzdHRzAAAAAAAAAAEAAAAeAAAD6QAAABRzdHNzAAAAAAAAAAEAAAABAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAAIxzdHN6AAAAAAAAAAAAAAAeAAADDwAAAAsAAAALAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAAiHN0Y28AAAAAAAAAHgAAAEYAAANnAAADewAAA5gAAAO0AAADxwAAA+MAAAP2AAAEEgAABCUAAARBAAAEXQAABHAAAASMAAAEnwAABLsAAATOAAAE6gAABQYAAAUZAAAFNQAABUgAAAVkAAAFdwAABZMAAAWmAAAFwgAABd4AAAXxAAAGDQAABGh0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAACAAAAAAAABDcAAAAAAAAAAAAAAAEBAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAQkAAADcAABAAAAAAPgbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAC7gAAAykBVxAAAAAAALWhkbHIAAAAAAAAAAHNvdW4AAAAAAAAAAAAAAABTb3VuZEhhbmRsZXIAAAADi21pbmYAAAAQc21oZAAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAADT3N0YmwAAABnc3RzZAAAAAAAAAABAAAAV21wNGEAAAAAAAAAAQAAAAAAAAAAAAIAEAAAAAC7gAAAAAAAM2VzZHMAAAAAA4CAgCIAAgAEgICAFEAVBbjYAAu4AAAADcoFgICAAhGQBoCAgAECAAAAIHN0dHMAAAAAAAAAAgAAADIAAAQAAAAAAQAAAkAAAAFUc3RzYwAAAAAAAAAbAAAAAQAAAAEAAAABAAAAAgAAAAIAAAABAAAAAwAAAAEAAAABAAAABAAAAAIAAAABAAAABgAAAAEAAAABAAAABwAAAAIAAAABAAAACAAAAAEAAAABAAAACQAAAAIAAAABAAAACgAAAAEAAAABAAAACwAAAAIAAAABAAAADQAAAAEAAAABAAAADgAAAAIAAAABAAAADwAAAAEAAAABAAAAEAAAAAIAAAABAAAAEQAAAAEAAAABAAAAEgAAAAIAAAABAAAAFAAAAAEAAAABAAAAFQAAAAIAAAABAAAAFgAAAAEAAAABAAAAFwAAAAIAAAABAAAAGAAAAAEAAAABAAAAGQAAAAIAAAABAAAAGgAAAAEAAAABAAAAGwAAAAIAAAABAAAAHQAAAAEAAAABAAAAHgAAAAIAAAABAAAAHwAAAAQAAAABAAAA4HN0c3oAAAAAAAAAAAAAADMAAAAaAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAACMc3RjbwAAAAAAAAAfAAAALAAAA1UAAANyAAADhgAAA6IAAAO+AAAD0QAAA+0AAAQAAAAEHAAABC8AAARLAAAEZwAABHoAAASWAAAEqQAABMUAAATYAAAE9AAABRAAAAUjAAAFPwAABVIAAAVuAAAFgQAABZ0AAAWwAAAFzAAABegAAAX7AAAGFwAAAGJ1ZHRhAAAAWm1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALWlsc3QAAAAlqXRvbwAAAB1kYXRhAAAAAQAAAABMYXZmNTUuMzMuMTAw",ao=()=>"wakeLock"in navigator&&window.navigator.userAgent.indexOf("Samsung")===-1;class fl{constructor(){s(this,"enabled",!1);s(this,"wakeLockVideo");s(this,"_wakeLock",null);s(this,"handleVisibilityChange",()=>{this._wakeLock!==null&&document.visibilityState==="visible"&&this.enable()});ao()&&(this._wakeLock=null,document.addEventListener("visibilitychange",this.handleVisibilityChange),document.addEventListener("fullscreenchange",this.handleVisibilityChange))}_addSourceToVideo(A,e,t){const g=document.createElement("source");g.src=t,g.type=`video/${e}`,A.appendChild(g)}get isEnabled(){return this.enabled}attach(A){if(!ao()){if(!this.wakeLockVideo){const e=document.createElement("video");this.wakeLockVideo=e,this.wakeLockVideo.setAttribute("title","Live Stream"),this.wakeLockVideo.setAttribute("playsinline",""),this._addSourceToVideo(this.wakeLockVideo,"mp4",wl),Object.assign(this.wakeLockVideo.style,{position:"absolute",left:"-100%",top:"-100%"}),this.wakeLockVideo.addEventListener("loadedmetadata",()=>{e.addEventListener("timeupdate",()=>{e.currentTime>.5&&(e.currentTime=Math.random())})})}A&&A.appendChild(this.wakeLockVideo)}}enable(){return c(this,null,function*(){var A,e;return ao()?navigator.wakeLock.request("screen").then(t=>{this._wakeLock=t,this.enabled=!0,this._wakeLock.addEventListener("release",()=>{})}).catch(()=>{this.enabled=!1}):((e=(A=this.wakeLockVideo)==null?void 0:A.play())!=null?e:Promise.resolve()).then(g=>(this.enabled=!0,g)).catch(()=>{this.enabled=!1})})}disable(){var A,e;ao()?(this._wakeLock&&this._wakeLock.release(),this._wakeLock=null):((A=this.wakeLockVideo)==null||A.pause(),(e=this.wakeLockVideo)==null||e.remove()),this.enabled=!1}unload(){document.removeEventListener("visibilitychange",this.handleVisibilityChange),document.removeEventListener("fullscreenchange",this.handleVisibilityChange),this.disable()}}const Dl=/\r\n|\r|\n/;class VC{constructor(A){r(this,Rt);r(this,it);E(this,Rt,A),E(this,it,0)}skipEmptyLines(){let A=0;for(;I(this,Rt)[I(this,it)]==="";)te(this,it)._++,A++;return A}readLine(){return I(this,Rt)[te(this,it)._++]}takeUntilEmptyLine(){const A=[];for(;I(this,Rt)[I(this,it)]!=="";){const e=this.readLine();if(e===void 0)break;A.push(e)}return A}linesLeft(){return I(this,Rt).length-I(this,it)}}Rt=new WeakMap,it=new WeakMap;class ZC{constructor(){r(this,hi)}parse(A){const e=[],t=A.split(Dl),g=new VC(t),n=g.readLine();if(!n||!n.startsWith("WEBVTT"))throw new Error("missing 'WEBVTT' signature");for(;g.readLine()!=="";);for(;g.linesLeft()>0;){const o=l(this,hi,bE).call(this,g);o&&e.push(o),g.skipEmptyLines()}return e}}hi=new WeakSet,bE=function(A){A.skipEmptyLines();const e=A.takeUntilEmptyLine(),t=new VC(e);let g=t.readLine(),n;if(g!=null&&g.startsWith("NOTE"))return;if(g!=null&&g.includes("-->")||(n=g,g=t.readLine()),g===void 0)throw new Error("expected cue line");const[o,a]=g.split("-->").map(u=>u.trim());if(!o||!a)throw new Error(`a cue needs both start and end time start: ${o} end: ${a}`);const[B,C]=a.split(" ",1).map(u=>u.trim());if(!B)throw new Error(`missing end time: ${B}`);const Q=t.readLine();if(!Q)throw new Error("missing text");const h=l(this,hi,pr).call(this,o),d=l(this,hi,pr).call(this,B);return{id:n,startTime:h,endTime:d,text:Q}},pr=function(A){const e=A.split(":");if(e.length==2){const[a=0,B=0]=e.map(Q=>parseFloat(Q));return a*60+B}const[t=0,g=0,n=0]=e.map(a=>parseFloat(a));return t*60*60+g*60+n};const Sl=i=>{const A=window;A.vindralInstances=A.vindralInstances||{},A.vindralInstances[i.getStatistics().clientId.substring(0,8)]=i};class BB extends ie{constructor({type:e,autoplay:t,muted:g,volume:n,logger:o,poster:a}){super();s(this,"element");s(this,"logger");s(this,"seekTimes",new P(10));s(this,"seekStartTime");s(this,"_totalSeekTime",0);s(this,"_userProvidedMuted");s(this,"timers",new JA);s(this,"_userHasProvidedInput",!1);s(this,"_isPaused",!0);s(this,"isActivated",!1);s(this,"dummy");s(this,"_iosHackEnterPiPMode",()=>{const e=this.element.parentElement,t=this.element.clientWidth/this.element.clientHeight;this.element.style.position="fixed",this.element.style.opacity="0",this.element.style.pointerEvents="none",e&&(this.dummy=document.createElement("video"),this.dummy.style.paddingBottom="calc(100% / "+t+")",this.dummy.style.width="100%",this.dummy.style.height="0px",e.appendChild(this.dummy))});s(this,"_iosHackExitPiPMode",()=>{this.element.style.position="relative",this.element.style.opacity="1",this.element.style.pointerEvents="auto",this.dummy&&(this.dummy.remove(),this.dummy=void 0)});s(this,"attach",e=>{this.element.remove(),e.appendChild(this.element)});s(this,"load",()=>{this.timers.setInterval(this.onPlayPause,500),this.timers.setTimeout(()=>{this.timers.setInterval(this.onBufferStateChange,500)},1e4)});s(this,"unload",()=>{this.timers.unload()});s(this,"getPlaybackRate",()=>this.element.playbackRate);s(this,"getPlaybackState",()=>this.element.readyState>=this.element.HAVE_FUTURE_DATA?"playing":"buffering");s(this,"setPlaybackRate",e=>{this.element.playbackRate=e});s(this,"getBuffer",()=>{const e=[],t=this.element.buffered;if(!t)return[];for(let g=0;g<t.length;g++)e.push({start:t.start(g)*1e3,end:t.end(g)*1e3});return e});s(this,"pause",()=>{this._isPaused=!1,this.element.pause()});s(this,"tryPlay",()=>{this.element.muted=this._userProvidedMuted,this._play().catch(G)});s(this,"play",()=>{this.element.muted=this._userProvidedMuted,this._play().catch(e=>{if(e instanceof Error){const t=new x("Media Play Error",{source:e,isFatal:!1,code:"media_play_error"});this.emit("error",t)}})});s(this,"_play",()=>c(this,null,function*(){try{yield this.element.play(),this._userHasProvidedInput=!this.muted||this._userProvidedMuted}catch(e){if(e instanceof Error&&e.name==="NotAllowedError")if(this._userHasProvidedInput=!1,this.element.muted)this.emit("needs user input",{forAudio:!0,forVideo:!0});else return this.element.muted=!0,this.emit("needs user input",{forAudio:!0,forVideo:!1}),this._play();else throw e}}));s(this,"onEvent",e=>{this.logger.trace(e.type,{state:this.element.readyState,event:e,playbackState:this.getPlaybackState()})});s(this,"onVolumeChange",()=>{this.logger.info("volume state",{isMuted:this.element.muted,volume:this.element.volume}),this.emit("volume state",{isMuted:this.element.muted,volume:this.element.volume})});s(this,"onPlayPause",()=>{this._isPaused!==this.element.paused&&(this._isPaused=this.element.paused,this.logger.info("player pause change",{paused:this.element.paused}),this.emit("media element state",this.element.paused?"paused":"playing"))});s(this,"onBufferStateChange",()=>{this.emit("buffer state",{isPaused:this.element.paused,buffered:this.getBuffer(),currentTime:this.currentTime,playbackState:this.getPlaybackState()})});s(this,"onSeekStart",()=>{this.seekStartTime=Date.now()});s(this,"onSeekEnd",()=>{if(!this.seekStartTime)return;const e=Date.now()-this.seekStartTime;this.seekTimes.push(e),this._totalSeekTime+=e,this.seekStartTime=void 0});this.logger=o,this._userProvidedMuted=g,this.element=document.createElement(e),this.element instanceof HTMLVideoElement&&(this.element.playsInline=!0),this.element.controls=!1,this.element.autoplay=t,this.element.muted=g,n!==void 0&&(this.element.volume=n),this.element.style.display="block",this.element.style.width="100%",this.element.disableRemotePlayback=!0,this.element.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAJCAQAAACRI2S5AAAAEElEQVR42mNkIAAYRxWAAQAG9gAKqv6+AwAAAABJRU5ErkJggg=="),this.onPlayPause(),setTimeout(()=>{!this.element||!a||this.element.setAttribute("poster",a)},0),this.element.addEventListener("stalled",this.onEvent),this.element.addEventListener("canplay",this.onEvent),this.element.addEventListener("loadeddata",this.onEvent),this.element.addEventListener("loadedmetadata",this.onEvent),this.element.addEventListener("canplaythrough",this.onEvent),this.element.addEventListener("waiting",this.onEvent),this.element.addEventListener("playing",this.onPlayPause),this.element.addEventListener("pause",this.onPlayPause),this.element.addEventListener("seeked",this.onSeekEnd),this.element.addEventListener("seeking",this.onSeekStart),this.element.addEventListener("volumechange",this.onVolumeChange),this.element.addEventListener("timeupdate",this.onBufferStateChange),this.element.addEventListener("progress",this.onBufferStateChange)}get seekTime(){return this.seekTimes.isEmpty()?0:we(this.seekTimes.items())}get totalSeekTime(){return this._totalSeekTime}get isSeeking(){return this.element.seeking}get currentTime(){return isNaN(this.element.currentTime)?0:this.element.currentTime*1e3}set currentTime(e){Number.isFinite(e)&&(this.element.currentTime=e/1e3)}get playbackRate(){return this.element.playbackRate}set playbackRate(e){this.element.playbackRate=e}get volume(){return this.element.volume}set volume(e){this.element.volume=e}get muted(){return this.element.muted}set muted(e){this._userProvidedMuted=e,this.element.muted=e}get userHasProvidedInput(){return this._userHasProvidedInput}get isPaused(){return this._isPaused}}const pl=i=>{if(!navigator.mediaCapabilities)return Promise.resolve({smooth:!0,supported:!0,powerEfficient:!0,failedToQuery:!0});if(i.codec==="webvtt")throw new Error("WebVTT is not supported");let A;return ti(i)?A={type:"media-source",audio:{contentType:mt(i),bitrate:i.bitRate,channels:i.channels.toString(),samplerate:i.sampleRate}}:A={type:"media-source",video:{contentType:mt(i),bitrate:i.bitRate,width:i.width,height:i.height,framerate:i.frameRate[0]/i.frameRate[1]}},navigator.mediaCapabilities.decodingInfo(A)},yl=.15,Fl=.2,XC=.4,kl=.5,Rl=.6,rB=15,Gl={cooldownTime:3e3,maxBufferingEvents:{last10Seconds:0},maxBufferingRatio:{last10Seconds:0},maxRecentDowngradesCount:3,maxDowngradeLookbackMs:60*1e3,minTimeSpentPlaying:{factor:.5,ratio:.1},maxCooldownRatio:2},CB=i=>A=>A>i,qo=class qo{constructor(A,e,t,g){s(this,"qualityOfServiceSource");s(this,"config");s(this,"emitter");s(this,"logger");s(this,"isSuspended",!1);s(this,"lastAdaptTime",Date.now());s(this,"isEnabled",!0);s(this,"load",()=>{this.emitter.on("buffer state",this.onBufferState),this.emitter.on("adapted level",this.onAdaptedLevel)});s(this,"unload",()=>{this.emitter.off("buffer state",this.onBufferState),this.emitter.off("adapted level",this.onAdaptedLevel)});s(this,"suspend",()=>{this.isSuspended=!0});s(this,"unsuspend",()=>{this.reset(),this.isSuspended=!1});s(this,"reset",(A=0)=>{this.lastAdaptTime=Date.now()+A});s(this,"getStatistics",()=>({isAbrEnabled:this.isEnabled}));s(this,"isQoSOk",A=>{const e=this.qualityOfServiceSource.getLevelStats(A),{upgradesFromLevel:t,downgradesFromLevel:g}=e!=null?e:{upgradesFromLevel:[],downgradesFromLevel:[]},n=Date.now()-this.config.maxDowngradeLookbackMs,o=g.filter(CB(n)).length,a=t.filter(CB(n)).length;if(o-a>this.config.maxRecentDowngradesCount)return this.logger.debug("Recent downgrades count is over maximum",{downgrades:o-a,maxRecentDowngradesCount:this.config.maxRecentDowngradesCount}),!1;const B=this.qualityOfServiceSource.timeSpentPlayingInAtLeastLevelRatio(A),C=this.qualityOfServiceSource.timeActive()-this.qualityOfServiceSource.timeSpentBuffering(),Q=B*C/this.config.maxDowngradeLookbackMs;if(o>1&&Q<this.config.minTimeSpentPlaying.factor)return this.logger.debug("Time spent playing is too low",{recentDowngrades:o,timeSpentPlayingInAtLeastLevelRatio:B}),!1;if(o>1&&B<this.config.minTimeSpentPlaying.ratio)return this.logger.debug("Time spent playing in at least this level is too low",{recentDowngrades:o,timeSpentPlayingInAtLeastLevelRatio:B}),!1;const h=Math.max(0,g.length-t.length-Q),d=Date.now()-this.config.maxDowngradeLookbackMs*h,u=g.filter(CB(d)).length;return u&&h>this.config.maxCooldownRatio?(this.logger.debug("Too many downgrades compared to time spent playing",{downgradesWithinCooldownTime:u,cooldownRatio:h}),!1):!0});s(this,"onBufferState",A=>{if(!this.isEnabled||this.isSuspended||this.lastAdaptTime+this.config.cooldownTime>Date.now())return;const{bufferFullness:e,general:t}=this.qualityOfServiceSource.getMetrics(),g=this.qualityOfServiceSource.getBufferFullnessRegression();if(!g)return;const n=10*1e3,o=30*1e3,{slope:a}=g,B=g.predict(rB),C=a<0,Q=g.predict(rB)<XC&&g.slope<0,h=g.predict(rB)>Rl,d=this.qualityOfServiceSource.timeSpentBufferingLast(o),u=this.qualityOfServiceSource.timeSpentActiveLast(o),m=this.qualityOfServiceSource.bufferingEventsLast(o),p=u>0?d/u:0,y=this.qualityOfServiceSource.getTargetBufferTime();if(e<.15&&p>.8){this.adaptLevel("reconnect");return}if(t.decodeRate<=.9){this.adaptLevel("downgrade");return}if(e>kl&&h&&!this.tooMuchTimeBuffering(n)&&!this.tooManyBufferingEvents(n)){this.adaptLevel("upgrade");return}if(y<1e3){A.playbackState==="buffering"&&(m>5||p>.3)&&this.adaptLevel("downgrade");return}(Q||e<yl)&&C&&e<XC&&B<Fl&&this.adaptLevel(A.playbackState==="buffering"?"double downgrade":"downgrade")});s(this,"onAdaptedLevel",()=>{this.reset()});s(this,"adaptLevel",A=>this.emitter.emit("adapt level",A));this.qualityOfServiceSource=t,this.config=f(f({},Gl),g),this.emitter=A,this.logger=e}tooMuchTimeBuffering(A){const e=this.qualityOfServiceSource.timeSpentActiveLast(A);return(e?this.qualityOfServiceSource.timeSpentBufferingLast(A)/e:0)>this.config.maxBufferingRatio.last10Seconds}tooManyBufferingEvents(A){return this.qualityOfServiceSource.timeSpentBufferingLast(A)>this.config.maxBufferingEvents.last10Seconds}};s(qo,"create",(A,e,t,g={})=>new qo(A,e,t,g));let QB=qo;const Ul={minBufferTime:1500,maxBufferTime:1500,cooldownTime:3e4,maxBufferingEvents:{last30Seconds:3},maxBufferingRatio:{last30Seconds:.15}},Gt=class Gt{constructor(A,e,t,g,n){s(this,"qualityOfServiceSource");s(this,"targetBufferTimeTarget");s(this,"config");s(this,"emitter");s(this,"logger");s(this,"isSuspended",!1);s(this,"lastIncreaseTime",Date.now());s(this,"bufferTimeAdjustmentCount",0);s(this,"load",()=>{this.emitter.on("buffer state",this.onBufferState)});s(this,"unload",()=>{this.emitter.off("buffer state",this.onBufferState)});s(this,"suspend",()=>{this.isSuspended=!0});s(this,"unsuspend",()=>{this.reset(),this.isSuspended=!1});s(this,"reset",()=>{this.lastIncreaseTime=Date.now()});s(this,"getStatistics",()=>({bufferTimeAdjustmentCount:this.bufferTimeAdjustmentCount}));s(this,"onBufferState",A=>{const{minBufferTime:e,maxBufferTime:t,cooldownTime:g}=this.config;if(this.isSuspended||this.lastIncreaseTime+g>Date.now()||this.targetBufferTimeTarget.targetBufferTime>=t)return;const n=this.qualityOfServiceSource.timeSpentBufferingLast(30*1e3),o=this.qualityOfServiceSource.bufferingEventsLast(30*1e3),a=this.qualityOfServiceSource.timeSpentActiveLast(30*1e3),B=n/a,C=Math.ceil(Math.max((t-e)/(Gt.BUFFER_TIME_MAX_STEPS-1),Gt.BUFFER_TIME_STEP_SIZE));(B>this.config.maxBufferingRatio.last30Seconds||o>this.config.maxBufferingEvents.last30Seconds)&&(this.targetBufferTimeTarget.targetBufferTime=Math.min(t,this.targetBufferTimeTarget.targetBufferTime+C),this.bufferTimeAdjustmentCount++,this.reset())});this.qualityOfServiceSource=t,this.targetBufferTimeTarget=g,this.config=f(f({},Ul),n),this.emitter=A,this.logger=e}updateConfig(A){this.config=f(f({},this.config),A)}};s(Gt,"BUFFER_TIME_STEP_SIZE",500),s(Gt,"BUFFER_TIME_MAX_STEPS",3),s(Gt,"create",(A,e,t,g,n={})=>new Gt(A,e,t,g,n));let EB=Gt;const bl=i=>i?{Authorization:`Bearer ${i}`}:void 0,Nl=(i,A)=>{try{const e=i.ancestorOrigins;if(e&&e.length>0)return Array.from(e).join(",")||void 0}catch(e){}try{if(A.referrer)return new URL(A.referrer).origin||void 0}catch(e){}},Ll=i=>typeof i=="object"&&i!==null&&"message"in i;class Jl extends Error{constructor({status:e,url:t,body:g}){const n=_r(g),o=Ll(n)?n.message:`Url ${t.toString()}, Status code: ${e}, Body: ${g}`;super(o);s(this,"status");s(this,"body");s(this,"url");this.status=e,this.body=g,this.url=t,Object.setPrototypeOf(this,new.target.prototype)}}const Ml=i=>typeof i.status=="number",vl=()=>{if(!(typeof window=="undefined"||typeof document=="undefined"))return Nl(window.location,document)},Hl=i=>{const A=vl();if(!A||i.searchParams.has("parentOrigin"))return i;const e=new URL(i.toString());return e.searchParams.append("parentOrigin",A),e},jC=(i,A)=>c(null,null,function*(){const e=Hl(i),t=yield fetch(e.toString(),f({mode:"cors"},A));if(!t.ok)throw new Jl({status:t.status,url:e,body:yield t.text()});return t}),cB=(i,A)=>c(null,null,function*(){return yield(yield jC(i,f({},A))).json()}),zC=(i,A)=>c(null,null,function*(){return jC(i,f({method:"POST"},A))});function ql(i){var A;return!(typeof i.edges[0]=="string"||i.channels[0]&&"catalog"in i.channels[0]&&typeof((A=i.channels[0])==null?void 0:A.catalog)=="undefined")}const _C={lbConnect:i=>i.channelGroupId?`connect?channelId=${i.channelId}&channelGroupId=${i.channelGroupId}`:`connect?channelId=${i.channelId}`,thumbnails:(i,A)=>A?i.channelGroupId?`thumbnail/?channelGroupId=${i.channelGroupId}&auth.token=${A}&auth.type=jwt`:i.channelId?`thumbnail/?channelId=${i.channelId}&auth.token=${A}&auth.type=jwt`:"thumbnail":"thumbnail"};class $C{constructor(A){s(this,"baseUrl");s(this,"tokenFactory");this.baseUrl=new URL("/api/v4/",A.publicEndpoint).toString(),this.tokenFactory=A.tokenFactory}connect(A){return c(this,null,function*(){const{channelId:e,channelGroupId:t}=A,g={channelId:e,channelGroupId:t},n=new URL(_C.lbConnect(A),this.baseUrl),o=this.getAuthToken(g),a=yield cB(n,{headers:this.getHeaders(o)});if(ql(a)){const B=a.channels.map(C=>{const Q=this.toChannel(C,g),h=iC(C.catalog);return V(f(f({},C),Q),{renditions:h})});return V(f({},a),{channels:B})}else{const B=a.channels.map(C=>{const Q=this.toChannel(C,g);return f(f({},C),Q)});return V(f({},a),{channels:B})}})}getChannel(A){return c(this,null,function*(){const e={channelId:A},t=new URL(`channel/${A}`,this.baseUrl),g=this.getAuthToken(e),n=yield cB(t,{headers:this.getHeaders(g)});return this.toChannel(n,e,g)})}getChannels(A){return c(this,null,function*(){const e={channelGroupId:A},t=new URL(`channels/${A}`,this.baseUrl),g=this.getAuthToken(e),n=yield cB(t,{headers:this.getHeaders(g)}),o=Array.isArray(n)?n:n.channels;return this.toChannels(o,e,g)})}getHeaders(A){var t;return(t=bl(A))!=null?t:{}}getAuthToken(A){return this.tokenFactory?this.tokenFactory(A):void 0}toChannels(A,e,t){return A.map(g=>this.toChannel(g,e,t))}toChannel(A,e,t){const{baseUrl:g,sizes:n}=A.thumbnail,o=g||new URL(_C.thumbnails(e,t),this.baseUrl),a=n.map(B=>new URL(`?channelId=${A.channelId}&width=${B.width}&height=${B.height}${Kl(e,t)}`,o).toString());return{channelId:A.channelId,name:A.name,isLive:A.isLive,thumbnailUrls:a}}}const Kl=(i,A)=>A?i.channelGroupId?`&channelGroupId=${i.channelGroupId}&auth.token=${A}&auth.type=jwt`:`&auth.token=${A}&auth.type=jwt`:"";var Bo=(i=>(i[i.StreamHeaderGroup=4]="StreamHeaderGroup",i[i.FetchHeader=5]="FetchHeader",i[i.StreamHeaderTrack=60]="StreamHeaderTrack",i))(Bo||{});const WA={Normal:0,ObjectDoesNotExist:1,GroupDoesNotExist:2,EndOfGroup:3,EndOfTrackAndGroup:4};function AQ(i){switch(i){case WA.Normal:case WA.ObjectDoesNotExist:case WA.GroupDoesNotExist:case WA.EndOfGroup:case WA.EndOfTrackAndGroup:return}throw new Error("Unknown object status "+i)}class Tl{constructor(A,e,t,g,n,o){r(this,Te);r(this,ws);r(this,fs);r(this,mI);r(this,wI);r(this,Ds,new _);r(this,fI,0);r(this,DI);E(this,Te,A),E(this,ws,e),E(this,fs,t),E(this,mI,g),E(this,wI,n),E(this,DI,o)}endStatus(){return I(this,Ds).promise}groupId(){return I(this,ws)}subscribeId(){return I(this,fs)}next(){return c(this,null,function*(){if(!I(this,Ds).pending)return{done:!0,value:void 0};if(yield I(this,Te).isDone())return{done:!0,value:void 0};const A=I(this,fI)===0?I(this,ws):yield I(this,Te).readBigVarInt(),e=yield I(this,Te).readBigVarInt(),t=yield I(this,Te).readVarInt();let g=0,n=new Uint8Array;return t>0?n=yield I(this,Te).read(t):g=yield I(this,Te).readVarInt(),AQ(g),(g===WA.EndOfTrackAndGroup||g===WA.EndOfGroup)&&I(this,Ds).resolve(g),te(this,fI)._++,{done:!1,value:{subscribeId:I(this,fs),trackAlias:I(this,mI),groupId:A,subGroupId:M(0),objectId:e,subscriberPriority:I(this,wI),streamId:I(this,DI),objectStatus:g,payload:n}}})}return(){return c(this,null,function*(){for(;!(yield this.next()).done;);return{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[Me()](){return Promise.resolve()}[Symbol.asyncDispose](){return Promise.resolve()}}Te=new WeakMap,ws=new WeakMap,fs=new WeakMap,mI=new WeakMap,wI=new WeakMap,Ds=new WeakMap,fI=new WeakMap,DI=new WeakMap;class Yl{constructor(A,e,t,g,n){r(this,di);r(this,Ye);r(this,Ss);r(this,SI);r(this,pI);r(this,ps);E(this,Ye,A),E(this,Ss,e),E(this,SI,t),E(this,pI,g),E(this,ps,n)}streamId(){return I(this,ps)}groups(){return l(this,di,NE).call(this)}subscribeId(){return I(this,Ss)}return(){return c(this,null,function*(){return yield I(this,Ye).close(),{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[Me()](){return l(this,di,yr).call(this)}[Symbol.asyncDispose](){return l(this,di,yr).call(this)}}Ye=new WeakMap,Ss=new WeakMap,SI=new WeakMap,pI=new WeakMap,ps=new WeakMap,di=new WeakSet,NE=function(){return lt(this,null,function*(){for(;!(yield new rA(I(this,Ye).isDone()));){const A=yield new rA(I(this,Ye).readBigVarInt()),e=new Tl(I(this,Ye),A,I(this,Ss),I(this,SI),I(this,pI),I(this,ps));if(yield e,(yield new rA(Promise.race([e.endStatus(),I(this,Ye).closed()])))===WA.EndOfTrackAndGroup)return}})},yr=function(){return I(this,Ye).close().catch(()=>{})};class Pl{constructor(A,e,t,g,n,o,a){r(this,li);r(this,ye);r(this,ys);r(this,yI);r(this,Fs);r(this,FI);r(this,kI);r(this,RI,!1);r(this,ks);r(this,Ko,GA.get().createContext("GroupReader"));E(this,ye,A),E(this,ys,e),E(this,yI,t),E(this,Fs,g),E(this,FI,n),E(this,kI,o),E(this,ks,a)}streamId(){return I(this,ks)}groupId(){return I(this,Fs)}subscribeId(){return I(this,ys)}next(){return c(this,null,function*(){try{if((yield I(this,ye).isDone())||I(this,RI))return{done:!0,value:void 0};const A=yield I(this,ye).readBigVarInt(),e=yield I(this,ye).readVarInt();let t=0,g=new Uint8Array;return e>0?g=yield I(this,ye).read(e):t=yield I(this,ye).readVarInt(),AQ(t),t===WA.EndOfGroup&&E(this,RI,!0),{done:!1,value:{subscribeId:I(this,ys),trackAlias:I(this,yI),groupId:I(this,Fs),subGroupId:I(this,FI),subscriberPriority:I(this,kI),streamId:I(this,ks),objectId:A,objectStatus:t,payload:g}}}catch(A){return I(this,Ko).info("Error reading object",{error:A}),{done:!0,value:void 0}}})}return(){return c(this,null,function*(){return yield I(this,ye).close().catch(()=>{}),{done:!0,value:void 0}})}groups(){return l(this,li,LE).call(this)}[Symbol.asyncIterator](){return this}[Me()](){return l(this,li,Fr).call(this)}[Symbol.asyncDispose](){return l(this,li,Fr).call(this)}}ye=new WeakMap,ys=new WeakMap,yI=new WeakMap,Fs=new WeakMap,FI=new WeakMap,kI=new WeakMap,RI=new WeakMap,ks=new WeakMap,Ko=new WeakMap,li=new WeakSet,LE=function(){return lt(this,null,function*(){yield this})},Fr=function(){return I(this,ye).close().catch(()=>{})};function eQ(i,A){return c(this,null,function*(){const e=yield i.readVarInt();switch(e){case Bo.StreamHeaderGroup:{const t=yield i.readBigVarInt(),g=yield i.readBigVarInt(),n=yield i.readBigVarInt(),o=yield i.readBigVarInt(),a=yield i.readUnsigned8();return new Pl(i,t,g,n,o,a,A)}case Bo.StreamHeaderTrack:{const t=yield i.readBigVarInt(),g=yield i.readBigVarInt(),n=yield i.readUnsigned8();return new Yl(i,t,g,n,A)}default:throw new Error("Unexpected message type "+e)}})}class xl{constructor(A,e){r(this,Ut);r(this,GI);E(this,Ut,A),E(this,GI,e)}start(A){I(this,Ut).addEventListener("message",e=>{if(typeof e.data=="object"&&e.data instanceof ArrayBuffer){const t=new Uint8Array(e.data);t[0]==I(this,GI)&&A.enqueue(t.subarray(1))}}),I(this,Ut).addEventListener("error",()=>A.error(new Error("WebSocket error"))),I(this,Ut).addEventListener("close",()=>zr(()=>A.close()))}cancel(A){I(this,Ut).close(void 0,A)}}Ut=new WeakMap,GI=new WeakMap;class Wl{constructor(A){r(this,Pe);r(this,ui,null);r(this,mi,null);r(this,wi,null);E(this,Pe,A)}start(A){E(this,ui,e=>{if(typeof e.data=="object"&&e.data instanceof ArrayBuffer){const t=new Uint8Array(e.data),g=t[0]||0,n=g&127,o=(g>>7&1)>0;if(n&&n!==0){const a=t.subarray(1);A.enqueue([o,n,a])}}}),E(this,mi,()=>zr(()=>A.close())),E(this,wi,()=>A.error(new Error("WebSocket error"))),I(this,Pe).addEventListener("message",I(this,ui)),I(this,Pe).addEventListener("error",I(this,wi)),I(this,Pe).addEventListener("close",I(this,mi))}cancel(A){I(this,ui)&&I(this,Pe).removeEventListener("message",I(this,ui)),I(this,wi)&&I(this,Pe).removeEventListener("error",I(this,wi)),I(this,mi)&&I(this,Pe).removeEventListener("close",I(this,mi))}}Pe=new WeakMap,ui=new WeakMap,mi=new WeakMap,wi=new WeakMap;function Ol(i,A){return i[A]<<8|i[A+1]}function Vl(i,A){return(i[A]<<24|i[A+1]<<16|i[A+2]<<8|i[A+3])>>>0}class ro{constructor(A,e){r(this,CA);r(this,vA);r(this,UI);r(this,fi);r(this,pA,0);r(this,To,new TextDecoder);E(this,vA,A),E(this,UI,e),E(this,fi,e.getReader())}readUnsigned8(){return c(this,null,function*(){return yield l(this,CA,$i).call(this,1),I(this,vA)[te(this,pA)._++]})}readString(){return c(this,null,function*(){const A=yield this.readVarInt(),e=yield this.read(A);return I(this,To).decode(e)})}readVarInt(){return c(this,null,function*(){const A=yield this.readBigVarInt();if(A>Number.MAX_SAFE_INTEGER)throw new Error("VarInt is too large");return Number(A)})}readBigVarInt(){return c(this,null,function*(){yield l(this,CA,$i).call(this,1);const A=I(this,vA)[I(this,pA)],e=(A&192)>>6;switch(I(this,vA)[I(this,pA)]=A&63,e){case 0:return M(I(this,vA)[te(this,pA)._++]);case 1:{yield l(this,CA,$i).call(this,2);const t=I(this,pA);return E(this,pA,I(this,pA)+2),M(Ol(I(this,vA),t))}case 2:{yield l(this,CA,$i).call(this,4);const t=I(this,pA);return E(this,pA,I(this,pA)+4),M(Vl(I(this,vA),t))}case 3:{yield l(this,CA,$i).call(this,8);const t=I(this,pA);E(this,pA,I(this,pA)+8);const g=new DataView(I(this,vA).buffer,I(this,vA).byteOffset+t,8);return M(Mn?g.getBigUint64(0):g.getUint32(0)*4294967296+g.getUint32(4))}default:throw new Error("Invalid VarInt size")}})}read(A){return c(this,null,function*(){return yield l(this,CA,$i).call(this,A),l(this,CA,kr).call(this,A)})}readAll(){return c(this,null,function*(){for(;yield l(this,CA,ba).call(this););return l(this,CA,kr).call(this,l(this,CA,Un).call(this))})}isDone(){return c(this,null,function*(){return l(this,CA,Un).call(this)>0?!1:(yield l(this,CA,ba).call(this))==0})}closed(){return c(this,null,function*(){return I(this,fi).closed})}close(){return c(this,null,function*(){return I(this,fi).releaseLock(),I(this,UI).cancel()})}}vA=new WeakMap,UI=new WeakMap,fi=new WeakMap,pA=new WeakMap,To=new WeakMap,CA=new WeakSet,Un=function(){return I(this,vA).length-I(this,pA)},ba=function(){return c(this,null,function*(){const{value:A,done:e}=yield I(this,fi).read();if(e)return Promise.resolve(0);if(l(this,CA,Un).call(this)===0)E(this,vA,A);else{const g=I(this,vA).subarray(I(this,pA)),n=new Uint8Array(g.length+A.length);n.set(g),n.set(A,g.byteLength),E(this,vA,n)}return E(this,pA,0),Promise.resolve(A.length)})},$i=function(A){return c(this,null,function*(){for(;l(this,CA,Un).call(this)<A;)if((yield l(this,CA,ba).call(this))===0)throw new Error("Read failed")})},JE=function(A){return I(this,vA).subarray(I(this,pA),I(this,pA)+A)},kr=function(A){const e=l(this,CA,JE).call(this,A);return E(this,pA,I(this,pA)+e.length),e};class tQ{constructor(A){r(this,NI);r(this,xe,new Uint8Array(8));r(this,bI,I(this,xe).subarray(0,1));r(this,Yo,I(this,xe).subarray(0,2));r(this,Po,I(this,xe).subarray(0,4));r(this,xo,I(this,xe).subarray(0,8));r(this,Rs);r(this,st);r(this,Wo,new TextEncoder);E(this,Rs,A),E(this,st,I(this,Rs).getWriter())}writeString(A){return c(this,null,function*(){const e=I(this,Wo).encode(A);return yield this.writeVarInt(e.length),this.write(e)})}write(A){return I(this,st).write(A)}writeUnsigned8(A){return I(this,xe)[0]=A,I(this,st).write(I(this,bI))}writeVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return I(this,st).write(l(this,NI,Rr).call(this,BQ(A,I(this,xe),0)))}writeBigVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return I(this,st).write(l(this,NI,Rr).call(this,rQ(A,I(this,xe),0)))}flush(){return c(this,null,function*(){})}close(){return c(this,null,function*(){I(this,st).releaseLock(),yield I(this,Rs).close()})}}xe=new WeakMap,bI=new WeakMap,Yo=new WeakMap,Po=new WeakMap,xo=new WeakMap,Rs=new WeakMap,st=new WeakMap,Wo=new WeakMap,NI=new WeakSet,Rr=function(A){switch(A){case 1:return I(this,bI);case 2:return I(this,Yo);case 4:return I(this,Po);default:return I(this,xo)}};const iQ={OPEN:1},Vo=class Vo{constructor(A){r(this,Ae,0);r(this,Ee,new Uint8Array(Vo.DEFAULT_BUFFER_SIZE));r(this,Di);r(this,Oo,new TextEncoder);E(this,Di,A)}writeString(A){return c(this,null,function*(){const e=I(this,Oo).encode(A);return yield this.writeVarInt(e.length),this.write(e)})}ensureBufferSpace(A){if(I(this,Ee).length-I(this,Ae)>=A)return;const e=new Uint8Array(I(this,Ee).length+A);e.set(I(this,Ee)),E(this,Ee,e)}write(A){return this.ensureBufferSpace(A.length),I(this,Ee).set(A,I(this,Ae)),E(this,Ae,I(this,Ae)+A.byteLength),Promise.resolve()}writeUnsigned8(A){return this.ensureBufferSpace(1),I(this,Ee)[I(this,Ae)]=A,E(this,Ae,I(this,Ae)+1),Promise.resolve()}writeVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return this.ensureBufferSpace(8),E(this,Ae,I(this,Ae)+BQ(A,I(this,Ee),I(this,Ae))),Promise.resolve()}writeBigVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return this.ensureBufferSpace(8),E(this,Ae,I(this,Ae)+rQ(A,I(this,Ee),I(this,Ae))),Promise.resolve()}flush(){if(I(this,Di).readyState!==iQ.OPEN)throw new Error("Writer is not open");return I(this,Di).send(I(this,Ee).subarray(0,I(this,Ae))),E(this,Ae,0),Promise.resolve()}close(){return I(this,Di).close(),Promise.resolve()}};Ae=new WeakMap,Ee=new WeakMap,Di=new WeakMap,Oo=new WeakMap,s(Vo,"DEFAULT_BUFFER_SIZE",1024);let Ng=Vo;const sQ=2**6-1,gQ=2**14-1,IQ=2**30-1,nQ=Number.MAX_SAFE_INTEGER;function oQ(i,A,e){A[e]=i>>8&255,A[e+1]=i&255}function aQ(i,A,e){A[e]=i>>>24&255,A[e+1]=i>>16&255,A[e+2]=i>>8&255,A[e+3]=i&255}function BQ(i,A,e){if(i<=sQ)return A[e]=i,1;if(i<=gQ)return oQ(i|16384,A,e),2;if(i<=IQ)return aQ(i|2147483648,A,e),4;if(i<=nQ)return CQ(i,A,e),8;throw new Error(`overflow, value larger than 53-bits: ${i}`)}function rQ(i,A,e){if(i<=sQ)return A[e]=Number(i),1;if(i<=gQ)return oQ(Number(i)|16384,A,e),2;if(i<=IQ)return aQ(Number(i)|2147483648,A,e),4;if(i<=nQ)return CQ(Number(i),A,e),8;throw new Error(`overflow, value larger than 53-bits: ${i}`)}function CQ(i,A,e){const t=new DataView(A.buffer,A.byteOffset+e,8);t.setUint32(0,i/4294967296),t.setUint32(4,i&4294967295),A[e]=192}var q=(i=>(i[i.SubscribeUpdate=2]="SubscribeUpdate",i[i.Subscribe=3]="Subscribe",i[i.SubscribeOk=4]="SubscribeOk",i[i.SubscribeError=5]="SubscribeError",i[i.Announce=6]="Announce",i[i.AnnounceOk=7]="AnnounceOk",i[i.AnnounceError=8]="AnnounceError",i[i.Unannounce=9]="Unannounce",i[i.Unsubscribe=10]="Unsubscribe",i[i.SubscribeDone=11]="SubscribeDone",i[i.AnnounceCancel=12]="AnnounceCancel",i[i.TrackStatusRequest=13]="TrackStatusRequest",i[i.TrackStatus=14]="TrackStatus",i[i.Goaway=16]="Goaway",i[i.ClientSetup=64]="ClientSetup",i[i.ServerSetup=65]="ServerSetup",i[i.Unknown=255]="Unknown",i))(q||{});function Co(i){return c(this,null,function*(){const A=yield i.readVarInt();if(A<1||A>32)throw new Error(`namespace must be between 1 and 32, got ${A}`);const e=[];for(let t=0;t<A;t++)e.push(yield i.readString());return e})}function hB(i,A){return c(this,null,function*(){yield i.writeVarInt(A.length);for(const e of A)yield i.writeString(e)})}const Qo=M(2);function as(i){return c(this,null,function*(){const A=yield i.readVarInt(),e=new Map;for(let t=0;t<A;t++){const g=yield i.readBigVarInt(),n=yield i.read(yield i.readVarInt());e.set(g,{type:g,payload:n})}return e})}function Bs(i,A){return c(this,null,function*(){yield i.writeVarInt(A.size);for(const[e,t]of A)yield i.writeBigVarInt(e),yield i.writeVarInt(t.payload.length),yield i.write(t.payload)})}function Zl(i){return c(this,null,function*(){return{type:q.Announce,namespace:yield Co(i),params:yield as(i)}})}function Xl(i,A){return c(this,null,function*(){yield hB(i,A.namespace),yield Bs(i,A.params)})}function jl(i){return c(this,null,function*(){return{type:q.AnnounceOk,namespace:yield Co(i)}})}function zl(i,A){return c(this,null,function*(){yield hB(i,A.namespace)})}const _l={"latest-group":1,"latest-object":2,"absolute-start":3,"absolute-range":4};function $l(i){return c(this,null,function*(){const A=yield i.readVarInt();switch(A){case 1:return{type:"latest-group"};case 2:return{type:"latest-object"};case 3:return{type:"absolute-start",start:{group:yield i.readBigVarInt(),object:yield i.readBigVarInt()}};case 4:return{type:"absolute-range",start:{group:yield i.readBigVarInt(),object:yield i.readBigVarInt()},end:{group:yield i.readBigVarInt(),object:yield i.readBigVarInt()}};default:throw new Error(`Invalid location type ${A}`)}})}function Au(i,A){return c(this,null,function*(){const e=_l[A.type];switch(yield i.writeVarInt(e),A.type){case"absolute-range":yield i.writeBigVarInt(A.start.group),yield i.writeBigVarInt(A.start.object),yield i.writeBigVarInt(A.end.group),yield i.writeBigVarInt(A.end.object);break;case"absolute-start":yield i.writeBigVarInt(A.start.group),yield i.writeBigVarInt(A.start.object);break;case"latest-object":case"latest-group":break;default:throw new Error(`Invalid location type ${e}`)}})}function QQ(i){return c(this,null,function*(){const A=yield i.readUnsigned8();switch(A){case 0:return"inherit-publisher";case 1:return"ascending";case 2:return"descending";default:throw new Error(`Invalid location type ${A}`)}})}function EQ(i,A){return c(this,null,function*(){switch(A){case"inherit-publisher":yield i.writeUnsigned8(0);break;case"ascending":yield i.writeUnsigned8(1);break;case"descending":yield i.writeUnsigned8(2);break}})}function eu(i){return c(this,null,function*(){const A=yield i.readBigVarInt(),e=yield i.readBigVarInt(),t=yield Co(i),g=yield i.readString(),n=yield i.readUnsigned8(),o=yield QQ(i),a=yield $l(i),B=yield as(i);if(a.type==="absolute-range"){const C=a.start.group>a.end.group,Q=a.start.group===a.end.group&&a.start.object>a.end.object;if(C||Q)throw new Error("Invalid filter range")}return{type:q.Subscribe,id:A,trackAlias:e,namespace:t,name:g,subscriberPriority:n,groupOrder:o,filterType:a,params:B}})}function tu(i,A){return c(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.trackAlias),yield hB(i,A.namespace),yield i.writeString(A.name),yield i.writeUnsigned8(A.subscriberPriority),yield EQ(i,A.groupOrder),yield Au(i,A.filterType),yield Bs(i,A.params)})}const dB={TrackEnded:3,Expired:6};function iu(i){return c(this,null,function*(){const A=yield i.readBigVarInt(),e=yield i.readVarInt(),t=yield i.readString(),g=(yield i.readUnsigned8())==1;let n;return g&&(n={group:yield i.readBigVarInt(),object:yield i.readBigVarInt()}),{type:q.SubscribeDone,id:A,errorCode:e,reason:t,finalInfo:n}})}function su(i,A){return c(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeVarInt(A.errorCode),yield i.writeString(A.reason),yield i.writeUnsigned8(A.finalInfo?1:0),A.finalInfo&&(yield i.writeBigVarInt(A.finalInfo.group),yield i.writeBigVarInt(A.finalInfo.object))})}function gu(i){return c(this,null,function*(){return{type:q.SubscribeError,id:yield i.readBigVarInt(),errorCode:yield i.readBigVarInt(),reason:yield i.readString(),trackAlias:yield i.readBigVarInt()}})}function Iu(i,A){return c(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.errorCode),yield i.writeString(A.reason),yield i.writeBigVarInt(A.trackAlias)})}function nu(i){return c(this,null,function*(){const A=yield i.readBigVarInt(),e=yield i.readBigVarInt(),t=yield QQ(i),g=(yield i.readUnsigned8())==1;let n;if(t=="inherit-publisher")throw new Error("SusbcribeOk cannot have inherit publisher group order");g&&(n={group:yield i.readBigVarInt(),object:yield i.readBigVarInt()});const o=yield as(i);return{type:q.SubscribeOk,id:A,groupOrder:t,expires:e,largestInfo:n,params:o}})}function ou(i,A){return c(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.expires),yield EQ(i,A.groupOrder),yield i.writeUnsigned8(A.largestInfo?1:0),A.largestInfo&&(yield i.writeBigVarInt(A.largestInfo.group),yield i.writeBigVarInt(A.largestInfo.object)),yield Bs(i,A.params)})}function au(i){return c(this,null,function*(){const A=yield i.readBigVarInt(),e=yield i.readBigVarInt(),t=yield i.readBigVarInt(),g=yield i.readBigVarInt(),n=yield i.readBigVarInt(),o=yield i.readUnsigned8(),a=yield as(i),B=e>g,C=e===g&&t>n;if(B||C)throw new Error("Invalid filter range");return{type:q.SubscribeUpdate,id:A,start:{group:e,object:t},end:{group:g,object:n},subscriberPriority:o,params:a}})}function Bu(i,A){return c(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.start.group),yield i.writeBigVarInt(A.start.object),yield i.writeBigVarInt(A.end.group),yield i.writeBigVarInt(A.end.object),yield i.writeUnsigned8(A.subscriberPriority),yield Bs(i,A.params)})}const ru={Subscriber:2},Eo={Role:M(0)},cQ={Draft07:4278190087};function hQ(i){return c(this,null,function*(){const A=yield i.readVarInt();return A===cQ.Draft07?{type:"known",value:A}:{type:"unknown",value:A}})}function Cu(i,A){return c(this,null,function*(){yield i.writeVarInt(A.supportedVersions.length);for(const e of A.supportedVersions)yield i.writeVarInt(e.value);yield Bs(i,A.parameters)})}function Qu(i){return c(this,null,function*(){const A=[],e=yield i.readVarInt();for(let g=0;g<e;g++)A.push(yield hQ(i));const t=yield as(i);if(!t.has(Eo.Role))throw new Error("Role parameter is required");return{type:q.ClientSetup,supportedVersions:A,parameters:t}})}function Eu(i,A){return c(this,null,function*(){yield i.writeVarInt(A.selectedVersion.value),yield Bs(i,A.parameters)})}function cu(i){return c(this,null,function*(){const A=yield hQ(i);if(A.type!=="known")throw new Error("Expected known version");const e=yield as(i);if(!e.has(Eo.Role))throw new Error("Role parameter is required");return{type:q.ServerSetup,selectedVersion:A,parameters:e}})}function hu(i){return c(this,null,function*(){return{type:q.Unsubscribe,id:yield i.readBigVarInt()}})}function du(i,A){return c(this,null,function*(){yield i.writeBigVarInt(A.id)})}class dQ{constructor(A){r(this,hA);r(this,gt);r(this,Gs,new Uint8Array);E(this,gt,A)}write(A){return c(this,null,function*(){yield I(this,gt).writeVarInt(A.type);const e=new Ng({close:()=>{},readyState:iQ.OPEN,send:t=>{E(this,Gs,new Uint8Array(t))}});switch(A.type){case q.Subscribe:yield l(this,hA,HE).call(this,e,A);break;case q.Announce:yield l(this,hA,xE).call(this,e,A);break;case q.SubscribeOk:yield l(this,hA,qE).call(this,e,A);break;case q.SubscribeUpdate:yield l(this,hA,TE).call(this,e,A);break;case q.SubscribeError:yield l(this,hA,KE).call(this,e,A);break;case q.SubscribeDone:yield l(this,hA,YE).call(this,e,A);break;case q.Unsubscribe:yield l(this,hA,PE).call(this,e,A);break;case q.ClientSetup:yield l(this,hA,ME).call(this,e,A);break;case q.ServerSetup:yield l(this,hA,vE).call(this,e,A);break;case q.AnnounceOk:yield l(this,hA,WE).call(this,e,A);break;default:throw new Error(`Unknown message type: ${A.type}`)}yield e.flush(),yield I(this,gt).writeVarInt(I(this,Gs).byteLength),yield I(this,gt).write(I(this,Gs)),yield I(this,gt).flush()})}close(){return c(this,null,function*(){return I(this,gt).close()})}}gt=new WeakMap,Gs=new WeakMap,hA=new WeakSet,ME=function(A,e){return c(this,null,function*(){yield Cu(A,e)})},vE=function(A,e){return c(this,null,function*(){yield Eu(A,e)})},HE=function(A,e){return c(this,null,function*(){yield tu(A,e)})},qE=function(A,e){return c(this,null,function*(){yield ou(A,e)})},KE=function(A,e){return c(this,null,function*(){yield Iu(A,e)})},TE=function(A,e){return c(this,null,function*(){yield Bu(A,e)})},YE=function(A,e){return c(this,null,function*(){yield su(A,e)})},PE=function(A,e){return c(this,null,function*(){yield du(A,e)})},xE=function(A,e){return c(this,null,function*(){yield Xl(A,e)})},WE=function(A,e){return c(this,null,function*(){yield zl(A,e)})};class lu{constructor(A,e){r(this,Us);r(this,LI);r(this,JI);E(this,Us,A),E(this,LI,new dQ(A)),E(this,JI,e)}write(A){return c(this,null,function*(){yield I(this,Us).write(I(this,JI)),yield I(this,LI).write(A)})}close(){return I(this,Us).close()}}Us=new WeakMap,LI=new WeakMap,JI=new WeakMap,M(1025),M(1027),M(1033),M(2048);class uu extends Error{constructor(A,e){super(A),this.errorCode=e}}function mu(i){return c(this,null,function*(){return{type:q.AnnounceError,namespace:yield Co(i),errorCode:yield i.readBigVarInt(),reason:yield i.readString()}})}function wu(i,A,e){return c(this,null,function*(){return{type:q.Unknown,messageType:A,payload:yield i.read(e)}})}class lQ{constructor(A){r(this,yA);E(this,yA,A)}cancel(){return I(this,yA).close()}read(){return c(this,null,function*(){const A=yield I(this,yA).readVarInt(),e=yield I(this,yA).readVarInt();switch(A){case q.ServerSetup:return cu(I(this,yA));case q.ClientSetup:return Qu(I(this,yA));case q.Subscribe:return eu(I(this,yA));case q.SubscribeOk:return nu(I(this,yA));case q.SubscribeDone:return iu(I(this,yA));case q.SubscribeError:return gu(I(this,yA));case q.SubscribeUpdate:return au(I(this,yA));case q.Unsubscribe:return hu(I(this,yA));case q.Announce:return Zl(I(this,yA));case q.AnnounceOk:return jl(I(this,yA));case q.AnnounceError:return mu(I(this,yA))}return wu(I(this,yA),M(A),e)})}}yA=new WeakMap;const Ls=class Ls{constructor(A,e){r(this,Zo);r(this,MI);r(this,bs);r(this,Ns,new _);r(this,vI,new _);E(this,MI,A),E(this,bs,e),I(this,Ns).resolve()}write(A){return c(this,null,function*(){const e=yield l(this,Zo,OE).call(this);try{yield I(this,MI).write(A)}finally{e.resolve()}})}markPostHandshake(){I(this,vI).resolve()}postHandshake(){return I(this,vI).promise}read(){return c(this,null,function*(){return I(this,bs).read()})}cancel(){return I(this,bs).cancel()}static wrapWebsocket(A){const e=new ReadableStream(new xl(A,I(Ls,Xo))),t=new lQ(new ro(new Uint8Array([]),e)),g=new lu(new Ng(A),new Uint8Array([0]));return new Ls(g,t)}static wrapWebTransport(A){const e=A.writable,t=A.readable;return new Ls(new dQ(new tQ(e)),new lQ(new ro(new Uint8Array,t)))}};MI=new WeakMap,bs=new WeakMap,Ns=new WeakMap,vI=new WeakMap,Zo=new WeakSet,OE=function(){const A=new _,e=I(this,Ns).promise.then(()=>A);return E(this,Ns,A),e},Xo=new WeakMap,r(Ls,Xo,0);let co=Ls;function uQ(i,A){return c(this,null,function*(){yield i.write({type:q.ClientSetup,supportedVersions:[{type:"known",value:cQ.Draft07}],parameters:new Map([[Eo.Role,{type:Eo.Role,payload:new Uint8Array([A])}]])});const e=yield i.read();if(i.markPostHandshake(),e.type!==q.ServerSetup)throw new Error("Expected server setup message");if(e.selectedVersion.type!=="known")throw new Error("Expected known version")})}class fu{constructor(A){s(this,"announce");r(this,Js,new _);this.announce=A}onOk(A){I(this,Js).resolve(A)}onError(A){const e=new uu(A.reason,A.errorCode);return I(this,Js).reject(e),e}ok(){return I(this,Js).promise}}Js=new WeakMap;function Du(i){const A=new fu(i);return new Su(A)}class Su{constructor(A){s(this,"state");this.state=A}}const vs=class vs{constructor(A){s(this,"subscribe");r(this,Ms,new _);r(this,bt,new _);r(this,Si,new _);r(this,jo,Date.now());r(this,pi,new _);r(this,Fe);switch(this.subscribe=A,A.filterType.type){case"absolute-start":E(this,Fe,{startGroup:A.filterType.start.group});break;case"absolute-range":E(this,Fe,{startGroup:A.filterType.start.group,endGroup:A.filterType.end.group});break}}onUpdate(A){E(this,Fe,{startGroup:A.start.group}),A.end.group>M(0)&&(I(this,Fe).endGroup=A.end.group-M(1))}onError(A){const e=new Error(A.reason);return I(this,Ms).reject(e),I(this,bt).reject(e),e}onDone(A){A.finalInfo&&(I(this,Fe)||E(this,Fe,{startGroup:M(0)}),I(this,Fe).endGroup=A.finalInfo.group),I(this,bt).resolve(A)}onUnsubscribe(A){I(this,Si).resolve(A)}onOk(A){const e=Math.max(0,Date.now()-I(this,jo)),t=Number(A.expires);if(t>0){const g=Math.max(vs.minGraceTime,Math.min(t/10,vs.maxGraceTime));Promise.race([ut(t-g-e),this.done().catch(G)]).then(()=>I(this,pi).resolve(this.expiryState())).catch(G)}I(this,Ms).resolve(A)}done(){return I(this,bt).promise}ok(){return I(this,Ms).promise}range(){return I(this,Fe)}close(){I(this,pi).promise.catch(G),I(this,pi).reject(new Error("Subscription closed"))}expiryState(){return I(this,bt).resolved&&I(this,bt).resolved.errorCode!==dB.Expired?"done":I(this,Si).pending?"active":"unsubscribed"}unsubscribed(){return I(this,Si).promise}isUnsubscribed(){return I(this,Si).resolved}expiryNotification(){return I(this,pi).promise}};Ms=new WeakMap,bt=new WeakMap,Si=new WeakMap,jo=new WeakMap,pi=new WeakMap,Fe=new WeakMap,s(vs,"maxGraceTime",15e3),s(vs,"minGraceTime",3e3);let ho=vs;class pu{constructor(A){r(this,TA);r(this,HI,!1);E(this,TA,A)}write(A){return c(this,null,function*(){I(this,HI)||(yield I(this,TA).writeVarInt(Bo.StreamHeaderGroup),yield I(this,TA).writeBigVarInt(A.subscribeId),yield I(this,TA).writeBigVarInt(A.trackAlias),yield I(this,TA).writeBigVarInt(A.groupId),yield I(this,TA).writeBigVarInt(A.subGroupId),yield I(this,TA).writeUnsigned8(A.subscriberPriority),E(this,HI,!0)),yield I(this,TA).writeBigVarInt(A.objectId),yield I(this,TA).writeVarInt(A.payload.length),A.payload.length>0?yield I(this,TA).write(A.payload):yield I(this,TA).writeVarInt(A.objectStatus),yield I(this,TA).flush()})}close(){return c(this,null,function*(){yield I(this,TA).close()})}}TA=new WeakMap,HI=new WeakMap;class yu{constructor(A,e,t,g){r(this,zo);r(this,qI);r(this,ce);r(this,KI);r(this,TI);r(this,Hs);r(this,YI);E(this,qI,e),E(this,ce,A),E(this,KI,t),E(this,TI,g),E(this,YI,GA.get().createContext(`SubscriptionWriter:${A.subscribe.name}`))}finalInfo(){return I(this,Hs)}run(){return c(this,null,function*(){yield Promise.race([l(this,zo,VE).call(this).catch(A=>I(this,YI).error("error writing subscription",A)),I(this,ce).unsubscribed(),I(this,ce).done(),I(this,ce).expiryNotification().catch(G)])})}done(A,e){return c(this,null,function*(){if(I(this,ce).isUnsubscribed())return;const t={type:q.SubscribeDone,id:I(this,ce).subscribe.id,errorCode:A,reason:e,finalInfo:I(this,Hs)};I(this,ce).onDone(t),yield I(this,TI).push(t)})}[Me()](){return this.done(dB.TrackEnded,"Track ended")}[Symbol.asyncDispose](){return this.done(dB.TrackEnded,"Track ended")}}qI=new WeakMap,ce=new WeakMap,KI=new WeakMap,TI=new WeakMap,Hs=new WeakMap,YI=new WeakMap,zo=new WeakSet,VE=function(){return c(this,null,function*(){try{for(var o=EA(I(this,qI)),a,B,C;a=!(B=yield o.next()).done;a=!1){const Q=B.value;var A=[];try{const h=I(this,ce).range();if(h&&(h.startGroup>Q.id||h.endGroup&&h.endGroup<Q.id))break;const d=yield I(this,KI).openSendStream();const u=new pu(d);const m=ue(A,new Fu(u,Q.consume(),I(this,ce)),!0);yield m.run();E(this,Hs,m.finalGroup())}catch(e){var t=e,g=!0}finally{var n=me(A,t,g);n&&(yield n)}}}catch(B){C=[B]}finally{try{a&&(B=o.return)&&(yield B.call(o))}finally{if(C)throw C[0]}}})};class Fu{constructor(A,e,t){r(this,yi);r(this,PI);r(this,qs);r(this,xI);r(this,Ks);E(this,yi,A),E(this,PI,e),E(this,qs,t),E(this,Ks,GA.get().createContext(`GroupSubscriptionWriter:${t.subscribe.name}`))}finalGroup(){return I(this,xI)}run(){return c(this,null,function*(){I(this,Ks).debug("write group");try{for(var A=EA(I(this,PI)),e,t,g;e=!(t=yield A.next()).done;e=!1){const n=t.value;yield I(this,yi).write({subscribeId:I(this,qs).subscribe.id,trackAlias:I(this,qs).subscribe.trackAlias,subGroupId:M(0),subscriberPriority:0,groupId:n.groupId,objectId:n.objectId,objectStatus:n.objectStatus,payload:n.payload}),E(this,xI,{group:n.groupId,object:n.objectId})}}catch(t){g=[t]}finally{try{e&&(t=A.return)&&(yield t.call(A))}finally{if(g)throw g[0]}}I(this,Ks).debug("write group done")})}[Me()](){return I(this,yi).close().catch(G)}[Symbol.asyncDispose](){return I(this,yi).close().catch(G)}}yi=new WeakMap,PI=new WeakMap,qs=new WeakMap,xI=new WeakMap,Ks=new WeakMap;class ku{constructor(A,e,t){r(this,Nt);s(this,"state");r(this,WI);r(this,Fi);this.state=A,E(this,WI,e),E(this,Fi,t)}ok(A){return c(this,null,function*(){var B,C,Q;const e=(B=this.state.range())==null?void 0:B.startGroup,t=A.latest(),g=t==null?void 0:t.id,n=(Q=(C=t==null?void 0:t.latest())==null?void 0:C.objectId)!=null?Q:M(0),o=A.consume(e!=null?e:g),a={type:q.SubscribeOk,id:this.state.subscribe.id,expires:M(0),groupOrder:"ascending",params:new Map,largestInfo:g?{group:g,object:n}:void 0};return yield I(this,Fi).push(a),new yu(this.state,o,I(this,WI),I(this,Fi))})}invalidRange(){return l(this,Nt,yg).call(this,M(1),"Invalid range")}retryTrackAlias(){return l(this,Nt,yg).call(this,M(2),"Retry track alias")}trackDoesNotExist(){return l(this,Nt,yg).call(this,M(3),"Track does not exist")}unauthorized(){return l(this,Nt,yg).call(this,M(4),"Unauthorized")}timeout(){return l(this,Nt,yg).call(this,M(5),"Timeout")}[Me()](){return this.trackDoesNotExist()}[Symbol.asyncDispose](){return this.trackDoesNotExist()}}WI=new WeakMap,Fi=new WeakMap,Nt=new WeakSet,yg=function(A,e){const t={type:q.SubscribeError,id:this.state.subscribe.id,errorCode:A,reason:e,trackAlias:this.state.subscribe.trackAlias};return I(this,Fi).push(t)},eE=[$A({context:"Session",enter:"info",error:"error"})];class lB{constructor(A,e,t){_i(Br,5,this);r(this,Ts);r(this,OI);r(this,Ys);r(this,ki,GA.get().createContext("Publisher"));r(this,Lt,new xA(new Map));r(this,Jt,new xA(new Map));r(this,Mt,new _t(10));E(this,Ts,A),E(this,OI,e),E(this,Ys,t)}announce(A){return c(this,null,function*(){if(I(this,Lt).current().has(A.join("/")))throw new Error("Duplicate announcement");const e=new Map,t=I(this,Ts).authToken();t&&e.set(Qo,{type:Qo,payload:new TextEncoder().encode(t)});const g={type:q.Announce,namespace:A,params:e},n=Du(g);if(I(this,Lt).update(a=>a.set(g.namespace.join("/"),n)),yield I(this,Ys).push(g),!(yield Promise.race([n.state.ok(),I(this,Ts).closed()])))throw new Error("Session closed")})}close(){I(this,Jt).current().forEach(A=>A.close()),I(this,Jt).close(),I(this,Lt).close(),I(this,Mt).close()}incomingSubscriptions(){return I(this,Mt)}onMessage(A){return c(this,null,function*(){switch(A.type){case q.Subscribe:{const e=new ho(A);if(I(this,Jt).update(t=>(t.set(A.id,e),t)),I(this,Mt).isFull()){const t=yield I(this,Mt).pop();yield t==null?void 0:t.timeout()}yield I(this,Mt).push(new ku(e,I(this,OI),I(this,Ys)))}break;case q.SubscribeUpdate:{const e=I(this,Jt).current().get(A.id);e||I(this,ki).debug("No subscription found",A),e==null||e.onUpdate(A)}break;case q.Unsubscribe:{const e=I(this,Jt).current().get(A.id);e||I(this,ki).debug("No subscription found",A),e==null||e.onUnsubscribe(A)}break;case q.AnnounceOk:{const e=I(this,Lt).current().get(A.namespace.join("/"));e||I(this,ki).debug("No announcement found",A),e==null||e.state.onOk(A)}break;case q.AnnounceError:{const e=I(this,Lt).current().get(A.namespace.join("/"));e||I(this,ki).debug("No announcement found",A),e==null||e.state.onError(A)}break}})}}Br=zi(null),Ts=new WeakMap,OI=new WeakMap,Ys=new WeakMap,ki=new WeakMap,Lt=new WeakMap,Jt=new WeakMap,Mt=new WeakMap,_A(Br,1,"announce",eE,lB),jt(Br,lB);function Ru(i,A){const e=new ho(A),[t,g]=zt(100),n=new Gu(e,t),o=new mQ(i,e,g);return[n,o]}class Gu{constructor(A,e){s(this,"state");r(this,Ri);this.state=A,E(this,Ri,e)}onDone(A){this.state.onDone(A)}onData(A){return I(this,Ri).push(A)}onError(A){const e=this.state.onError(A);I(this,Ri).abort(e)}close(){this.state.close(),I(this,Ri).close()}}Ri=new WeakMap;class mQ{constructor(A,e,t){_i(rr,5,this);r(this,Os);r(this,Ps);r(this,bA);r(this,xs);r(this,Ws,new _);E(this,Ps,A),E(this,bA,e),E(this,xs,t)}get id(){return I(this,bA).subscribe.id}get trackAlias(){return I(this,bA).subscribe.trackAlias}get name(){return I(this,bA).subscribe.name}range(){return I(this,bA).range()}expiryNotification(){return I(this,bA).expiryNotification()}update(A,e){return c(this,null,function*(){const t={type:q.SubscribeUpdate,id:I(this,bA).subscribe.id,start:{group:A,object:M(0)},end:{group:e+M(1),object:M(0)},params:new Map,subscriberPriority:0};I(this,bA).onUpdate(t),yield I(this,Ps).push(t)})}unsubscribe(){return c(this,null,function*(){const A={type:q.Unsubscribe,id:I(this,bA).subscribe.id};I(this,bA).onUnsubscribe(A),yield I(this,Ps).push(A)})}close(){var A,e;return I(this,Ws).resolve(),(e=(A=I(this,xs)).return)==null?void 0:e.call(A)}closed(){return I(this,Ws).promise}done(){return I(this,bA).done()}expiryState(){return I(this,bA).expiryState()}unsubscribed(){return I(this,bA).isUnsubscribed()}return(){return c(this,null,function*(){return I(this,Ws).resolve(),yield this.unsubscribe(),{done:!0,value:void 0}})}groups(){return lt(this,null,function*(){var A,e;try{for(var u=EA(I(this,xs)),m,p,y;m=!(p=yield new rA(u.next())).done;m=!1){var a=p.value;var B=[];try{const k=ue(B,a,!0);try{for(var t=EA(k.groups()),g,n,o;g=!(n=yield new rA(t.next())).done;g=!1){const N=n.value;const U=(A=I(this,bA).range())==null?void 0:A.startGroup,K=(e=I(this,bA).range())==null?void 0:e.endGroup;if(U&&N.groupId()<U)return{done:!0,value:void 0};if(K&&N.groupId()>K)return{done:!0,value:void 0};yield N}}catch(n){o=[n]}finally{try{g&&(n=t.return)&&(yield new rA(n.call(t)))}finally{if(o)throw o[0]}}}catch(C){var Q=C,h=!0}finally{var d=me(B,Q,h);d&&(yield new rA(d))}}}catch(p){y=[p]}finally{try{m&&(p=u.return)&&(yield new rA(p.call(u)))}finally{if(y)throw y[0]}}})}[Symbol.asyncIterator](){return this.groups()}objects(){return lt(this,null,function*(){try{for(var n=EA(this.groups()),o,a,B;o=!(a=yield new rA(n.next())).done;o=!1){const C=a.value;try{for(var A=EA(C),e,t,g;e=!(t=yield new rA(A.next())).done;e=!1){const Q=t.value;yield Q}}catch(t){g=[t]}finally{try{e&&(t=A.return)&&(yield new rA(t.call(A)))}finally{if(g)throw g[0]}}}}catch(a){B=[a]}finally{try{o&&(a=n.return)&&(yield new rA(a.call(n)))}finally{if(B)throw B[0]}}})}[(tE=[$A({context:"SubscriptionConsumer",enter:"info"})],Me())](){return l(this,Os,bn).call(this)}[Symbol.asyncDispose](){return l(this,Os,bn).call(this)}}rr=zi(null),Ps=new WeakMap,bA=new WeakMap,xs=new WeakMap,Ws=new WeakMap,Os=new WeakSet,bn=function(){return c(this,null,function*(){return yield this.close(),this.unsubscribe()})},bn=_A(rr,17,"#dispose",tE,Os,bn),jt(rr,mQ);const Uu=2e3;IE=[$A({context:"Session",return:"debug"})],gE=[$A({context:"Session",enter:"info",error:"error"})],sE=[$A({context:"Session",enter:"debug"})],iE=[$A({context:"Session",enter:"debug"})];class lo{constructor(A,e){_i(Vs,5,this);r(this,We);r(this,It);s(this,"nextSubscribeId",M(0));r(this,ge,new xA(new Map));r(this,Gi);r(this,Ui,GA.get().createContext("Subscriber"));E(this,It,A),E(this,Gi,e),l(this,We,Na).call(this).catch(G)}subscribe(g,n){return c(this,arguments,function*(A,e,t=new Map){const o=this.nextSubscribeId++,a=I(this,It).authToken();a&&t.set(Qo,{type:Qo,payload:new TextEncoder().encode(a)});const B={type:q.Subscribe,namespace:A,name:e.name,id:o,trackAlias:o,groupOrder:e.groupOrder,subscriberPriority:e.priority,filterType:e.filterType,params:t},[C,Q]=Ru(I(this,Gi),B);if(I(this,ge).update(d=>d.set(o,C)),yield I(this,Gi).push(B),!(yield Promise.race([C.state.ok(),I(this,It).closed()])))throw new Error("Session closed");return Q.closed().then(()=>Promise.race([ut(Uu),this.closed()])).then(()=>l(this,We,Fg).call(this,Q.id)).catch(()=>l(this,We,Fg).call(this,Q.id)),Q})}closed(){return I(this,It).closed()}transportType(){return I(this,It).transportType()}url(){return I(this,It).url()}onMessage(A){return c(this,null,function*(){switch(A.type){case q.Announce:yield I(this,Gi).push({type:q.AnnounceOk,namespace:A.namespace});break;case q.SubscribeOk:{const e=I(this,ge).current().get(A.id);e&&e.state.onOk(A)}break;case q.SubscribeError:{const e=I(this,ge).current().get(A.id);e||I(this,Ui).debug("No subscription found",A),e==null||e.onError(A),l(this,We,Fg).call(this,A.id)}break;case q.SubscribeDone:{const e=I(this,ge).current().get(A.id);e||I(this,Ui).debug("No subscription found",A),e==null||e.onDone(A)}break}})}onObjectReader(A){return c(this,null,function*(){const e=I(this,ge).current().get(A.subscribeId());if(!e){I(this,Ui).warn("No subscription found",A.subscribeId());return}yield e.onData(A)})}close(){I(this,ge).current().forEach(A=>A.close()),I(this,ge).close()}}Vs=zi(null),It=new WeakMap,ge=new WeakMap,Gi=new WeakMap,Ui=new WeakMap,We=new WeakSet,Na=function(){return c(this,null,function*(){try{for(var A=EA(I(this,ge)),e,t,g;e=!(t=yield A.next()).done;e=!1){const n=t.value;const o=[...n.values()].map(a=>a.state.subscribe);I(this,Ui).debug("current subscriptions",o)}}catch(t){g=[t]}finally{try{e&&(t=A.return)&&(yield t.call(A))}finally{if(g)throw g[0]}}})},Fg=function(A){I(this,ge).isClosed()||I(this,ge).update(e=>(e.delete(A),e))},Na=_A(Vs,17,"#observeChanges",IE,We,Na),_A(Vs,1,"subscribe",gE,lo),_A(Vs,1,"close",sE,lo),Fg=_A(Vs,17,"#deleteSubscription",iE,We,Fg),jt(Vs,lo);class uB{constructor(A,e){_i(js,5,this);r(this,FA);r(this,ke);r(this,VI);r(this,bi);r(this,Zs,GA.get().createContext("Session"));s(this,"subscriber");s(this,"publisher");r(this,Xs);const[t,g]=zt(100);E(this,ke,A),E(this,bi,g),this.subscriber=new lo(this,t),this.publisher=new lB(this,A,t),E(this,VI,l(this,FA,XE).call(this)),E(this,Xs,new xA(e)),this.closed().then(()=>this.close()).catch(G)}updateAuthToken(A){I(this,Xs).update(A)}authToken(){return I(this,Xs).current()}transportType(){return I(this,ke).transportType()}url(){return I(this,ke).url()}closed(){return I(this,VI)}close(){try{this.subscriber.close(),this.publisher.close(),I(this,bi).cancel("closing"),I(this,ke).close()}catch(A){I(this,Zs).warn("Error closing session",A)}}[(BE=[$A({context:"Session",return:"info",error:"error"})],aE=[$A({context:"Session",return:"info",error:"error"})],oE=[$A({context:"Session",return:"info",error:"error"})],nE=[$A({context:"Session",enter:"debug"})],Zr())](){l(this,FA,Nn).call(this)}[Symbol.dispose](){l(this,FA,Nn).call(this)}}js=zi(null),ke=new WeakMap,VI=new WeakMap,bi=new WeakMap,Zs=new WeakMap,Xs=new WeakMap,FA=new WeakSet,ZE=function(A){return c(this,null,function*(){var e,t;I(this,Zs).debug("received message",A),yield(e=this.subscriber)==null?void 0:e.onMessage(A),yield(t=this.publisher)==null?void 0:t.onMessage(A),A.type,q.Goaway})},XE=function(){return c(this,null,function*(){return(yield Promise.all([l(this,FA,Ja).call(this),l(this,FA,Ma).call(this),l(this,FA,La).call(this)])).find(e=>e instanceof Error)})},La=function(){return c(this,null,function*(){try{try{for(var A=EA(I(this,bi)),e,t,g;e=!(t=yield A.next()).done;e=!1){const n=t.value;I(this,Zs).debug("sending message",n),yield I(this,ke).writeMessage(n)}}catch(t){g=[t]}finally{try{e&&(t=A.return)&&(yield t.call(A))}finally{if(g)throw g[0]}}}catch(n){return n}})},Ja=function(){return c(this,null,function*(){try{for(yield I(this,ke).afterHandshake();;){const A=yield I(this,ke).readMessage().catch(()=>{});if(!A)break;yield l(this,FA,ZE).call(this,A)}}catch(A){return A}finally{I(this,bi).cancel("closing")}})},Ma=function(){return c(this,null,function*(){var A;try{for(;;){const e=yield I(this,ke).objectStream();if(!e)break;yield(A=this.subscriber)==null?void 0:A.onObjectReader(e)}}catch(e){return e}})},Nn=function(){this.close()},La=_A(js,17,"#runOutgoingMessages",BE,FA,La),Ja=_A(js,17,"#runControl",aE,FA,Ja),Ma=_A(js,17,"#runObjects",oE,FA,Ma),Nn=_A(js,17,"#dispose",nE,FA,Nn),jt(js,uB);const bu=128;class Nu{constructor(A,e,t){r(this,YA);r(this,he);r(this,ZI);r(this,Ni,!0);r(this,zs,!1);r(this,XI);E(this,he,A),E(this,ZI,e),E(this,XI,t)}writeUnsigned8(A){return c(this,null,function*(){return l(this,YA,As).call(this),yield l(this,YA,es).call(this),I(this,he).writeUnsigned8(A)})}writeVarInt(A){return c(this,null,function*(){return l(this,YA,As).call(this),yield l(this,YA,es).call(this),I(this,he).writeVarInt(A)})}writeBigVarInt(A){return c(this,null,function*(){return l(this,YA,As).call(this),yield l(this,YA,es).call(this),I(this,he).writeBigVarInt(A)})}write(A){return c(this,null,function*(){return l(this,YA,As).call(this),yield l(this,YA,es).call(this),I(this,he).write(A)})}writeString(A){return c(this,null,function*(){return l(this,YA,As).call(this),yield l(this,YA,es).call(this),I(this,he).writeString(A)})}flush(){return c(this,null,function*(){l(this,YA,As).call(this),E(this,Ni,!0),yield I(this,he).flush()})}close(){return c(this,null,function*(){I(this,zs)||(E(this,Ni,!0),yield l(this,YA,es).call(this,!1),yield I(this,he).flush(),E(this,zs,!0),I(this,XI).call(this))})}}he=new WeakMap,ZI=new WeakMap,Ni=new WeakMap,zs=new WeakMap,XI=new WeakMap,YA=new WeakSet,As=function(){if(I(this,zs))throw new Error("Stream is closed")},es=function(A=!0){if(I(this,Ni))return E(this,Ni,!1),I(this,he).writeUnsigned8(I(this,ZI)|(A?bu:0))};class Lu{constructor(A,e){r(this,_o);r(this,vt);r(this,nt);r(this,_s);r(this,Li);r(this,ot,new Map);r(this,Ji,GA.get().createContext("WebSocketConnection"));r(this,$s,new Set(new Array(128).fill(0).map((A,e)=>e+1)));E(this,vt,A),E(this,nt,e),E(this,_s,new ReadableStream(new Wl(A))),I(this,vt).addEventListener("close",t=>{I(this,Ji).info("WebSocket closed",{code:t.code,reason:t.reason,wasClean:t.wasClean}),I(this,nt).markPostHandshake(),I(this,ot).forEach(g=>g.close())})}openSendStream(){const A=I(this,$s).values().next().value;if(!A)throw new Error("No stream IDs available");return I(this,$s).delete(A),Promise.resolve(new Nu(new Ng(I(this,vt)),A,()=>l(this,_o,jE).call(this,A)))}transportType(){return"websocket"}url(){return I(this,vt).url}afterHandshake(){return I(this,nt).postHandshake()}objectStream(){return c(this,null,function*(){var A;for(;;){E(this,Li,I(this,_s).getReader());try{const{value:e,done:t}=yield I(this,Li).read();if(t)return;const[g,n,o]=e;if(I(this,ot).has(M(n))){const a=I(this,ot).get(M(n));if(!a)throw new Error("Stream not found");o.length>0&&(yield a.push(o)),g||(I(this,Ji).debug("Closing stream",{streamId:n}),a.close(),I(this,ot).delete(M(n)))}else{let Q;I(this,Ji).debug("Creating new stream",{streamId:n});const[a,B]=zt(1e3),C=new ReadableStream({pull(h){return c(this,null,function*(){const d=yield B.pop();d?h.enqueue(d):h.close()})}});if(I(this,ot).set(M(n),a),g||(I(this,Ji).debug("Closing new stream",{streamId:n}),yield C.cancel(),I(this,ot).delete(M(n))),o.length>0)return yield eQ(new ro(o,C),n)}}finally{(A=I(this,Li))==null||A.releaseLock()}}})}close(){var A;return I(this,nt).cancel().catch(G),I(this,_s).cancel("closing").catch(G),(A=I(this,Li))==null||A.cancel("closing").catch(G),I(this,vt).close()}closed(){return Promise.resolve()}writeMessage(A){return c(this,null,function*(){yield I(this,nt).write(A)})}readMessage(){return c(this,null,function*(){return I(this,nt).read()})}}vt=new WeakMap,nt=new WeakMap,_s=new WeakMap,Li=new WeakMap,ot=new WeakMap,Ji=new WeakMap,$s=new WeakMap,_o=new WeakSet,jE=function(A){I(this,$s).add(A)};class Ju{constructor(A,e,t){r(this,Aa);r(this,at);r(this,Bt);r(this,Ht,new _t(100));r(this,jI);r(this,zI,0);r(this,$o,GA.get().createContext("WebTransportConnection"));E(this,jI,t),E(this,at,A),E(this,Bt,e),l(this,Aa,zE).call(this).catch(g=>{I(this,$o).debug("Incoming streams handling ended with error",g),I(this,Bt).markPostHandshake(),I(this,Ht).close()}),I(this,at).closed.then(()=>{I(this,Bt).markPostHandshake(),I(this,Ht).close()})}openSendStream(){return c(this,null,function*(){const A=yield I(this,at).createUnidirectionalStream();return new tQ(A)})}transportType(){return"webtransport"}url(){return I(this,jI)}afterHandshake(){return I(this,Bt).postHandshake()}closed(){return c(this,null,function*(){yield I(this,at).closed})}close(){I(this,at).close()}writeMessage(A){return c(this,null,function*(){yield I(this,Bt).write(A)})}readMessage(){return c(this,null,function*(){return I(this,Bt).read()})}objectStream(){return c(this,null,function*(){return I(this,Ht).pop()})}}at=new WeakMap,Bt=new WeakMap,Ht=new WeakMap,jI=new WeakMap,zI=new WeakMap,$o=new WeakMap,Aa=new WeakSet,zE=function(){return c(this,null,function*(){const A=I(this,at).incomingUnidirectionalStreams.getReader();for(;;){const{value:e,done:t}=yield A.read();if(t){I(this,Ht).close();return}const g=new ro(new Uint8Array,e);yield I(this,Ht).push(eQ(g,I(this,zI))),te(this,zI)._++}})};const Mu=GA.get().createContext("MoqClient");function mB(i){return c(this,null,function*(){const A=new WebSocket(i.wsUrl||i.url);A.binaryType="arraybuffer",yield new Promise((n,o)=>{A.addEventListener("error",()=>o(new Error("WebSocket error")),{once:!0}),A.addEventListener("open",n,{once:!0})});const e=co.wrapWebsocket(A);uQ(e,i.role).catch(n=>{throw Mu.warn("MoQ handshake failed, closing WebSocket",{error:n}),A.close(),n});const t=new Lu(A,e);return new uB(t,i.authToken)})}function vu(i){return c(this,null,function*(){const A="60b82e8021689e163c1041b4475ef9c86e7565bc45d1a0aa43f5148769f461c7",e=new Uint8Array(A.length/2);for(let B=0;B<e.length;B+=1)e[B]=parseInt(A.slice(2*B,2*B+2),16);const t=new WebTransport(i.url,{congestionControl:"low-latency"});yield Promise.race([t.ready,t.closed.then(()=>Promise.reject(new Error("WebTransport closed")))]);const g=yield t.createBidirectionalStream(),n=co.wrapWebTransport(g);uQ(n,i.role).catch(()=>{t.close()});const o=new Ju(t,n,i.url.toString());return new uB(o,i.authToken)})}function Hu(i){return c(this,null,function*(){if(self.WebTransport&&(i==null?void 0:i.preferredTransport)!=="websocket"&&i.url.protocol.startsWith("https")){const A=vu(i).catch(()=>mB(i)),e=yield Promise.race([A,ut(i.websocketFallbackTimeoutMs)]);return e||mB(i)}return mB(i)})}class $e{constructor(){r(this,rt,{name:"",priority:0,groupOrder:"ascending",filterType:{type:"latest-group"}})}name(A){return I(this,rt).name=A,this}priority(A){return I(this,rt).priority=A,this}groupOrder(A){return I(this,rt).groupOrder=A,this}startGroup(A){return I(this,rt).filterType={type:"absolute-start",start:{group:A,object:M(0)}},this}range(A,e){return I(this,rt).filterType={type:"absolute-range",start:{group:A,object:M(0)},end:{group:e,object:M(0)}},this}build(){return I(this,rt)}}rt=new WeakMap;class wQ{constructor(A,e){r(this,Ag);r(this,_I);E(this,Ag,A),E(this,_I,e)}subscribe(A,e=new Map){return I(this,Ag).subscribe(this.namespace(),A,e)}closed(){return I(this,Ag).closed()}namespace(){return I(this,_I).namespace}}Ag=new WeakMap,_I=new WeakMap;function qu(i,A){return["com.vindral.moq",i]}function gi(i){const A=i[1];if(!A)throw new Error("namespace must contain a channel ID");return A}function Ku(i){return"tracks"in i}function Tu(i){const A=new TextDecoder().decode(i);return JSON.parse(A)}const Cr=class Cr{constructor(A,e){r(this,An);r(this,Ie);r(this,Oe);r(this,Mi,new P(100));r(this,de);r(this,$I);r(this,ea,A=>c(this,null,function*(){if(!A)return I(this,Ie).close();if(I(this,de))return;const e=I(this,Mi).items().reduce((t,g)=>t<g?t:g,A);E(this,de,l(this,An,Gr).call(this,e,A)),I(this,de).size===0&&(yield I(this,Ie).close())}));E(this,Ie,A),E(this,Oe,e),A.done().then(t=>c(this,null,function*(){var g;return I(this,ea).call(this,(g=t.finalInfo)==null?void 0:g.group)})).catch(G),E(this,$I,A.groups())}static subscribe(A,e){return c(this,null,function*(){const t=yield A.subscribe(e);return new Cr(t,void 0)})}subscribeId(){return I(this,Ie).id}name(){return I(this,Ie).name}largestGroupId(){return I(this,Oe)}needsRenewal(){return I(this,Ie).expiryState()==="active"&&I(this,de)===void 0}endOfTrack(A){const e=I(this,Mi).items().reduce((t,g)=>t<g?t:g,A);return this.update(e,A)}update(A,e){return c(this,null,function*(){return E(this,de,l(this,An,Gr).call(this,A,e)),I(this,de).size===0&&(yield I(this,Ie).close()),I(this,Ie).update(A,e)})}unsubscribe(){return I(this,Ie).unsubscribe()}next(){return c(this,null,function*(){var t;if(I(this,de)&&I(this,de).size===0)return{done:!0,value:void 0};const A=yield I(this,$I).next();if(A.done)return A;const e=A.value.groupId();return(t=I(this,de))==null||t.delete(e),I(this,Mi).push(e),I(this,Oe)||E(this,Oe,e),E(this,Oe,I(this,Oe)<e?e:I(this,Oe)),A})}return(){return I(this,Ie).return()}[Symbol.asyncIterator](){return this}};Ie=new WeakMap,Oe=new WeakMap,Mi=new WeakMap,de=new WeakMap,$I=new WeakMap,ea=new WeakMap,An=new WeakSet,Gr=function(A,e){const t=new Set;for(let g=A;g<=e;g++)t==null||t.add(g);return I(this,Mi).items().forEach(g=>{t==null||t.delete(g)}),t};let uo=Cr;const Qr=class Qr{constructor(A){r(this,en);r(this,Re);r(this,vi);r(this,Ct,new _t(10));r(this,Ve);r(this,tn,(A,e)=>c(this,null,function*(){var h=[];try{const t=ue(h,yield I(this,Re).lock());const g={subscribeId:t.value.subscribeId()};if(!t.value.needsRenewal()){I(this,Ve).debug("Subscription does not need renewal",g);return}const n=t.value.largestGroupId();const o=n!==void 0;const a=new $e().name(e.name).priority(e.priority).groupOrder(e.groupOrder);g.largestGroupId=n;I(this,Ve).debug("Renewing subscription",g);switch(e.filterType.type){case"absolute-range":I(this,Ve).debug("Absolute range is not renewed",g);return;case"absolute-start":case"latest-group":case"latest-object":o&&a.startGroup(n+M(1));break}const B=a.build();g.newTrack=B;const[C]=yield Promise.all([A.subscribe(B),o?t.value.update(n,n):t.value.unsubscribe()]);C.done().then(()=>l(this,en,Ur).call(this,C)).catch(G);C.expiryNotification().then(()=>I(this,tn).call(this,A,B)).catch(G);const Q=new uo(C,n);t.value=Q;yield I(this,Ct).push(Q);I(this,Ve).info("Subscription renewed",g)}catch(d){var u=d,m=!0}finally{me(h,u,m)}}));E(this,Re,new Vc(A)),E(this,vi,A),E(this,Ve,GA.get().createContext(`Renewable '${A.name()}'`))}static subscribe(A,e,t){return c(this,null,function*(){const g=t==null?void 0:t.params,n=t==null?void 0:t.largestGroupId,o=yield A.subscribe(e,g),a=new Qr(new uo(o,n));return o.done().then(()=>{var B;return l(B=a,en,Ur).call(B,o)}).catch(G),o.expiryNotification().then(()=>{var B;return I(B=a,tn).call(B,A,e)}).catch(G),a})}largestGroupId(){return I(this,Re).unsafeValue().largestGroupId()}update(A,e){return c(this,null,function*(){var g=[];try{const t=ue(g,yield I(this,Re).lock());I(this,Ct).close();return t.value.update(A,e)}catch(n){var o=n,a=!0}finally{me(g,o,a)}})}endOfTrack(A){return c(this,null,function*(){var t=[];try{const e=ue(t,yield I(this,Re).lock());I(this,Ct).close();return e.value.endOfTrack(A)}catch(g){var n=g,o=!0}finally{me(t,n,o)}})}unsubscribe(){return c(this,null,function*(){var e=[];try{const A=ue(e,yield I(this,Re).lock());I(this,Ct).close();return A.value.unsubscribe()}catch(t){var g=t,n=!0}finally{me(e,g,n)}})}return(){return c(this,null,function*(){var e=[];try{const A=ue(e,yield I(this,Re).lock());I(this,Ct).close();return A.value.return()}catch(t){var g=t,n=!0}finally{me(e,g,n)}})}next(){return c(this,null,function*(){var e,t;const A=yield I(this,vi).next();if(A.done){yield(t=(e=I(this,vi)).return)==null?void 0:t.call(e);const g=yield I(this,Ct).pop();if(g)return E(this,vi,g),this.next()}return A})}[Symbol.asyncIterator](){return this}objects(){return lt(this,null,function*(){try{for(var a=EA(this),B,C,Q;B=!(C=yield new rA(a.next())).done;B=!1){var A=C.value;var e=[];try{const h=ue(e,A,!0);yield*Dr(h)}catch(t){var g=t,n=!0}finally{var o=me(e,g,n);o&&(yield new rA(o))}}}catch(C){Q=[C]}finally{try{B&&(C=a.return)&&(yield new rA(C.call(a)))}finally{if(Q)throw Q[0]}}})}};Re=new WeakMap,vi=new WeakMap,Ct=new WeakMap,Ve=new WeakMap,en=new WeakSet,Ur=function(A){return c(this,null,function*(){var e;if(A.unsubscribed()||(e=A.range())!=null&&e.endGroup){I(this,Ve).info("Server initiated subscribe done but the subscription is already closing");return}if(I(this,Re).unsafeValue().subscribeId()!==A.id){I(this,Ve).info("subscribeId mismatch - the subscription already has been renewed");return}return this.return()})},tn=new WeakMap;let ft=Qr;const Yu="catalog";function fQ(i){const A=Tu(i.payload);if(!Ku(A))throw new Error("unexpected catalog type");return A}const ia=class ia{constructor(A,e,t){r(this,ta);r(this,qt);r(this,sn);r(this,gn);r(this,In);E(this,sn,A),E(this,qt,e),E(this,gn,t),E(this,In,l(this,ta,_E).call(this)),this.closed().finally(()=>I(this,qt).close()).catch(G)}catalog(){return I(this,qt)}closed(){return I(this,In)}close(){return c(this,null,function*(){return I(this,qt).close(),(yield I(this,sn).promise).unsubscribe()})}static start(A,e){return c(this,null,function*(){const t=_.fromPromise(ft.subscribe(A,new $e().name(e.catalogName||Yu).groupOrder("ascending").build())),g=_.fromPromise(t.promise.then(B=>B.objects()));if(e.catalog)return new ia(t,new xA(e.catalog),g);const o=yield(yield g.promise).next();if(!o.value)throw new Error("No catalog found");const a=fQ(o.value);return new ia(t,new xA(a),g)})}};qt=new WeakMap,sn=new WeakMap,gn=new WeakMap,In=new WeakMap,ta=new WeakSet,_E=function(){return c(this,null,function*(){const A=yield I(this,gn).promise;try{for(var e=EA(A),t,g,n;t=!(g=yield e.next()).done;t=!1){const o=g.value;if(o.objectStatus!==WA.Normal)continue;const a=fQ(o);I(this,qt).update(a)}}catch(g){n=[g]}finally{try{t&&(g=e.return)&&(yield g.call(e))}finally{if(n)throw n[0]}}})};let wB=ia;class Pu{constructor(A,e,t,g){r(this,an);r(this,nn);r(this,eg);r(this,on);s(this,"track");r(this,tg,GA.get().createContext("CmafGroup"));this.track=g,E(this,nn,t),E(this,eg,A),E(this,on,e)}[Symbol.asyncIterator](){return lt(this,null,function*(){const A={name:this.track.trackObject.name,namespace:this.track.namespace};I(this,tg).debug("start",f({},A));try{for(var e=EA(I(this,eg)),t,g,n;t=!(g=yield new rA(e.next())).done;t=!1){const o=g.value;if(o.objectStatus===WA.EndOfTrackAndGroup&&(yield new rA(this.track.endOfTrack(o.groupId))),o.objectStatus!==WA.Normal)continue;const a=I(this,on).createFragment(o.payload),B=a.timescale(),C=a.baseMediaDecodeTime()/B*1e3,Q=a.duration()/B*1e3,h=C+Q,d=I(this,nn)/1e3*B;a.updateBaseMediaDecodeTime(a.baseMediaDecodeTime()-d);const u=this.track.timestampRange();if(u&&C>=u[1])break;I(this,tg).debug("fragment",V(f({},A),{startTime:C,endTime:h,subscribeId:o.subscribeId,groupId:o.groupId,objectId:o.objectId,streamId:o.streamId})),yield[o.groupId,a]}}catch(g){n=[g]}finally{try{t&&(g=e.return)&&(yield new rA(g.call(e)))}finally{if(n)throw n[0]}}I(this,tg).debug("end",f({},A))})}[Me()](){return l(this,an,br).call(this)}[Symbol.asyncDispose](){return l(this,an,br).call(this)}}nn=new WeakMap,eg=new WeakMap,on=new WeakMap,tg=new WeakMap,an=new WeakSet,br=function(){return c(this,null,function*(){var A,e;return yield(e=(A=I(this,eg)).return)==null?void 0:e.call(A),Promise.resolve()})};const ig=class ig{constructor(A,e,t,g,n){r(this,Bn);r(this,Ze);r(this,rn);r(this,Cn);s(this,"trackObject");s(this,"namespace");this.trackObject=A,this.namespace=e,E(this,Ze,t),E(this,Bn,g),E(this,rn,n)}static subscribe(o,a,B){return c(this,arguments,function*(A,e,{timestampOffsetMs:t,startGroup:g,params:n}){var m;if(e.format!=="cmaf")throw new Error("format must be cmaf");const C=new $e().name(e.name);g&&C.startGroup(g);const Q=C.build();if(e.initTrack){const p=new $e().name(e.initTrack).build(),[y,k]=yield Promise.all([l(m=ig,sa,$E).call(m,A,p),ft.subscribe(A,Q,{params:n,largestGroupId:g?g-M(1):void 0})]),N=new HC(y);return new ig(e,A.namespace(),k,N,t)}lA(e.initData,"no init data found on track");const h=Mr(e.initData),d=new HC(new Uint8Array(h)),u=yield ft.subscribe(A,Q,{params:n,largestGroupId:g?g-M(1):void 0});return new ig(e,A.namespace(),u,d,t)})}largestGroupId(){return I(this,Ze).largestGroupId()}stopAfterTimestampReached(A){E(this,Cn,[0,A])}timestampRange(){return I(this,Cn)}endOfTrack(A){return I(this,Ze).endOfTrack(A)}update(A,e){return I(this,Ze).update(A,e)}unsubscribe(){return c(this,null,function*(){return I(this,Ze).unsubscribe()})}next(){return c(this,null,function*(){const A=yield I(this,Ze).next();return A.done?A:{done:!1,value:new Pu(A.value,I(this,Bn),I(this,rn),this)}})}return(){return c(this,null,function*(){return yield I(this,Ze).return(),{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[Me()](){return this.unsubscribe()}[Symbol.asyncDispose](){return c(this,null,function*(){return this.unsubscribe()})}};Bn=new WeakMap,Ze=new WeakMap,rn=new WeakMap,Cn=new WeakMap,sa=new WeakSet,$E=function(A,e){return c(this,null,function*(){var n=[];try{const t=ue(n,yield A.subscribe(e),!0);const g=yield t.objects().next();if(g.done)throw new Error("No init object");yield t.close();return g.value.payload}catch(o){var a=o,B=!0}finally{var C=me(n,a,B);C&&(yield C)}})},r(ig,sa);let fB=ig;const DQ=1e4,xu=3e4,Er=class Er{constructor(A,e,t){r(this,qi);r(this,ga,GA.get().createContext("Timeline"));r(this,Kt,new xA([]));r(this,Hi);r(this,Qn);r(this,En);r(this,cn);E(this,Qn,A),E(this,En,t),E(this,Hi,e),E(this,cn,l(this,qi,Nr).call(this,I(this,Hi))),this.closed().finally(()=>I(this,Kt).close()).catch(G)}closed(){return I(this,cn)}close(){return c(this,null,function*(){return(yield I(this,Hi).promise).unsubscribe()})}timeline(){const[A,e]=I(this,Kt).value();return A}timestampWallclockOffset(){return we(this.timeline().map(A=>A.mediaPts-A.wallclock))}static start(A,e){const t=_.fromPromise(ft.subscribe(A,new $e().name(e).groupOrder("ascending").build()));return new Er(A,t,e)}waitForWallclockTime(A){return c(this,null,function*(){return yield I(this,Kt).waitFor(e=>!!e.find(t=>t.wallclock>=A)),this.timeline()})}waitForTimelineToHaveMinDuration(){return c(this,null,function*(){return yield I(this,Kt).waitFor(A=>{const e=A[0],t=A[A.length-1];return!e||!t?!1:t.wallclock-e.wallclock>DQ}),this.timeline()})}};ga=new WeakMap,Kt=new WeakMap,Hi=new WeakMap,Qn=new WeakMap,En=new WeakMap,cn=new WeakMap,qi=new WeakSet,Nr=function(A){return c(this,null,function*(){const e=yield A.promise;try{for(var u=EA(e),m,p,y;m=!(p=yield u.next()).done;m=!1){var a=p.value;var B=[];try{const k=ue(B,a,!0);try{for(var t=EA(k),g,n,o;g=!(n=yield t.next()).done;g=!1){const N=n.value;if(N.objectStatus!==WA.Normal)continue;const U=Wu(N.payload);I(this,Kt).update(K=>{var W,Z;for(K.push(...U),K.sort((j,QA)=>j.wallclock-QA.wallclock);K[0]&&((Z=(W=K[K.length-1])==null?void 0:W.wallclock)!=null?Z:0)-K[0].wallclock>xu;)K.shift();return K}),e===I(this,Hi).resolved&&N.groupId>M(0)&&N.objectId==M(0)&&l(this,qi,Ac).call(this,N.groupId).catch(K=>{I(this,ga).warn("backfill failed",K)})}}catch(n){o=[n]}finally{try{g&&(n=t.return)&&(yield n.call(t))}finally{if(o)throw o[0]}}}catch(C){var Q=C,h=!0}finally{var d=me(B,Q,h);d&&(yield d)}}}catch(p){y=[p]}finally{try{m&&(p=u.return)&&(yield p.call(u))}finally{if(y)throw y[0]}}})},Ac=function(A){return c(this,null,function*(){const e=A-M(1),t=this.timeline(),g=t[0],n=t[t.length-1];if(!g||!n||n.wallclock-g.wallclock>DQ)return;const o=_.fromPromise(ft.subscribe(I(this,Qn),new $e().name(I(this,En)).groupOrder("ascending").range(e,e).build()));return l(this,qi,Nr).call(this,o)})};let DB=Er;function Wu(i){var e;const A=new TextDecoder("utf-8").decode(i).split(`
49
49
  `);return(e=A[0])!=null&&e.startsWith("MEDIA_PTS")&&A.shift(),A.filter(t=>t.length>0).map(t=>{const[g,n,o,a,B]=t.split(",");if(!g||!a)throw new Error(`invalid timeline row: ${t}`);return{mediaPts:parseInt(g),groupId:n?parseInt(n):void 0,objectId:o?parseInt(o):void 0,wallclock:parseInt(a),metadata:B}})}function Ou(i){return typeof i.language=="string"}const cr=class cr{constructor(A,e,t,g,n){r(this,Ia,new ZC);r(this,hn);r(this,Tt);r(this,sg,0);s(this,"trackObject");s(this,"namespace");E(this,Tt,A),E(this,hn,e),this.trackObject=t,this.namespace=g,E(this,sg,n)}static subscribe(A,e,t){return c(this,null,function*(){if(!Ou(e))throw new Error("track object language is required");const g=new $e().name(e.name).build(),n=yield ft.subscribe(A,g),o=n.objects();return new cr(n,o,e,A.namespace(),t)})}largestGroupId(){return I(this,Tt).largestGroupId()}update(A,e){return I(this,Tt).update(A,e)}unsubscribe(){return I(this,Tt).unsubscribe()}next(){return c(this,null,function*(){for(;;){const A=yield I(this,hn).next();if(A.done)return A;if(A.value.objectStatus!==WA.Normal)continue;const e=new TextDecoder().decode(A.value.payload),t=I(this,Ia).parse(e).map(n=>(n.startTime-=I(this,sg)/1e3,n.endTime-=I(this,sg)/1e3,n));return{done:!1,value:{language:this.trackObject.language,cues:t}}}})}return(){return c(this,null,function*(){return yield I(this,Tt).return(),{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[Me()](){return this.unsubscribe()}[Symbol.asyncDispose](){return this.unsubscribe()}};Ia=new WeakMap,hn=new WeakMap,Tt=new WeakMap,sg=new WeakMap;let SB=cr;rE=[$A({context:"Channel",enter:"info"})];const Ig=class Ig{constructor(A,e,t,g,n){r(this,gg);s(this,"namespace");r(this,Ki);r(this,Ti);r(this,Yi);r(this,Yt);this.namespace=g,E(this,Ki,A),E(this,Ti,e),E(this,Yi,t),E(this,Yt,n)}static start(A,e){return c(this,null,function*(){const t=new wQ(A,{namespace:e.namespace}),[g,n]=yield Promise.all([DB.start(t,"timeline"),wB.start(t,{catalog:e.catalog,namespace:e.namespace})]);return new Ig(t,g,n,e.namespace,0)})}closed(){return I(this,Yi).closed()}catalog(){return I(this,Yi).catalog()}timestampWallclockOffset(){return I(this,Ti).timestampWallclockOffset()}timestampOffsetMs(){return I(this,Yt)}setTimestampOffsetMs(A){E(this,Yt,A)}waitForWallclockTime(A){return I(this,Ti).waitForWallclockTime(A)}subscribeCmafTrack(A,e){const t=e==null?void 0:e.startGroup,g=e==null?void 0:e.params,n=this.catalog().current().tracks,o=A["com.vindral.variant_uid"]!==void 0?n.find(a=>a["com.vindral.variant_uid"]===A["com.vindral.variant_uid"]):void 0;return l(this,gg,va).call(this,()=>fB.subscribe(I(this,Ki),o!=null?o:A,{timestampOffsetMs:I(this,Yt),startGroup:t,params:g}))}subscribeWebVttTrack(A){return l(this,gg,va).call(this,()=>SB.subscribe(I(this,Ki),A,I(this,Yt)))}subscribeTrack(A){return l(this,gg,va).call(this,()=>I(this,Ki).subscribe(A))}close(){return Promise.all([I(this,Yi).close(),I(this,Ti).close()])}};hr=zi(null),Ki=new WeakMap,Ti=new WeakMap,Yi=new WeakMap,Yt=new WeakMap,gg=new WeakSet,va=function(A){return c(this,null,function*(){const[e,t]=this.catalog().value();try{return yield A()}catch(g){if(e===this.catalog().current()&&t&&(yield Promise.race([t,ut(500)])),e!==this.catalog().current())return A();throw g}})},_A(hr,9,"start",rE,Ig),jt(hr,Ig),_i(hr,3,Ig);let mo=Ig;const Vu=M(8);function Zu(i){if(i<0||i>65535)throw new RangeError("burstMs must be between 0 and 65535 inclusive");const A=new Uint8Array([i>>8&255,i&255]);return{type:Vu,payload:A}}const dr=class dr{constructor(A){r(this,na);r(this,Pi);r(this,dn);const[e,t]=A.value.value();E(this,Pi,{createdAt:new Date,wallclock:new Date(e.ntpTimestamp),rtt:e.rtt}),E(this,dn,l(this,na,ec).call(this,A))}wallclock(){const e=Date.now()-I(this,Pi).createdAt.getTime();return I(this,Pi).wallclock.getTime()+e}closed(){return I(this,dn)}static start(A){return new dr(A)}};Pi=new WeakMap,dn=new WeakMap,na=new WeakSet,ec=function(A){return c(this,null,function*(){try{for(var e=EA(A.value),t,g,n;t=!(g=yield e.next()).done;t=!1){const o=g.value;E(this,Pi,{createdAt:new Date,wallclock:new Date(o.ntpTimestamp),rtt:o.rtt})}}catch(g){n=[g]}finally{try{t&&(g=e.return)&&(yield g.call(e))}finally{if(n)throw n[0]}}})};let pB=dr;function wo(i){return typeof i=="string"||i===null||i===void 0}function Xu(i){return"provider"in i&&typeof i.provider=="string"&&(!("widevineLicenseUrl"in i)||wo(i.widevineLicenseUrl))&&(!("playreadyLicenseUrl"in i)||wo(i.playreadyLicenseUrl))&&(!("fairplayLicenseUrl"in i)||wo(i.fairplayLicenseUrl))&&(!("fairplayCertificate"in i)||wo(i.fairplayCertificate))}function ju(i){try{return Mr(i)}catch(A){throw new Error("Failed to convert fairplayCertificate")}}function zu(i){const A=new TextDecoder().decode(i),e=JSON.parse(A);if(!Xu(e))throw new Error("Invalid drm object");const n=e,{fairplayCertificate:t}=n,g=uE(n,["fairplayCertificate"]);return V(f({},g),{fairplayCertificate:t?ju(t):void 0})}class yB{constructor(A){s(this,"value");this.value=A}static create(A,e,t){return c(this,null,function*(){var B=[];try{const g=ue(B,yield A.subscribeTrack(new $e().name("drm").build()),!0);const n=g.objects();const o=yield n.next();if(o.done)throw new Error("No drm object received");const a=zu(o.value.payload);return new yB(V(f({},a),{videoCodec:e,audioCodec:t}))}catch(C){var Q=C,h=!0}finally{var d=me(B,Q,h);d&&(yield d)}})}}function _u(i){return"rtt"in i&&typeof i.rtt=="number"&&"ntpTimestamp"in i&&typeof i.ntpTimestamp=="number"&&"estimatedBandwidth"in i&&typeof i.estimatedBandwidth=="number"}function SQ(i){const A=new TextDecoder().decode(i),e=JSON.parse(A);if(!_u(e))throw new Error("Invalid stats object");return e}const $u=1e4,lr=class lr{constructor(A,e,t){r(this,oa);s(this,"ip");s(this,"value");r(this,ln);this.ip=t,this.value=new xA(e),E(this,ln,l(this,oa,tc).call(this,A))}closed(){return I(this,ln)}idleTimeout(){return c(this,null,function*(){for(;;){const[A,e]=this.value.value();try{yield Promise.race([xa($u,new Error("Idle timeout")),e])}catch(t){return t}}})}static start(A){return c(this,null,function*(){const t=(yield A.subscribe(new $e().name("stats").groupOrder("ascending").build())).objects(),g=yield t.next();if(g.done)throw new Error("No stats object received");const n=SQ(g.value.payload);if(!n.ip)throw new Error("Expected IP in initial stats object");return new lr(t,n,n.ip)})}};ln=new WeakMap,oa=new WeakSet,tc=function(A){return c(this,null,function*(){try{for(var e=EA(A),t,g,n;t=!(g=yield e.next()).done;t=!1){const o=g.value;if(o.objectStatus!==WA.Normal)continue;const a=SQ(o.payload);this.value.update(a)}}catch(g){n=[g]}finally{try{t&&(g=e.return)&&(yield g.call(e))}finally{if(n)throw n[0]}}})};let FB=lr;class Am{constructor(A){r(this,aa,GA.get().createContext("UpstreamWatcher"));r(this,ng);E(this,ng,new xA(_.fromPromise(A.closed())))}update(A){I(this,ng).update(_.fromPromise(A.closed()))}closed(){return c(this,null,function*(){try{for(;;){const[A,e]=I(this,ng).value();let t=!1;yield Promise.race([e==null?void 0:e.then(()=>t=!0),A.promise.then(()=>{if(!t)throw I(this,aa).warn("Upstream closed"),new Error("Upstream closed")})])}}catch(A){return A}})}}aa=new WeakMap,ng=new WeakMap;class kB{constructor(A,e){r(this,og,GA.get().createContext("TracksIterator"));r(this,un);r(this,mn);E(this,un,A),E(this,mn,e)}[Symbol.asyncIterator](){return lt(this,null,function*(){const A=I(this,mn);try{for(var e=EA(I(this,un)),t,g,n;t=!(g=yield new rA(e.next())).done;t=!1){const o=g.value;if(!o)continue;const a={name:o.trackObject.name,namespace:o.namespace};I(this,og).debug("track start",f({mediaType:A},a)),yield*Dr(o),I(this,og).debug("track end",f({mediaType:A},a))}}catch(g){n=[g]}finally{try{t&&(g=e.return)&&(yield new rA(g.call(e)))}finally{if(n)throw n[0]}}I(this,og).debug("tracks ended",{mediaType:A})})}}og=new WeakMap,un=new WeakMap,mn=new WeakMap;let em=(EE=[$A({context:"Player",enter:"info"})],QE=[$A({context:"Player",enter:"info",return:"info"})],CE=[$A({context:"Player",enter:"info"})],Qt=class{constructor(A,e,t){_i(fn,5,this);r(this,VA);r(this,ag);r(this,Bg);r(this,xi);r(this,HA);r(this,Ge,new xA(void 0));r(this,Ue,new xA(void 0));r(this,Pt,new xA(void 0));r(this,rg);r(this,wn);s(this,"subtitles",new kB(I(this,Pt),"subtitles"));s(this,"video",new kB(I(this,Ue),"video"));s(this,"audio",new kB(I(this,Ge),"audio"));E(this,ag,A),E(this,Bg,pB.start(t)),E(this,xi,t),E(this,HA,new xA(e)),E(this,rg,new Am(e)),E(this,wn,Promise.race([t.idleTimeout(),l(this,VA,ic).call(this),I(this,rg).closed()])),I(this,ag).closed().then(()=>this.close()).catch(G)}closed(){return I(this,wn)}static start(A,e){return c(this,null,function*(){const t=new Map;if(e.burstMs!==void 0){const Q=Zu(e.burstMs);t.set(Q.type,Q)}const g=new wQ(A,{namespace:qu("auxiliary")}),[[n,o,a],B]=yield Promise.all([mo.start(A,e).then(Q=>Promise.all([Promise.resolve(Q),e.videoTrack?Q.subscribeCmafTrack(e.videoTrack,{params:t}):void 0,e.audioTrack?Q.subscribeCmafTrack(e.audioTrack,{params:t}):void 0])),FB.start(g)]),C=new Qt(A,n,B);return a&&I(C,Ge).update(a),o&&I(C,Ue).update(o),C})}connectionInfo(){const A=I(this,xi).value.current();return{ip:I(this,xi).ip,rtt:A.rtt,estimatedBandwidth:A.estimatedBandwidth}}stats(){return I(this,xi).value}catalog(){return I(this,HA).current().catalog()}namespace(){return I(this,HA).current().namespace}videoTrack(){var A;return(A=I(this,Ue).current())==null?void 0:A.trackObject}audioTrack(){var A;return(A=I(this,Ge).current())==null?void 0:A.trackObject}referenceClock(){return I(this,Bg)}drm(){return c(this,null,function*(){var e,t;if(this.catalog().current().tracks.find(({name:g})=>g==="drm"))return yB.create(I(this,HA).current(),(e=this.videoTrack())==null?void 0:e.codec,(t=this.audioTrack())==null?void 0:t.codec)})}close(){return Promise.all([I(this,HA).current().close(),I(this,HA).close(),l(this,VA,Ha).call(this,I(this,Ge)),l(this,VA,Ha).call(this,I(this,Ue)),l(this,VA,Ha).call(this,I(this,Pt))])}zap(A,e){return c(this,null,function*(){var m,p;const t=yield mo.start(I(this,ag),A),g=I(this,Bg).wallclock()-e,n=I(this,HA).current(),o=n.timestampWallclockOffset(),a=yield t.waitForWallclockTime(g);I(this,rg).update(t),yield I(this,HA).current().close();const B=a.toReversed().find(y=>y.wallclock<=g),C=B!=null&&B.mediaPts?B.mediaPts-n.timestampOffsetMs():void 0,d=t.timestampWallclockOffset()-o+n.timestampOffsetMs();t.setTimestampOffsetMs(d);const u=B!=null&&B.groupId?M(B.groupId):void 0;C&&((m=I(this,Ue).current())==null||m.stopAfterTimestampReached(C),(p=I(this,Ge).current())==null||p.stopAfterTimestampReached(C)),I(this,HA).update(t),yield Promise.all([A.videoTrack?this.setVideoTrack(A.videoTrack,u):void 0,A.audioTrack?this.setAudioTrack(A.audioTrack,u):void 0])})}setSubtitleTrack(A){return c(this,null,function*(){var t,g;if(!A){yield(t=I(this,Pt).current())==null?void 0:t.unsubscribe();return}const[e]=yield Promise.all([I(this,HA).current().subscribeWebVttTrack(A),(g=I(this,Pt).current())==null?void 0:g.unsubscribe()]);I(this,Pt).update(e)})}setVideoTrack(A,e){return c(this,null,function*(){const t=yield l(this,VA,Ln).call(this,I(this,HA).current(),A,I(this,Ue).current(),e);I(this,Ue).update(t)})}setAudioTrack(A,e){return c(this,null,function*(){const t=yield l(this,VA,Ln).call(this,I(this,HA).current(),A,I(this,Ge).current(),e);I(this,Ge).update(t)})}},fn=zi(null),ag=new WeakMap,Bg=new WeakMap,xi=new WeakMap,HA=new WeakMap,Ge=new WeakMap,Ue=new WeakMap,Pt=new WeakMap,rg=new WeakMap,wn=new WeakMap,VA=new WeakSet,Ha=function(A){const e=A.current(),t=e==null?void 0:e.largestGroupId();return A.isClosed()||A.update(void 0),A.close(),t?e==null?void 0:e.update(t,t):e==null?void 0:e.unsubscribe()},Ln=function(A,e,t,g){return c(this,null,function*(){const n=t==null?void 0:t.largestGroupId(),[o,a]=yield Promise.all([A.subscribeCmafTrack(e,{startGroup:g||(n?n+M(1):void 0)}),n?t==null?void 0:t.update(n,n):t==null?void 0:t.unsubscribe()]);return o})},ic=function(){return c(this,null,function*(){try{for(var n=EA(I(this,HA)),o,a,B;o=!(a=yield n.next()).done;o=!1){const C=a.value;try{for(var A=EA(C.catalog()),e,t,g;e=!(t=yield A.next()).done;e=!1){const Q=t.value;yield Promise.all([l(this,VA,Lr).call(this,Q,I(this,Ue)),l(this,VA,Lr).call(this,Q,I(this,Ge))])}}catch(t){g=[t]}finally{try{e&&(t=A.return)&&(yield t.call(A))}finally{if(g)throw g[0]}}}}catch(a){B=[a]}finally{try{o&&(a=n.return)&&(yield a.call(n))}finally{if(B)throw B[0]}}})},Lr=function(A,e){return c(this,null,function*(){const t=e.current();if(!t)return;const g=t.trackObject.name,n=t.trackObject["com.vindral.variant_uid"],o=A.tracks.find(B=>B.name===g),a=A.tracks.find(B=>B["com.vindral.variant_uid"]===n);if(!o){if(!a){e.update(void 0);return}e.update(yield I(this,HA).current().subscribeCmafTrack(a))}})},_A(fn,1,"close",EE,Qt),_A(fn,1,"zap",QE,Qt),Ln=_A(fn,17,"#replaceTrack",CE,VA,Ln),jt(fn,Qt),Qt);function RB(i,A,e){const t=new URL("/voq/subscribe",i);return t.searchParams.set("sessionId",A.sessionId),t.searchParams.set("clientId",A.clientId),t.searchParams.set("channelId",A.channelId),e&&t.searchParams.set("authToken",e),t}const tm=1e4,ur=class ur{constructor(A,e,t,g,n,o,a){r(this,DA);r(this,kA);r(this,ZA);r(this,ne);r(this,Dn,"disconnected");r(this,dA);r(this,xt,new Map);r(this,Sn);r(this,Cg);r(this,pn);r(this,Qg,new Map);r(this,Eg,A=>{if(!A){I(this,dA).setSubtitleTrack(void 0).catch(G);return}const e=I(this,xt).get(gi(I(this,dA).namespace())),t=e==null?void 0:e.getTextTrack(A);t&&I(this,dA).setSubtitleTrack(t).catch(G)});r(this,yn,A=>{switch(A.type){case"subscribe":{if(I(this,cg)){I(this,ZA).info("Ignoring - we are already switching");return}E(this,cg,!0),l(this,DA,Ic).call(this,A.subscription).catch(e=>{I(this,ZA).error("error handling subscription",e),I(this,kA).emit("received signal",{type:"subscription changed",subscription:A.subscription,reset:!0})}).finally(()=>E(this,cg,!1))}break;case"telemetry":zC(new URL("/api/telemetry",I(this,ne).url().replace("wss://","https://")),{body:A.body,headers:{"Content-Type":"text/plain"}}).catch(G);break;case"refresh auth":I(this,ne).updateAuthToken(A.token);break}});r(this,cg,!1);s(this,"disconnect",(A="Disconnect Requested")=>{I(this,ZA).info("Disconnecting",A),I(this,ne).close(),I(this,dA).close().catch(G),E(this,Qg,new Map),l(this,DA,Jn).call(this,"disconnected")});E(this,kA,A),E(this,ZA,e),E(this,ne,t),E(this,dA,g),E(this,xt,n),E(this,Sn,o),E(this,Cg,a),I(this,kA).on("send signal",I(this,yn)),I(this,kA).on("disconnect",this.disconnect),I(this,kA).on("text track",I(this,Eg)),l(this,DA,sc).call(this).catch(G),l(this,DA,nc).call(this).catch(G)}get estimatedBandwidth(){return I(this,pn)}unload(){I(this,kA).off("send signal",I(this,yn)),I(this,kA).off("disconnect",this.disconnect),I(this,kA).off("text track",I(this,Eg)),this.disconnect()}suspend(){}unsuspend(){}getStatistics(){const e=I(this,ne).transportType()==="webtransport"?"moq":"moq_ws";return{edgeUrl:I(this,ne).url(),connectionProtocol:e}}static start(A,e,t,g,n){return c(this,null,function*(){var U,K,W,Z;const o=new Map(g.connectInfo.channels.map(j=>[gi(j.catalog.namespace),new UB(new xA(j.catalog))])),a=yield g.onConnectInfo(g.connectInfo),B=g.options.get("authenticationToken");let C,Q;typeof g.edgeUrl==="string"?C=RB(g.edgeUrl,a,B):(C=RB(g.edgeUrl.moqUrl||g.edgeUrl.moqWsUrl,a,B),Q=RB(g.edgeUrl.moqWsUrl,a,B));const h=(U=g.connectInfo.channels.find(j=>j.channelId===a.channelId))==null?void 0:U.catalog;e.debug("Resolved edge url",{edgeUrl:C,edgeWsUrl:Q}),lA(h,"no catalog found");const d=(K=o.get(gi(h.namespace)))==null?void 0:K.getVideoTrack(a.video),u=(W=o.get(gi(h.namespace)))==null?void 0:W.getAudioTrack(a.audio),m=yield Hu({url:C,wsUrl:Q,authToken:g.options.get("authenticationToken"),preferredTransport:g.options.get("webtransportEnabled")?"webtransport":"websocket",role:ru.Subscriber,websocketFallbackTimeoutMs:2e3}),p=m.closed().then(j=>{throw j instanceof Error?j:new Error(j?`Session closed before player started: ${String(j)}`:"Session closed before player started")}),y=yield Promise.race([em.start(m.subscriber,{namespace:h.namespace,catalog:h,videoTrack:d==null?void 0:d.track,audioTrack:u==null?void 0:u.track,burstMs:a.burstMs||0}),xa(tm,new Error("Timeout waiting for player to start")),p]),k=new UB(y.catalog());o.set(gi(h.namespace),k),A.emit("received signal",{type:"client ip",ip:y.connectionInfo().ip}),y.drm().then(j=>{j&&A.emit("received drm data",j.value)}).catch(j=>{e.error("Error getting DRM data",j)});const N=new ur(A,e,m,y,o,t,n);return a.textTrack&&I(Z=N,Eg).call(Z,a.textTrack),N})}getState(){return I(this,Dn)}close(){I(this,ne).close()}closed(){return Promise.race([I(this,ne).closed(),I(this,dA).closed()])}};kA=new WeakMap,ZA=new WeakMap,ne=new WeakMap,Dn=new WeakMap,dA=new WeakMap,xt=new WeakMap,Sn=new WeakMap,Cg=new WeakMap,pn=new WeakMap,Qg=new WeakMap,DA=new WeakSet,sc=function(){return c(this,null,function*(){I(this,ne).transportType()==="websocket"&&(yield ut(5e3));try{for(var A=EA(I(this,dA).stats()),e,t,g;e=!(t=yield A.next()).done;e=!1){const{rtt:n,estimatedBandwidth:o}=t.value;E(this,pn,o),I(this,Cg).push(n),I(this,kA).emit("rtt",we(I(this,Cg).items()))}}catch(t){g=[t]}finally{try{e&&(t=A.return)&&(yield t.call(A))}finally{if(g)throw g[0]}}})},Eg=new WeakMap,yn=new WeakMap,cg=new WeakMap,gc=function(A){return c(this,null,function*(){var g;const e=yield I(this,Sn).connect({channelId:A});if(!tC(e))throw new Error("no moq connect info found");const t=(g=e.channels.find(n=>n.channelId===A))==null?void 0:g.catalog;if(!t)throw new Error("no catalog found");return t})},Ic=function(A){return c(this,null,function*(){var o,a,B;I(this,ZA).info("handle subscription",A);const e=I(this,dA);let t=I(this,xt).get(A.channelId);if(t||(t=new UB(new xA(yield l(this,DA,gc).call(this,A.channelId))),I(this,xt).set(A.channelId,t)),e.namespace().join("/")!==t.namespace().join("/")){I(this,ZA).info("changing channel",A.channelId);const C=t.getVideoTrack(A.video),Q=t.getAudioTrack(A.audio);yield e.zap({namespace:t.namespace(),catalog:t.catalog(),videoTrack:C==null?void 0:C.track,audioTrack:Q==null?void 0:Q.track},500),e.drm().then(h=>{h&&I(this,kA).emit("received drm data",h.value)}).catch(h=>{I(this,ZA).error("Error getting DRM data",h)}),I(this,ZA).info("switched channel",A.channelId),(o=I(this,xt).get(gi(e.namespace())))==null||o.updateCatalog(e.catalog()),I(this,kA).emit("received signal",{type:"subscription changed",subscription:A});return}const g=t.getVideoTrack(A.video),n=t.getAudioTrack(A.audio);yield Promise.all([g&&g.track.name!==((a=I(this,dA).videoTrack())==null?void 0:a.name)?I(this,dA).setVideoTrack(g.track):void 0,n&&n.track.name!==((B=I(this,dA).audioTrack())==null?void 0:B.name)?I(this,dA).setAudioTrack(n.track):void 0]),I(this,kA).emit("received signal",{type:"subscription changed",subscription:A})})},Jn=function(A){E(this,Dn,A),I(this,kA).emit("connection state",A)},nc=function(){return c(this,null,function*(){try{l(this,DA,Jn).call(this,"connecting"),I(this,ZA).info("Connecting..."),l(this,DA,Jn).call(this,"connected"),yield Promise.all([l(this,DA,Jr).call(this,I(this,dA).referenceClock(),I(this,dA).audio),l(this,DA,Jr).call(this,I(this,dA).referenceClock(),I(this,dA).video),l(this,DA,oc).call(this,I(this,dA).subtitles)]),yield I(this,dA).closed(),I(this,ne).close(),I(this,ZA).info("Session closed")}catch(A){I(this,ZA).warn("Session error",A)}finally{l(this,DA,Jn).call(this,"disconnected")}})},oc=function(A){return c(this,null,function*(){try{for(var e=EA(A),t,g,n;t=!(g=yield e.next()).done;t=!1){const o=g.value;I(this,kA).emit("text track data",o)}}catch(g){n=[g]}finally{try{t&&(g=e.return)&&(yield g.call(e))}finally{if(n)throw n[0]}}})},Jr=function(A,e){return c(this,null,function*(){var a;let t="",g="",n;const o=I(this,dA).videoTrack()===void 0;try{for(var d=EA(e),u,m,p;u=!(m=yield d.next()).done;u=!1){const y=m.value;const k=gi(y.track.namespace),N=y.track.trackObject.language,U=Oa((a=y.track.trackObject.codec)!=null?a:""),K=y.track.trackObject.codec,W=U?mt({codec:U,codecString:K}):void 0,Z=!!y.track.trackObject["com.vindral.drm"];try{for(var B=EA(y),C,Q,h;C=!(Q=yield B.next()).done;C=!1){const[j,QA]=Q.value;const ee={channelId:t!==""&&(o||QA.mediaType()==="video")&&t!==k?k:void 0,language:QA.mediaType()==="audio"&&g!==N?N:void 0,drmTransition:n!==void 0&&n!==Z};t=k,g=N,n=Z;const qA=QA.producerReferenceTime(),XA=I(this,Qg).get(y.track.namespace)||0;if(qA&&Date.now()-XA>1e3){I(this,Qg).set(y.track.namespace,Date.now());const jA=A.wallclock()-qA.getTime();I(this,ZA).debug("timing-info",{mediaType:QA.mediaType(),referenceClock:A,delta:jA,groupId:j,timestamp:QA.baseMediaDecodeTime()/QA.timescale()*1e3+jA,wallclockTime:qA.getTime()}),I(this,kA).emit("received signal",{type:"timing info",timingInfo:{channelId:k,timestamp:QA.baseMediaDecodeTime()/QA.timescale()*1e3+jA,wallclockTime:qA.getTime()}})}I(this,kA).emit("received moq data",{payload:QA,channelId:k,groupId:j,mimeType:W,codec:U,switchInfo:ee,renditionId:im(y.track.trackObject.name)})}}catch(Q){h=[Q]}finally{try{C&&(Q=B.return)&&(yield Q.call(B))}finally{if(h)throw h[0]}}}}catch(m){p=[m]}finally{try{u&&(m=d.return)&&(yield m.call(d))}finally{if(p)throw p[0]}}})};let GB=ur;function im(i){return i.split("").reduce((e,t)=>e=t.charCodeAt(0)+(e<<6)+(e<<16)-e,0)}class UB{constructor(A){r(this,Ba);r(this,Et);r(this,Wi);E(this,Et,A),E(this,Wi,l(this,Ba,ac).call(this))}catalog(){return I(this,Et).current()}namespace(){return I(this,Et).current().namespace}updateCatalog(A){E(this,Et,A)}getTextTrack(A){return I(this,Et).current().tracks.find(e=>e.label===A)}getAudioTrack(A){if(!A.codec)return;const e=I(this,Wi).filter(t=>!(!ti(t)||t.bitRate>A.bitRate||A.codec&&t.codec!==A.codec||A.language&&t.language!==A.language));return e[e.length-1]}getVideoTrack(A){if(!A.codec)return;const e=I(this,Wi).filter(t=>!(!ei(t)||t.bitRate>A.bitRate||A.codec&&t.codec!==A.codec));return e[e.length-1]}renditions(){return I(this,Wi)}}Et=new WeakMap,Wi=new WeakMap,Ba=new WeakSet,ac=function(){const[A,e]=I(this,Et).value();return iC(A)};const sm=(i,A)=>{const e=new URL("/subscribe",i);return e.searchParams.append("channelId",A.channelId),e.searchParams.append("sessionId",A.sessionId),e.searchParams.append("clientId",A.clientId),A.audio&&A.audio.codec&&(e.searchParams.append("audio.bitRate",Math.round(A.audio.bitRate).toString()),e.searchParams.append("audio.codec",A.audio.codec),A.audio.language&&e.searchParams.append("audio.language",A.audio.language)),A.video&&A.video.codec&&(e.searchParams.append("video.width",A.video.width.toString()),e.searchParams.append("video.height",A.video.height.toString()),e.searchParams.append("video.bitRate",Math.round(A.video.bitRate).toString()),e.searchParams.append("video.codec",A.video.codec)),A.expectAdditionalConnection&&e.searchParams.append("expectAdditionalConnection",A.expectAdditionalConnection.toString()),A.burstMs&&e.searchParams.append("burstMs",A.burstMs.toString()),A.channelGroupId&&e.searchParams.append("channelGroupId",A.channelGroupId),A.authToken&&(e.searchParams.append("auth.token",A.authToken),e.searchParams.append("auth.type","jwt")),e.toString()};class gm extends ie{constructor(e,t){super();s(this,"options");s(this,"websockets",[]);s(this,"logger");s(this,"reconnectState",{reconnectRetries:0});s(this,"isSuspended",!1);s(this,"_connectionAttemptCount",0);s(this,"connectStartTime",0);s(this,"_connectTime");s(this,"shouldContinueConnecting",!1);s(this,"_isConnectInProgress",!1);s(this,"readyState",()=>{if(this.websockets.length===0)return WebSocket.CLOSED;const e=this.websockets.map(t=>t.readyState);for(const t of e)if(t!==WebSocket.OPEN)return t;return WebSocket.OPEN});s(this,"url",()=>{var e;return(e=this.websockets[0])==null?void 0:e.url});s(this,"send",e=>{var t;this.websockets.length&&((t=this.websockets[0])==null||t.send(e))});s(this,"close",e=>{var g;let t=!1;return(g=this.websockets)==null||g.forEach(n=>{n.onmessage=G,n.removeEventListener("error",this.onError),n.removeEventListener("close",this.onClose),n.removeEventListener("open",this.onOpen),n.close(1e3,e),t=!0}),this.websockets=[],this.shouldContinueConnecting=!1,this._isConnectInProgress=!1,this.logger.info("Closed websocket",{reason:e}),t});s(this,"suspend",()=>{this.isSuspended=!0});s(this,"unsuspend",()=>{this.isSuspended=!1,this.readyState()!==WebSocket.OPEN&&!this.isConnectInProgress&&this.connect()});s(this,"onMessage",(e,t)=>{this.websockets.length!==0&&this.options.onMessage(e,t.data)});s(this,"onError",()=>{this.logger.info("On error",f({},this.options)),this.close("one websocket had an error"),this.emit("error",new x("WebSocket error",{code:"websocket_error",isFatal:!1}))});s(this,"onClose",e=>{switch(this.logger.info("Closed",V(f({},this.options),{reason:e.reason,code:e.code,isSuspended:this.isSuspended})),this.close("one websocket was closed"),e.code){case 4e3:this.emit("error",Tn(kg()));break;case 4001:this.emit("error",Tn(kg()));break;case 4002:this.emit("error",dh(kg()));break;case 4003:this.emit("error",lC("internal",kg()));break;case 4010:this.emit("error",lh("internal",kg()));break}this.emit("close",this)});s(this,"onOpen",()=>{this.logger.info("Opened",f({},this.options)),this.readyState()===WebSocket.OPEN&&(this._connectTime=Date.now()-this.connectStartTime,this.reconnectState.reconnectRetries=0,this._isConnectInProgress=!1,this.emit("open",this))});s(this,"connect",(e=!1)=>c(this,null,function*(){if(this.isConnectInProgress)return this.logger.info("Connect already in progress"),!1;if(this.isSuspended)return!1;if(this.readyState()!==WebSocket.CLOSED&&this.close("new connection in progress"),this.shouldContinueConnecting=!0,this._isConnectInProgress=!0,e&&this.options.reconnectDelay>0){this.logger.info("Waiting for reconnect delay",f({},this.options)),yield ut(this.options.reconnectDelay);const t=yield this.options.reconnectHandler(this.reconnectState);if(this.reconnectState.reconnectRetries++,!t)return this._isConnectInProgress=!1,this.emit("error",uC()),!1}this._connectionAttemptCount++;try{if(!this.shouldContinueConnecting)return this._isConnectInProgress=!1,this.logger.info("Connection aborted"),!1;const{url:t,connectionCount:g}=yield this.options.connectHandler();if(this.connectStartTime=Date.now(),!this.shouldContinueConnecting)return this._isConnectInProgress=!1,this.logger.info("Connection aborted"),!1;this.logger.info("Connecting websockets",V(f({},this.options),{url:t}));for(let n=0;n<g;n++){const o=new WebSocket(t);o.binaryType="arraybuffer",o.onmessage=a=>this.onMessage(n,a),o.addEventListener("error",this.onError),o.addEventListener("close",this.onClose),o.addEventListener("open",this.onOpen),this.websockets.push(o)}return!0}catch(t){return this._isConnectInProgress=!1,t instanceof x&&(this.logger.error("Failed to connect",t.toStringifiable()),t.isFatal())||this.shouldContinueConnecting&&(this.logger.info("Connection aborted",{error:t}),this.emit("error",new x("Failed to connect",{code:"failed_to_connect",isFatal:!1,source:t,type:"internal"}))),!1}}));this.options=e,this.logger=t}get isConnectInProgress(){return this._isConnectInProgress}get connectionCount(){return this.websockets.length}get connectionAttemptCount(){return this._connectionAttemptCount}get connectTime(){return this._connectTime}}const Im=65536*8,nm=.9,om=40,am=i=>{const A=i||om;return Im*nm*1e3/A},Xe=class Xe{constructor(A,e,t,g){s(this,"emitter");s(this,"transport");s(this,"logger");s(this,"config");s(this,"rtts");s(this,"lastPingSentTime",Date.now());s(this,"isPingInFlight",!1);s(this,"connectCount",0);s(this,"missedPings",0);s(this,"contextSwitchesInProgress",new Set);s(this,"contextSwitchesCompleted",new Set);s(this,"buffer",[]);s(this,"disconnected",new _);s(this,"unload",()=>{this.logger.debug("Unloading module..."),this.close("Unloading"),this.emitter.off("send signal",this.sendSignal),this.emitter.off("disconnect",this.close),this.emitter.off("reconnect",this.reconnect),this.logger.debug("Unloaded module")});s(this,"suspend",()=>{this.resetPingState(),this.transport.suspend()});s(this,"unsuspend",()=>{this.transport.unsuspend()});s(this,"getState",()=>{switch(this.transport.readyState()){case WebSocket.OPEN:return"connected";case WebSocket.CONNECTING:return"connecting";default:return"disconnected"}});s(this,"sendSignal",A=>{if(this.logger.debug("sending signal",{signal:A}),this.transport.readyState()!==WebSocket.OPEN){this.logger.debug("transport is closed");return}this.transport.send(JSON.stringify(A))});s(this,"getStatistics",()=>{var A;return{edgeUrl:(A=this.transport)==null?void 0:A.url(),connectionProtocol:"vindral_ws"}});s(this,"onMessage",(A,e)=>{var t;if(this.pingCooldownExpired()&&this.sendPing(),this.contextSwitchesCompleted.size===((t=this.transport)==null?void 0:t.connectionCount)){this.logger.info("Completing context switch"),this.contextSwitchesInProgress.clear(),this.contextSwitchesCompleted.clear();const g=this.buffer.filter(([o,a])=>!(a instanceof ArrayBuffer)),n=this.buffer.filter(([o,a])=>a instanceof ArrayBuffer);g.map(o=>this.handleMessage(o[0],o[1])),n.map(o=>this.handleMessage(o[0],o[1])),this.buffer=[]}if(this.contextSwitchesInProgress.has(A)){if(!(e instanceof ArrayBuffer)){const g=JSON.parse(e);if(sC(g)&&g.type==="context switch complete"){this.logger.info("context switch completed",{socketId:A}),this.emitter.emit("context switch complete"),this.contextSwitchesCompleted.add(A);return}}this.buffer.push([A,e]);return}this.handleMessage(A,e)});s(this,"resolveEdgeUrl",()=>c(this,null,function*(){const A=this.config.connectInfo,e=yield this.config.onConnectInfo(A),t=this.config.options.getOverride("separateVideoSocketEnabled",e.channelId),g=this.config.options.get("media")==="audio+video";let n=1;g&&(n=t!==!1?2:1);const o=sm(this.config.edgeUrl,{video:e.video,audio:e.audio,burstMs:e.burstMs,sessionId:e.sessionId,clientId:e.clientId,channelId:e.channelId,channelGroupId:e.channelGroupId,expectAdditionalConnection:n>1,authToken:this.config.options.get("authenticationToken")});return this.logger.debug("Resolved edge url",{edgeUrl:o}),{url:o,connectionCount:n}}));s(this,"handleMessage",(A,e)=>{if(e instanceof ArrayBuffer)this.emitter.emit("received data",e);else{const t=JSON.parse(e);if(!sC(t))return;switch(t.type){case"pong":this.lastPingSentTime&&(this.rtts.push(Date.now()-this.lastPingSentTime),this.isPingInFlight=!1,this.emitter.emit("rtt",we(this.rtts.items())));break;case"context switch":this.logger.info("Starting context switch",{socketId:A}),this.emitter.emit("context switch started"),this.contextSwitchesInProgress.add(A);break;default:this.emitter.emit("received signal",t);break}}});s(this,"connectWebSocketTransport",()=>{const A=new gm({reconnectDelay:1e3,onMessage:this.onMessage,reconnectHandler:this.config.reconnectHandler,connectHandler:this.resolveEdgeUrl},this.logger.createContext("Transport"));return A.on("open",this.onTransportChange),A.on("close",this.onTransportChange),A.on("error",e=>this.disconnected.reject(e)),A.connect(),A});s(this,"close",(A="Disconnect Requested")=>{var e;this.contextSwitchesCompleted.clear(),this.contextSwitchesInProgress.clear(),this.buffer=[],this.resetPingState(),this.disconnected.resolve(),(e=this.transport)==null||e.close(A)});s(this,"onTransportChange",()=>{var A;this.getState()==="connected"?((A=this.transport)!=null&&A.connectTime&&(this.rtts.push(this.transport.connectTime/Xe.TLS_ROUNDTRIPS/(this.transport.connectionCount||1)),this.emitter.emit("rtt",we(this.rtts.items()))),this.connectCount++,this.resetPingState()):(this.contextSwitchesCompleted.clear(),this.contextSwitchesInProgress.clear(),this.buffer=[],this.resetPingState(),this.disconnected.resolve()),this.emitter.emit("connection state",this.getState())});s(this,"reconnect",A=>{if(this.transport.isConnectInProgress){this.logger.debug("Stopping reconnect, already mid-connection");return}this.close(A)});s(this,"resetPingState",()=>{this.missedPings=0,this.isPingInFlight=!1});s(this,"pingCooldownExpired",()=>Date.now()-this.lastPingSentTime>Xe.PING_INTERVAL);s(this,"sendPing",()=>{if(this.isPingInFlight){this.missedPings++,this.missedPings>Xe.MAX_MISSED_PINGS&&this.reconnect("missed pings");return}this.isPingInFlight=!0,this.lastPingSentTime=Date.now(),this.missedPings=0,this.sendSignal({type:"ping"})});this.logger=e,this.emitter=A,this.config=t,this.rtts=g,this.emitter.on("send signal",this.sendSignal),this.emitter.on("disconnect",this.close),this.emitter.on("reconnect",this.reconnect),this.disconnected.promise.catch(G),this.transport=this.connectWebSocketTransport()}closed(){return this.disconnected.promise}};s(Xe,"PING_INTERVAL",5e3),s(Xe,"MAX_MISSED_PINGS",4),s(Xe,"TLS_ROUNDTRIPS",3),s(Xe,"start",(A,e,t,g)=>new Promise((n,o)=>{const a=new Xe(A,e,t,g);a.transport.once("error",B=>o(B)),a.transport.once("open",()=>n(a))}));let bB=Xe;class Bm{constructor(A){r(this,hg);r(this,Wt,[]);r(this,dg);E(this,hg,A)}select(A){if(I(this,hg).edgeUrl)return I(this,hg).edgeUrl;I(this,Wt).length===0&&E(this,Wt,I(this,Wt).concat(A));const e=I(this,Wt).shift();if(E(this,dg,e),e)return e}shiftedEdge(){return I(this,dg)}reset(){E(this,dg,void 0),E(this,Wt,[])}}hg=new WeakMap,Wt=new WeakMap,dg=new WeakMap;const wg=class wg{constructor(A,e,t){r(this,Qa);s(this,"emitter");s(this,"logger");s(this,"config");s(this,"apiClient");s(this,"connectionImpl");r(this,je,new P(10));r(this,be,!0);r(this,lg);r(this,Oi,0);r(this,Ot,0);r(this,Vi,0);r(this,ug);r(this,mg);s(this,"unload",()=>{var A;this.logger.debug("Unloading module..."),this.disconnect("Unloading"),(A=this.connectionImpl)==null||A.unload(),this.logger.debug("Unloaded module")});s(this,"suspend",()=>{var A;E(this,be,!1),(A=this.connectionImpl)==null||A.suspend()});s(this,"unsuspend",()=>{var A;E(this,be,!0),(A=this.connectionImpl)==null||A.unsuspend(),this.connect()});s(this,"getState",()=>this.connectionImpl?this.connectionImpl.getState():"disconnected");s(this,"getStatistics",()=>{const A=I(this,Ot)>0?I(this,Vi)/I(this,Ot):0;return this.connectionImpl?V(f({},this.connectionImpl.getStatistics()),{rtt:$t(I(this,je).items()),estimatedBandwidth:this.estimatedBandwidth,connectCount:I(this,Vi),connectionAttemptCount:I(this,Ot),connectionSuccessRatio:A}):{rtt:{min:0,max:0,average:0,last:0},estimatedBandwidth:0,connectCount:I(this,Vi),connectionAttemptCount:I(this,Ot),connectionSuccessRatio:A,connectionProtocol:void 0}});s(this,"connect",()=>{E(this,be,!0),!I(this,lg)&&E(this,lg,l(this,Qa,Bc).call(this))});s(this,"disconnect",(A="Disconnect Requested")=>{var e;E(this,be,!1),(e=this.connectionImpl)==null||e.close(A)});s(this,"reconnect",A=>{this.disconnect(A),this.connect()});r(this,ra,()=>c(this,null,function*(){try{return yield this.apiClient.connect(this.config.options.getOptions())}catch(A){if(Ml(A))switch(A.status){case 401:throw this.emitter.emit("error",Tn(A)),Tn(A);case 403:throw this.emitter.emit("error",mC(A.message)),mC(A.message)}throw this.emitter.emit("error",mh(A instanceof Error?A:void 0)),A}}));r(this,Ca,()=>c(this,null,function*(){const A=Date.now(),e=()=>Date.now()-A;return Promise.race([ut(wg.PING_TIMEOUT),fetch(new URL("/api/v4/connect/ping",this.config.options.get("url")).toString(),{method:"HEAD"})]).then(e,e)}));this.logger=e,this.emitter=A,this.config=t,this.apiClient=new $C({publicEndpoint:this.config.options.get("url").toString(),tokenFactory:()=>this.config.options.get("authenticationToken")})}get rtt(){return I(this,je).items().length>0?we(I(this,je).items()):0}get estimatedBandwidth(){return this.connectionImpl&&"estimatedBandwidth"in this.connectionImpl&&this.connectionImpl.estimatedBandwidth?this.connectionImpl.estimatedBandwidth:am(this.rtt)}get firstConnectionTime(){return I(this,ug)}get lastConnectionTime(){return I(this,mg)}};je=new WeakMap,be=new WeakMap,lg=new WeakMap,Oi=new WeakMap,Ot=new WeakMap,Vi=new WeakMap,ug=new WeakMap,mg=new WeakMap,ra=new WeakMap,Ca=new WeakMap,Qa=new WeakSet,Bc=function(){return c(this,null,function*(){var e;const A=new Bm({edgeUrl:this.config.options.get("edgeUrl")});for(E(this,Oi,0);;){te(this,Oi)._++,te(this,Ot)._++;let t=!1;try{const[n,o]=yield Promise.all([I(this,ra).call(this),I(this,Ca).call(this)]),a=o/2;if(I(this,je).clear(),I(this,je).push(a),!I(this,be))break;const B=A.select(n.edges);if(!B)throw new x("Failed to resolve edge url",{isFatal:!0,code:"failed_to_resolve_edge_url"});tC(n)?this.connectionImpl=yield GB.start(this.emitter,this.logger,this.apiClient,V(f({},this.config),{connectInfo:n,edgeUrl:B}),I(this,je)):(lA(typeof B=="string","Edge URL is expected to be a string"),this.connectionImpl=yield bB.start(this.emitter,this.logger,V(f({},this.config),{connectInfo:n,edgeUrl:B}),I(this,je))),A.reset(),te(this,Vi)._++,E(this,Oi,0),E(this,mg,Date.now()),I(this,ug)||E(this,ug,I(this,mg)),yield this.connectionImpl.closed()}catch(n){this.logger.info("Failed to connect",n);const o=A.shiftedEdge();o&&this.emitter.emit("telemetry event",{code:"shifted_edge",edgeUrl:typeof o=="string"?o:o.moqUrl||o.moqWsUrl}),n instanceof x?(this.emitter.emit("error",n),t=n.isFatal()):n instanceof Error&&this.emitter.emit("error",new x(n.message,{code:"start_failed",isFatal:!1}))}if((e=this.connectionImpl)==null||e.unload(),this.connectionImpl=void 0,t){E(this,be,!1);break}if(!I(this,be))break;if(!(yield this.config.reconnectHandler({reconnectRetries:I(this,Oi)}))){this.emitter.emit("error",uC());break}if(yield ut(1e3),!I(this,be))break}E(this,lg,void 0)})},s(wg,"PING_TIMEOUT",1e3),s(wg,"create",(A,e,t)=>new wg(A,e,t));let NB=wg;const LB=()=>({video:V(f({},qn()),{bitRate:wt()}),audio:{bitRate:wt()}}),rm=()=>({width:window.innerWidth,height:window.innerHeight,bitRate:wt()}),fg=class fg{constructor(A,e,t,g){s(this,"emitter");s(this,"timers",new JA);s(this,"pictureInPictureSource");s(this,"element");s(this,"currentCap");s(this,"userSpecifiedCap");s(this,"renditionLevelSource");s(this,"resizeObserver");s(this,"elementSize");s(this,"_sizeBasedResolutionCapEnabled");s(this,"unload",()=>{var A;this.emitter.off("enter picture in picture",this.enterPictureInPicture),this.emitter.off("exit picture in picture",this.exitPictureInPicture),(A=this.resizeObserver)==null||A.disconnect(),this.suspend()});s(this,"load",()=>{window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(this.onResize),this.resizeObserver.observe(this.element)),this.evaluateConstraintCap()});s(this,"setElement",A=>{var t;if(A===this.element)return;(t=this.resizeObserver)==null||t.disconnect(),this.element=A;const e=this.element.getBoundingClientRect();this.elementSize={width:e.width,height:e.height},this.resizeObserver&&this.resizeObserver.observe(this.element),this.evaluateConstraintCap()});s(this,"unsuspend",()=>{this.timers.setInterval(this.evaluateConstraintCap,fg.CHECK_SIZE_INTERVAL),this.evaluateConstraintCap()});s(this,"suspend",()=>{this.timers.unload()});s(this,"setUserSpecifiedCap",A=>{var t;const e=(t=this.getUserSpecifiedCap())!=null?t:LB();this.userSpecifiedCap=V(f({},e),{video:f(f({},e.video),A.video),audio:f(f({},e.audio),A.audio)}),this.evaluateConstraintCap()});s(this,"getUserSpecifiedCap",()=>this.userSpecifiedCap);s(this,"getCurrentConstraintCap",()=>this.currentCap);s(this,"getStatistics",()=>({constraintCap:this.getUserSpecifiedCap(),windowInnerWidth:window.innerWidth,windowInnerHeight:window.innerHeight,elementWidth:this.elementSize.width,elementHeight:this.elementSize.height,pixelRatio:window.devicePixelRatio}));s(this,"constrainSubscription",A=>{const e=this.getCurrentConstraintCap();return e&&(A.video.codec&&(A.video.bitRate=Math.min(e.video.bitRate,A.video.bitRate),A.video.width=Math.min(e.video.width,A.video.width),A.video.height=Math.min(e.video.height,A.video.height)),A.audio.codec&&(A.audio.bitRate=Math.min(e.audio.bitRate,A.audio.bitRate))),A});s(this,"onResize",A=>{A.forEach(e=>{this.elementSize={width:e.contentRect.width,height:e.contentRect.height}})});s(this,"evaluateConstraintCap",()=>{var o,a,B,C,Q;const A=this.sizeBasedResolutionCapEnabled?V(f({},LB()),{video:rm()}):LB();if(!this.resizeObserver){const h=this.element.getBoundingClientRect();this.elementSize={width:h.width,height:h.height}}if(this.sizeBasedResolutionCapEnabled){const h=window.devicePixelRatio,d=(o=this.pictureInPictureSource)==null?void 0:o.getPictureInPictureSize();this.elementSize.width>0&&this.elementSize.height>0&&(A.video.width=this.elementSize.width,A.video.height=this.elementSize.height),d&&(A.video.width=d.width,A.video.height=d.height),A.video.width*=h,A.video.height*=h}const t=this.renditionLevelSource.getRenditionLevels().find(h=>{if(h.video){const d=h.video.width/h.video.height,u=A.video.width/A.video.height;return d>u?h.video.width>A.video.width:h.video.height>A.video.height}});t&&t.video&&(A.video.width=t.video.width,A.video.height=t.video.height);const g=(a=this.userSpecifiedCap)==null?void 0:a.video,n=(B=this.userSpecifiedCap)==null?void 0:B.audio;g&&(A.video.width>g.width&&(A.video.width=g.width),A.video.height>g.height&&(A.video.height=g.height)),A.video.bitRate=(C=g==null?void 0:g.bitRate)!=null?C:A.video.bitRate,A.audio.bitRate=(Q=n==null?void 0:n.bitRate)!=null?Q:A.audio.bitRate,gs(A,this.currentCap)?this.currentCap=f({},A):(this.currentCap=f({},A),this.emitter.emit("constraint cap changed",A))});s(this,"enterPictureInPicture",A=>{this.pictureInPictureSource=A,this.evaluateConstraintCap()});s(this,"exitPictureInPicture",()=>{this.pictureInPictureSource=void 0,this.evaluateConstraintCap()});this.element=e;const n=this.element.getBoundingClientRect();this.elementSize={width:n.width,height:n.height},this.emitter=A,this.renditionLevelSource=t,this._sizeBasedResolutionCapEnabled=g,this.emitter.on("enter picture in picture",this.enterPictureInPicture),this.emitter.on("exit picture in picture",this.exitPictureInPicture)}get sizeBasedResolutionCapEnabled(){return this._sizeBasedResolutionCapEnabled}set sizeBasedResolutionCapEnabled(A){this._sizeBasedResolutionCapEnabled=A,this.evaluateConstraintCap()}};s(fg,"CHECK_SIZE_INTERVAL",1e3),s(fg,"create",(A,e,t,g)=>new fg(A,e,t,g));let JB=fg;const Cm=5,Qm=100,pQ=1e3;class MB{constructor(A,e,t,g,n=!1,o=!1,a=!1){s(this,"timers",JA.create());s(this,"logger");s(this,"emitter");s(this,"trackContexts");s(this,"playbackSource");s(this,"isSuspended",!1);s(this,"_webCodecsInUse");s(this,"_audioWebCodecsInUse");s(this,"_offscreenCanvasInUse");s(this,"decodedVideoSamplesInCurrentInterval",0);s(this,"currentVideoDecodeRate",Number.MAX_SAFE_INTEGER);s(this,"isAudioEmitRetryScheduled",!1);s(this,"videoKeyframeTimestamps",[]);s(this,"load",()=>{const A=this._audioWebCodecsInUse?20:Qm;this.timers.setInterval(this.emitDecodedFrames,A),this.timers.setInterval(this.emitDecodeRate,pQ),this.emitter.on("init segment",this.onInitSegment),this.emitter.on("coded sample",this.decode)});s(this,"unload",()=>{this.trackContexts.forEach(({decoderContext:A})=>A.unload()),this.timers.unload(),this.isAudioEmitRetryScheduled=!1,this.videoKeyframeTimestamps=[],this.emitter.off("init segment",this.onInitSegment),this.emitter.off("coded sample",this.decode)});s(this,"suspend",()=>{this.isSuspended=!0});s(this,"unsuspend",()=>{this.isSuspended=!1});s(this,"getBuffer",A=>{var e;return(e=this.trackContexts.get(A))==null?void 0:e.buffer});s(this,"getVideoKeyframeTimestamps",()=>this.videoKeyframeTimestamps);s(this,"videoDecodeRate",()=>this.currentVideoDecodeRate);s(this,"calculateVideoDecodeRate",()=>{var o;if(this._webCodecsInUse)return 2;const A=this.trackContexts.get("video");if(!A)return Number.MAX_SAFE_INTEGER;const e=(o=A.sampleDuration)!=null?o:40;if(!Number.isFinite(e)||e<=0)return 0;const t=1e3/e,n=this.decodedVideoSamplesInCurrentInterval*1e3/pQ/t;return!Number.isFinite(n)||n<0?0:n});s(this,"getStatistics",()=>{var o,a,B,C,Q;const A=this.trackContexts.get("video"),e=$t((o=A==null?void 0:A.decodeTime.items())!=null?o:[]),t=$t((a=A==null?void 0:A.transportTime.items())!=null?a:[]),g=$t((C=(B=this.trackContexts.get("audio"))==null?void 0:B.decodeTime.items())!=null?C:[]),n=this._offscreenCanvasInUse?(Q=A==null?void 0:A.getRenderStatistics)==null?void 0:Q.call(A):void 0;return V(f({videoDecodeRate:this.videoDecodeRate(),videoDecodeTime:e,audioDecodeTime:g,videoTransportTime:t,videoKeyframeIntervalMs:Wr(this.videoKeyframeTimestamps)},n?{renderedFrameCount:n.renderedFrameCount,rendererDroppedFrameCount:n.rendererDroppedFrameCount}:{}),{videoRenderer:this._offscreenCanvasInUse?"OffscreenCanvas":"Canvas",videoDecoder:this._webCodecsInUse?"WebCodecs":"WASM",audioRenderer:"AudioContext",audioDecoder:this._audioWebCodecsInUse?"WebCodecs":"WASM"})});s(this,"setSubtitleCues",(A,e,t,g,n)=>{var a;if(!this._offscreenCanvasInUse)return;const o=(a=this.trackContexts.get("video"))==null?void 0:a.decoderContext;o&&"setSubtitleCues"in o&&o.setSubtitleCues(A,e,t,g,n)});s(this,"onInitSegment",({initSegment:A})=>{var t;const e=(t=this.trackContexts.get(A.type))==null?void 0:t.decoderContext;if(!e)throw new x("No known decoder context",{code:"no_known_decoder_context",isFatal:!1});e.initSegment(A)});s(this,"decode",A=>{const e=this.trackContexts.get(A.type);if(!e)throw new x("No known decoder context",{code:"no_known_decoder_context",isFatal:!1});if(this.isSuspended)return;e.sampleDuration=A.duration/A.timescale*1e3;const t=A.compositionTimeOffset||0,{decoderContext:g,buffer:n}=e,o=(A.timestamp+t)/A.timescale*1e3,a=A.duration/A.timescale*1e3,B=n[n.length-1];if(!B||o-Cm>B.end?n.push({start:o,end:o+a}):o+a*5<B.end?(e.buffer=[{start:o,end:o+a}],A.type==="video"&&(this.videoKeyframeTimestamps=[])):B.end=o+a,A.type==="video"&&A.isSync){const C=this.videoKeyframeTimestamps[this.videoKeyframeTimestamps.length-1];C!==void 0&&o<C&&(this.videoKeyframeTimestamps=[]),this.videoKeyframeTimestamps.push(o),this.videoKeyframeTimestamps.length>20&&(this.videoKeyframeTimestamps=this.videoKeyframeTimestamps.slice(-20))}g.enqueue(A),this.emitDecodedFrames(),this._audioWebCodecsInUse&&A.type==="audio"&&this.scheduleAudioEmitRetry()});s(this,"scheduleAudioEmitRetry",()=>{this.isAudioEmitRetryScheduled||(this.isAudioEmitRetryScheduled=!0,this.timers.setTimeout(()=>{this.isAudioEmitRetryScheduled=!1,this.emitDecodedFrames()},0))});s(this,"emitDecodedFrames",()=>{let A;this.updateBufferState(),this.trackContexts.forEach((e,t)=>{var o,a,B,C,Q,h;let g;for(;(g=(a=(o=e.decoderContext).error)==null?void 0:a.call(o))!==void 0;)this.emitter.emit("error",Xa(!1,g));for(;(A=e.decoderContext.take())!==void 0;){const{statistics:d}=A;d&&(e.decodeTime.push(d.decodeTime),e.transportTime.push((d.transportTimeToWorker+d.transportTimeFromWorker)/d.samplesInBatch)),t==="video"&&this.decodedVideoSamplesInCurrentInterval++,this.emitter.emit("decoded frame",A)}let n=(C=(B=e.decoderContext).takeEstimatedStatistics)==null?void 0:C.call(B);for(;n!==void 0;)e.decodeTime.push(n.decodeTime),e.transportTime.push(n.transportTime),t==="video"&&this.decodedVideoSamplesInCurrentInterval++,n=(h=(Q=e.decoderContext).takeEstimatedStatistics)==null?void 0:h.call(Q)})});s(this,"emitDecodeRate",()=>{this.currentVideoDecodeRate=this.calculateVideoDecodeRate(),this.decodedVideoSamplesInCurrentInterval=0,this.emitter.emit("video decode rate",this.currentVideoDecodeRate)});s(this,"updateBufferState",()=>{let A;if(this.trackContexts.forEach(n=>{var o,a,B,C;if(!A)A=n.buffer;else{const Q=(a=(o=n.buffer[n.buffer.length-1])==null?void 0:o.end)!=null?a:0;((C=(B=A[A.length-1])==null?void 0:B.end)!=null?C:0)>Q&&(A=n.buffer)}}),!A)return;const e=this.playbackSource.currentTime;let t=!0;this.trackContexts.forEach(n=>{n.buffer.some(a=>a.start<=e&&e<a.end)||(t=!1)});const g=t?"playing":"buffering";this.emitter.emit("buffer state",{buffered:A,currentTime:this.playbackSource.currentTime,isPaused:this.playbackSource.isPaused,playbackState:g})});this.logger=e,this.emitter=A,this.trackContexts=t,this.playbackSource=g,this._webCodecsInUse=n,this._audioWebCodecsInUse=o,this._offscreenCanvasInUse=a}static create(A,e,t,g,n,o,a=!1,B="no-preference",C){return c(this,null,function*(){const Q=new Map,h=new Set;let d=!1,u=!1,m=!1;for(const p of g){if(h.has(p.type)){e.warn("Received duplicate track type for decoder initialization. Ignoring subsequent track.",{trackType:p.type,codec:p.codec,mimeType:p.mimeType});continue}switch(h.add(p.type),p.type){case"audio":{let y,k,N=!1;if(a){const{WebCodecsAudioDecoderContext:U}=yield Promise.resolve().then(()=>vw);if(N=U.isSupported(),N)try{y=yield U.create(e.createContext("WebCodecsAudio")),u=!0}catch(K){k=K instanceof Error?K:new Error("Failed to initialize WebCodecs audio decoder"),p.codec==="opus"&&e.warn("Failed to initialize WebCodecs audio decoder, falling back to WASM Opus decoder",{codec:p.codec,error:k})}}if(!y)if(p.codec==="opus"){const{OpusDecoderContext:U}=yield Promise.resolve().then(()=>qw);y=yield U.create(48e3,2)}else{const U=a?k?`WebCodecs audio decoder initialization failed: ${k.message}`:N?"WebCodecs audio decoder could not be initialized.":"WebCodecs AudioDecoder API is not supported in this environment.":"WebCodecs audio decoding is disabled.";throw Qh(p.codec,U,k)}Q.set(p.type,{buffer:[],decoderContext:y,decodeTime:new P(100),transportTime:new P(100),sampleDuration:40});break}case"video":{const{VideoDecoderWorkerContext:y}=yield Promise.resolve().then(()=>Tw),k=yield y.create(e.createContext("VideoDecoderWorker"),t,o,a,B,C,()=>n.currentTime);d=k.isWebCodecs,m=k.usingOffscreenCanvas,Q.set(p.type,{buffer:[],decoderContext:k,decodeTime:new P(100),transportTime:new P(100),sampleDuration:40,getRenderStatistics:k.getRenderStatistics});break}}}return new MB(A,e,Q,n,d,u,m)})}}const Ea=class Ea{constructor(A){s(this,"emitter");s(this,"isVisibleCount",0);s(this,"isHiddenCount",0);s(this,"isOnlineCount",0);s(this,"isOfflineCount",0);s(this,"isActive",document.visibilityState==="visible");s(this,"unload",()=>{document.removeEventListener("visibilitychange",this.onVisibilityChanged),window.removeEventListener("pagehide",this.onPageHide),window.removeEventListener("online",this.onOnline),window.removeEventListener("offline",this.onOffline)});s(this,"load",()=>{document.addEventListener("visibilitychange",this.onVisibilityChanged),window.addEventListener("pagehide",this.onPageHide),window.addEventListener("online",this.onOnline),window.addEventListener("offline",this.onOffline)});s(this,"unsuspend",()=>{});s(this,"getStatistics",()=>{var A,e,t,g,n;return{isVisible:this.isVisible,isOnline:this.isOnline,isVisibleCount:this.isVisibleCount,isHiddenCount:this.isHiddenCount,isOnlineCount:this.isOnlineCount,isOfflineCount:this.isOfflineCount,navigatorRtt:(A=navigator.connection)==null?void 0:A.rtt,navigatorEffectiveType:(e=navigator.connection)==null?void 0:e.effectiveType,navigatorConnectionType:(t=navigator.connection)==null?void 0:t.type,navigatorSaveData:(g=navigator.connection)==null?void 0:g.saveData,navigatorDownlink:(n=navigator.connection)==null?void 0:n.downlink}});s(this,"onOnline",()=>this.isOnlineCount++);s(this,"onOffline",()=>this.isOfflineCount++);s(this,"onPageHide",A=>this.emitter.emit("pagehide",A));s(this,"onVisibilityChanged",()=>{this.setIsActive(document.visibilityState==="visible")});s(this,"setIsActive",A=>{A!==this.isActive&&(this.emitter.emit("page active",A),A?this.isVisibleCount++:this.isHiddenCount++),this.isActive=A});this.emitter=A}get isOnline(){return navigator.onLine}get isVisible(){return document.visibilityState==="visible"}};s(Ea,"create",A=>new Ea(A));let vB=Ea;const Em=i=>(A,e,t)=>A.timestamp<=e||A.timestampAdded<=t-i,Vt=class Vt{constructor(A,e,t){s(this,"logger");s(this,"emitter");s(this,"waitingEvents",[]);s(this,"isTriggered",Em(Vt.EVENT_TIMEOUT));s(this,"timeSource");s(this,"timers",new JA);s(this,"load",()=>{this.timers.setInterval(this.onBufferedStateChanged,Vt.EVENT_CHECK_INTERVAL),this.emitter.on("add event",this.addEvent)});s(this,"unload",()=>{this.timers.unload(),this.emitter.off("add event",this.addEvent)});s(this,"addEvent",A=>{this.logger.debug("Adding event",{event:A}),!this.waitingEvents.some(e=>typeof e.id!="undefined"&&e.id===A.id)&&this.waitingEvents.push(V(f({},A),{timestampAdded:Date.now()}))});s(this,"extractEvent",(A,e)=>{e.type==="video"&&A.channelId!==e.channelId&&this.addEvent({type:"channel switch",channelId:e.channelId,timestamp:e.timestamp/e.timescale*1e3}),e.type==="audio"&&A.type==="audio"&&e.language!==void 0&&e.language!==A.language&&this.addEvent({type:"language switch",language:e.language,timestamp:e.timestamp/e.timescale*1e3})});s(this,"onBufferedStateChanged",()=>{var n;const A=Date.now(),e=(n=this.timeSource.drift)!=null?n:0,t=this.timeSource.serverCurrentTime-e;if(this.waitingEvents.length===0)return;const g=this.waitingEvents.filter(o=>this.isTriggered(o,t,A));this.waitingEvents=this.waitingEvents.filter(o=>!this.isTriggered(o,t,A)),g.forEach(o=>{this.logger.debug("Emitting event",{event:o}),this.emitter.emit("event",o)})});this.logger=e,this.emitter=A,this.timeSource=t}};s(Vt,"EVENT_TIMEOUT",5e3),s(Vt,"EVENT_CHECK_INTERVAL",20),s(Vt,"create",(A,e,t)=>new Vt(A,e,t));let HB=Vt;const Ne=class Ne{constructor(A){s(this,"emitter");s(this,"timers",JA.create());s(this,"bytesReceived",new Map);s(this,"timeoutInterval");s(this,"lastBytesUpdated",Date.now());s(this,"load",()=>{this.emitter.on("connection state",this.onConnectionState),this.timers.setInterval(()=>this.bytesReceived.forEach(A=>A.tick()),100)});s(this,"unload",()=>{this.emitter.off("connection state",this.onConnectionState),this.timers.unload()});s(this,"averageBitRate",A=>{var e,t;return((t=(e=this.bytesReceived.get(A))==null?void 0:e.average)!=null?t:0)*8});s(this,"totalBytesReceived",()=>{let A=0;return this.bytesReceived.forEach(e=>{A+=e.total}),A});s(this,"add",(A,e)=>{let t=this.bytesReceived.get(A);t||(t=new Tc(20),this.bytesReceived.set(A,t)),e>0&&(this.lastBytesUpdated=Date.now(),this.timeoutInterval||(this.timeoutInterval=this.timers.setInterval(this.checkTimeout,Ne.UPDATE_RECEIVED_BYTES_INTERVAL))),t.add(e)});s(this,"getStatistics",()=>({bytesReceived:this.totalBytesReceived(),videoBitRate:this.averageBitRate("video"),audioBitRate:this.averageBitRate("audio")}));s(this,"onConnectionState",A=>{this.clearTimeoutInterval(),A==="connected"&&(this.lastBytesUpdated=Date.now(),this.timeoutInterval=this.timers.setInterval(this.checkTimeout,Ne.UPDATE_RECEIVED_BYTES_INTERVAL))});s(this,"checkTimeout",()=>{const A=Date.now()-this.lastBytesUpdated;if(this.totalBytesReceived()===0&&A>Ne.NO_DATA_ERROR_TIMEOUT){this.emitter.emit("error",uh()),this.emitter.emit("reconnect","no incoming data"),this.clearTimeoutInterval();return}A>Ne.NO_DATA_TIMEOUT&&this.totalBytesReceived()>0&&(this.emitter.emit("no data timeout",this.totalBytesReceived()),this.clearTimeoutInterval())});s(this,"clearTimeoutInterval",()=>{this.timeoutInterval&&(this.timers.clearInterval(this.timeoutInterval),this.timeoutInterval=void 0)});this.emitter=A}};s(Ne,"NO_DATA_ERROR_TIMEOUT",20*1e3),s(Ne,"NO_DATA_TIMEOUT",5*1e3),s(Ne,"UPDATE_RECEIVED_BYTES_INTERVAL",1e3),s(Ne,"create",A=>new Ne(A));let qB=Ne;const yQ=1e3,FQ=50;class KB{constructor(A){s(this,"logger");s(this,"trackingState",new Map);s(this,"runningJitter",new Map);s(this,"recentJitterSamples",new Map);s(this,"load",()=>{this.logger.debug("JitterModule loaded")});s(this,"unload",()=>{this.trackingState.clear(),this.runningJitter.clear(),this.recentJitterSamples.clear(),this.logger.debug("JitterModule unloaded")});this.logger=A}static create(A){return new KB(A)}getTrackingKey(A,e){return`${A}-${e}`}recordSample(A){var d,u,m,p;const e=this.getTrackingKey(A.type,A.renditionId),t=(m=(u=(d=globalThis.performance)==null?void 0:d.now)==null?void 0:u.call(d))!=null?m:Date.now(),g=A.timestamp/A.timescale*1e3,n=this.trackingState.get(e);if(!n){this.trackingState.set(e,{lastArrivalTime:t,lastTimestampMs:g,jitterSamples:new P(yQ),interArrivalTimes:new P(yQ)}),this.runningJitter.set(e,0),this.recentJitterSamples.set(e,new P(FQ));return}const o=g-n.lastTimestampMs;if(o<=0){n.lastArrivalTime=t,n.lastTimestampMs=g;return}const a=t-n.lastArrivalTime,B=Math.abs(a-o);n.jitterSamples.push(B),n.interArrivalTimes.push(a);const C=(p=this.runningJitter.get(e))!=null?p:0,Q=C+(B-C)/16;this.runningJitter.set(e,Q);let h=this.recentJitterSamples.get(e);h||(h=new P(FQ),this.recentJitterSamples.set(e,h)),h.push(B),n.lastArrivalTime=t,n.lastTimestampMs=g}getJitterForType(A){var e,t,g;for(const[n,o]of this.trackingState)if(n.startsWith(A)){if(o.jitterSamples.items().length<1)return;const B=(e=this.runningJitter.get(n))!=null?e:0,C=(g=(t=this.recentJitterSamples.get(n))==null?void 0:t.items())!=null?g:[],{min:Q,max:h,average:d}=$t(C);return{min:Math.round(Q),max:Math.round(h),last:Math.round(d),average:Math.round(B)}}}getRunningJitter(A){for(const[e,t]of this.runningJitter)if(e.startsWith(A))return t}reset(A,e){if(A!==void 0&&e!==void 0){const t=this.getTrackingKey(A,e);this.trackingState.delete(t),this.runningJitter.delete(t),this.recentJitterSamples.delete(t)}else if(A!==void 0)for(const t of this.trackingState.keys())t.startsWith(A)&&(this.trackingState.delete(t),this.runningJitter.delete(t),this.recentJitterSamples.delete(t));else this.trackingState.clear(),this.runningJitter.clear(),this.recentJitterSamples.clear()}getStatistics(){return{audioJitter:this.getJitterForType("audio"),videoJitter:this.getJitterForType("video")}}}const cm=()=>window.AudioContext||window.webkitAudioContext,ca=class ca extends ie{constructor(){super();s(this,"context",new(cm()));s(this,"timers",JA.create());s(this,"previousCurrentTime",0);s(this,"_isStuck",!1);s(this,"mediaStreamDestination");s(this,"unload",()=>(this.timers.unload(),this.context.removeEventListener("statechange",this.onStateChange),this.context.state!=="closed"?this.context.close():Promise.resolve()));s(this,"createGain",()=>this.context.createGain());s(this,"createBuffer",(e,t,g)=>this.context.createBuffer(e,t,g));s(this,"createBufferSource",()=>this.context.createBufferSource());s(this,"getMediaStreamDestination",()=>(this.mediaStreamDestination||(this.mediaStreamDestination=this.context.createMediaStreamDestination()),this.mediaStreamDestination));s(this,"getDefaultDestination",()=>this.context.destination);s(this,"createSplitter",()=>this.context.createChannelSplitter(2));s(this,"resume",()=>c(this,null,function*(){try{return yield Promise.race([this.context.resume(),xa(1e3,hh())])}catch(e){throw this.suspend().catch(G),e}}));s(this,"suspend",()=>c(this,null,function*(){var e;yield(e=this.context.suspend())!=null?e:Promise.resolve()}));s(this,"onStateChange",()=>this.emit("state",this.state));this.context.addEventListener("statechange",this.onStateChange),this.timers.setInterval(()=>{this._isStuck=this.isRunning&&this.context.currentTime===this.previousCurrentTime,this._isStuck&&this.emit("stuck"),this.previousCurrentTime=this.context.currentTime},ca.CHECK_INTERVAL)}get isStuck(){return this._isStuck}get isRunning(){return this.state==="running"}get currentTime(){return this.context.currentTime}get sampleRate(){return this.context.sampleRate}get state(){return this.context.state}};s(ca,"CHECK_INTERVAL",1e3);let TB=ca;const hm=400,ha=class ha extends ie{constructor(e,t,{muted:g,reInitWhenStuck:n,bufferTime:o}){super();s(this,"logger");s(this,"audio");s(this,"gainNode");s(this,"splitter");s(this,"_volume",1);s(this,"_userProvidedMuted",!1);s(this,"_muted",!1);s(this,"startTime",0);s(this,"samples",new Float32Array(0));s(this,"preInitSampleQueue",new P(500));s(this,"unplayedBufferSources",new P(100));s(this,"sampleRate",48e3);s(this,"channels",2);s(this,"index",0);s(this,"clockSource");s(this,"clockDelta");s(this,"startTimeIsInvalidated",!0);s(this,"lastSampleTimestamp",0);s(this,"reInitWhenStuck");s(this,"ignoreSuspendCalls",!1);s(this,"audioBufferMultiplier");s(this,"isActivated",!1);s(this,"unload",()=>c(this,null,function*(){var e,t;(e=this.gainNode)==null||e.disconnect(),yield(t=this.audio)==null?void 0:t.unload(),this.reset(),this.audio=void 0,this.gainNode=void 0}));s(this,"suspend",()=>{this.setGain(0)});s(this,"unsuspend",()=>{var e;this.setGain(this._volume),this.ignoreSuspendCalls=!!this.audio,(e=this.audio)==null||e.suspend().then(()=>c(this,null,function*(){yield this.resume(),this.ignoreSuspendCalls=!1})).catch(()=>{this.ignoreSuspendCalls=!1,this.emit("state change","suspended")})});s(this,"flush",(e=this.samples.length)=>{if(!this.audio||!this.gainNode)throw new x("AudioContext must be initialized to flush",{isFatal:!1,code:"audiocontext_must_be_initialized"});const t=Math.floor(e/this.channels);if(t<=0)return;const g=this.audio.createBufferSource(),n=this.audio.createBuffer(this.channels,t,this.sampleRate);let o=0;for(let B=0;B<this.channels;B++){o=B;const C=n.getChannelData(B);for(let Q=0;Q<t;Q++)C[Q]=this.samples[o],o+=this.channels}const a=Math.max(this.startTime,0);g.buffer=n,g.connect(this.gainNode),this.splitter&&g.connect(this.splitter),g.start(a),this.unplayedBufferSources.push([a,g]),this.startTime+=n.duration});s(this,"onDecodedFrame",e=>{if(!(this.gainNode&&this.audio&&this.audio.isRunning)){if(e.type==="audio"){this.preInitSampleQueue.push(V(f({},e),{data:e.data.slice(0,e.data.length)}));const t=this.clockSource.currentTime;this.preInitSampleQueue.filterPop(({timestamp:g,timescale:n})=>g/n*1e3>t)}return}for(;!this.preInitSampleQueue.isEmpty();){const t=this.preInitSampleQueue.items();this.preInitSampleQueue.clear(),t.forEach(this.onDecodedFrame)}if(this.unplayedBufferSources.filterPop(([t,g])=>{var n,o;return((o=(n=this.audio)==null?void 0:n.currentTime)!=null?o:0)<t}),e.type==="audio"){const t=e.timestamp/e.timescale*1e3;if(t<this.lastSampleTimestamp&&(this.logger.info("Unordered timestamp - invalidating start time"),this.startTimeIsInvalidated=!0),this.lastSampleTimestamp=t,this.startTimeIsInvalidated){const n=this.audio.currentTime*1e3,o=this.clockSource.currentTime,a=(n+t-o)/1e3;this.clockDelta=o-n,this.startTime=a,this.startTimeIsInvalidated=!1,this.unplayedBufferSources.items().forEach(([B,C])=>{a<=B&&C.stop()})}const g=e.data.length*this.audioBufferMultiplier;this.samples.length!==g&&(this.index>0&&this.flush(this.index),this.samples=new Float32Array(g),this.index=0),this.channels=e.channels,this.sampleRate=e.sampleRate,this.samples.set(e.data,this.index),this.index+=e.data.length,this.samples.length<=this.index&&(this.flush(this.samples.length),this.index=0)}});s(this,"play",()=>c(this,null,function*(){this.audio=this.getAudioContext(),yield this.resume()}));s(this,"pause",()=>{});s(this,"flushBuffer",()=>{var e,t;this.unplayedBufferSources.items().forEach(([g,n])=>{try{n.stop()}catch(o){}}),this.unplayedBufferSources.clear(),this.preInitSampleQueue.clear(),this.samples=new Float32Array(0),this.index=0,this.lastSampleTimestamp=0,this.startTime=(t=(e=this.audio)==null?void 0:e.currentTime)!=null?t:0,this.startTimeIsInvalidated=!0});s(this,"resume",()=>c(this,null,function*(){var e;if(!this._userProvidedMuted)try{yield(e=this.audio)==null?void 0:e.resume(),this._muted=this._userProvidedMuted,this.startTimeIsInvalidated=!0}catch(t){throw this._muted=!0,t}}));s(this,"getAudioContext",()=>this.audio?this.audio:this.setupContext());s(this,"setupContext",()=>{var e,t,g;return(e=this.audio)==null||e.unload(),this.audio=new TB,this.audio.on("state",n=>{this.logger.info("AudioContext state change",{state:n}),n==="running"&&(this._muted=this._userProvidedMuted,this.setGain(this._volume)),!this.ignoreSuspendCalls&&this.emit("state change",n)}),this.audio.on("stuck",()=>{this.reInitWhenStuck&&(this.logger.info("Re-init audio context"),this.setupContext(),this.resume().catch(G),this.emit("stuck"))}),(t=this.gainNode)==null||t.disconnect(),this.gainNode=this.audio.createGain(),this.setGain(this._volume),this.startTime=this.audio.currentTime,(g=this.splitter)==null||g.disconnect(),this.splitter=this.audio.createSplitter(),this.audio});s(this,"setGain",e=>{this.gainNode&&(this.gainNode.gain.value=this._muted?0:e)});this._muted=g,this._userProvidedMuted=g,this.logger=e,this.clockSource=t,this.reInitWhenStuck=n,this.audioBufferMultiplier=o!==void 0&&o<hm?2:5}get isContextRunning(){var e;return((e=this.audio)==null?void 0:e.state)==="running"}get volume(){return this._volume}set volume(e){this._volume=e,this.muted||this.setGain(e)}get seekTime(){return 0}get totalSeekTime(){return 0}get isSeeking(){return!1}get muted(){var e;return this._muted||!((e=this.audio)!=null&&e.isRunning)}set muted(e){this._userProvidedMuted=e,this._muted=e,this.setGain(this._volume)}get isPaused(){return!1}get currentTime(){var e;return!this.audio||!this.audio.isRunning||this.audio.isStuck?this.clockSource.currentTime:this.audio.currentTime*1e3+((e=this.clockDelta)!=null?e:0)}set currentTime(e){this.logger.debug("setting current time to",{currentTime:e}),this.startTimeIsInvalidated=!0}get audioNode(){return this.splitter}useMediaStreamDestination(){var g;const e=this.getAudioContext(),t=e.getMediaStreamDestination();return(g=this.gainNode)==null||g.connect(t),e.isRunning||e.resume().catch(()=>{}),t}useDefaultDestination(){var g;const t=this.getAudioContext().getDefaultDestination();return(g=this.gainNode)==null||g.connect(t),t}};s(ha,"create",(e,t,g)=>new ha(e,t,g));let fo=ha;const da=class da{constructor(A,e,t,g,n,o){s(this,"staleFrameThresholdMs",400);s(this,"pool");s(this,"logger");s(this,"videoRenderer",new za);s(this,"videoFrameCanvas2DRenderer",null);s(this,"renderQueue",[]);s(this,"clockSource");s(this,"isFirstFrame",!0);s(this,"usingWebCodecs",!1);s(this,"onCanvasChangeCallback");s(this,"onRendererErrorCallback");s(this,"animationFrameRequest");s(this,"firstFrameAnimationFrameRequest");s(this,"pendingFirstFrameSample");s(this,"renderedFrameCount",0);s(this,"rendererDroppedFrameCount",0);s(this,"renderTargetSize");s(this,"load",()=>{this.videoRenderer.load(),this.subscribeToContextLost(this.videoRenderer)});s(this,"unload",()=>(this.stopRender(),this.clearRenderQueue(),this.unsubscribeFromContextLost(this.videoRenderer),this.videoRenderer.unload(),this.videoFrameCanvas2DRenderer&&(this.unsubscribeFromContextLost(this.videoFrameCanvas2DRenderer),this.videoFrameCanvas2DRenderer.unload()),Promise.resolve()));s(this,"suspend",()=>{this.clearRenderQueue(),this.stopRender()});s(this,"unsuspend",()=>{this.animationFrameRequest===void 0&&(this.animationFrameRequest=requestAnimationFrame(this.render))});s(this,"element",()=>this.usingWebCodecs&&this.videoFrameCanvas2DRenderer?this.videoFrameCanvas2DRenderer.canvas:this.videoRenderer.canvas);s(this,"getStatistics",()=>({renderedFrameCount:this.renderedFrameCount,rendererDroppedFrameCount:this.rendererDroppedFrameCount}));s(this,"resetSize",()=>{this.videoRenderer.resetSize()});s(this,"setActiveCues",(A,e)=>{this.usingWebCodecs&&this.videoFrameCanvas2DRenderer?this.videoFrameCanvas2DRenderer.setActiveCues(A,e):this.usingWebCodecs||this.videoRenderer.getTextRenderer().setActiveCues(A,e)});s(this,"onDecodedFrame",A=>{if(A.type==="video")if(this.isFirstFrame)this.isFirstFrame=!1,this.pendingFirstFrameSample=A,this.firstFrameAnimationFrameRequest=requestAnimationFrame(()=>{this.firstFrameAnimationFrameRequest=void 0;const e=this.pendingFirstFrameSample;this.pendingFirstFrameSample=void 0,e&&this.renderSample(e)});else{const e=(this.clockSource.currentTime-this.staleFrameThresholdMs)/1e3;this.renderQueue=this.renderQueue.filter(t=>{const g=this.samplePresentationTime(t),n=this.samplePresentationTime(A),o=g>e&&g<=n;return o||this.releaseSampleResources(t),o}),this.renderQueue.push(A)}});s(this,"render",()=>{const A=this.clockSource.currentTime;let e=this.renderQueue[0],t,g=0;for(;e&&this.samplePresentationTime(e)*1e3<=A;)e=this.renderQueue.shift(),e&&(g++,t&&this.releaseSampleResources(t),t=e),e=this.renderQueue[0];t&&this.renderSample(t),this.rendererDroppedFrameCount+=Math.max(g-1,0),this.animationFrameRequest=requestAnimationFrame(this.render)});s(this,"renderSample",A=>{var e,t;if(this.renderedFrameCount++,A.videoFrame){let g=this.videoFrameCanvas2DRenderer;if(!this.usingWebCodecs){this.logger.info("Switching to Canvas2D renderer for WebCodecs"),g||(g=new _c,g.load(),this.subscribeToContextLost(g),this.videoFrameCanvas2DRenderer=g);const n=this.videoRenderer.canvas,o=g.canvas;if(n.parentElement)try{n.parentElement.replaceChild(o,n)}catch(a){}this.usingWebCodecs=!0,(e=this.onCanvasChangeCallback)==null||e.call(this)}g?g.render(A,this.getSubtitlePadding()):this.videoRenderer.render(A,this.renderTargetSize),A.videoFrame.close()}else{if(this.usingWebCodecs){this.logger.info("Switching back to WebGL renderer for WASM");const g=this.videoFrameCanvas2DRenderer;if(!g){this.usingWebCodecs=!1,this.videoRenderer.render(A,this.renderTargetSize),A.buffer.byteLength>0&&this.pool.reclaim(A.buffer);return}const n=g.canvas,o=this.videoRenderer.canvas;if(n.parentElement)try{n.parentElement.replaceChild(o,n)}catch(a){}this.usingWebCodecs=!1,(t=this.onCanvasChangeCallback)==null||t.call(this)}this.videoRenderer.render(A,this.renderTargetSize)}A.buffer.byteLength>0&&this.pool.reclaim(A.buffer)});s(this,"stopRender",()=>{this.animationFrameRequest!==void 0&&(cancelAnimationFrame(this.animationFrameRequest),this.animationFrameRequest=void 0),this.firstFrameAnimationFrameRequest!==void 0&&(cancelAnimationFrame(this.firstFrameAnimationFrameRequest),this.firstFrameAnimationFrameRequest=void 0),this.pendingFirstFrameSample&&(this.releaseSampleResources(this.pendingFirstFrameSample),this.pendingFirstFrameSample=void 0)});s(this,"clearRenderQueue",()=>{this.renderQueue.forEach(A=>{this.releaseSampleResources(A)}),this.renderQueue=[]});s(this,"onRendererContextLost",A=>{var e;(e=this.onRendererErrorCallback)==null||e.call(this,A)});s(this,"subscribeToContextLost",A=>{const e=A;typeof e.on=="function"&&e.on("context lost",this.onRendererContextLost)});s(this,"unsubscribeFromContextLost",A=>{const e=A;typeof e.off=="function"&&e.off("context lost",this.onRendererContextLost)});s(this,"getSubtitlePadding",()=>{const A=this.renderTargetSize.style.getPropertyValue("--vindral-subtitle-offset")||this.renderTargetSize.style.getPropertyValue("--vindral-control-bar-offset"),e=parseInt(A||"0",10);return Number.isNaN(e)?0:-e});s(this,"samplePresentationTime",A=>(A.timestamp+(A.compositionTimeOffset||0))/A.timescale);s(this,"releaseSampleResources",A=>{var e;try{(e=A.videoFrame)==null||e.close()}catch(t){}A.buffer.byteLength>0&&this.pool.reclaim(A.buffer)});this.logger=A,this.clockSource=e,this.pool=t,this.renderTargetSize=g||this.videoRenderer.canvas,this.onCanvasChangeCallback=n,this.onRendererErrorCallback=o}};s(da,"create",(A,e,t,g,n,o)=>new da(A,e,t,g,n,o));let Do=da;class kQ{constructor(){r(this,Zt,[]);E(this,Zt,[])}addTextTrack(A,e,t){const g=[],n={kind:A,label:e,language:t,mode:"disabled",cues:g,addCue:o=>{g.push(o)},removeCue:o=>{const a=g.findIndex(B=>B===o);a!==-1&&g.splice(a,1)}};return I(this,Zt).push(n),n}set language(A){I(this,Zt).forEach(e=>{e.language===A?e.mode="showing":e.mode="hidden"})}get language(){var A;return(A=I(this,Zt).find(e=>e.mode==="showing"))==null?void 0:A.language}getActiveCues(A){const e=I(this,Zt).find(t=>t.mode==="showing");return e?e.cues.filter(({startTime:t,endTime:g})=>A>=t&&A<=g):[]}}Zt=new WeakMap;const Ii=(i,A)=>{let e;for(e=A;i>1;i--)e+=A;return e};class dm{constructor(){s(this,"audio");s(this,"unmute",()=>this.audio.play().catch(G));const A=document.createElement("div");A.innerHTML="<audio x-webkit-airplay='deny'></audio>";const e=A.children.item(0);if(e instanceof HTMLAudioElement)this.audio=e,this.audio.controls=!1,this.audio.disableRemotePlayback=!0,this.audio.preload="auto",this.audio.src="data:audio/mpeg;base64,//uQx"+Ii(23,"A")+"WGluZwAAAA8AAAACAAACcQCA"+Ii(16,"gICA")+Ii(66,"/")+"8AAABhTEFNRTMuMTAwA8MAAAAAAAAAABQgJAUHQQAB9AAAAnGMHkkI"+Ii(320,"A")+"//sQxAADgnABGiAAQBCqgCRMAAgEAH"+Ii(15,"/")+"7+n/9FTuQsQH//////2NG0jWUGlio5gLQTOtIoeR2WX////X4s9Atb/JRVCbBUpeRUq"+Ii(18,"/")+"9RUi0f2jn/+xDECgPCjAEQAABN4AAANIAAAAQVTEFNRTMuMTAw"+Ii(97,"V")+"Q==",this.audio.loop=!1,this.audio.load();else throw new Error("Failed to create audio tag")}}const la=class la{constructor(A,e,t,g,n,o,a,B){s(this,"logger");s(this,"emitter");s(this,"audioPlayer");s(this,"videoPlayer");s(this,"pool");s(this,"unmuter",new dm);s(this,"_isPaused",!1);s(this,"isDisconnected",!1);s(this,"timers",new JA);s(this,"isVideoRenderingEnabled",!0);s(this,"isLoaded",!1);s(this,"isSuspended",!0);s(this,"isVideoPlayerLoaded",!1);s(this,"textTracks",new kQ);s(this,"playbackRate");s(this,"reset",()=>{});s(this,"load",()=>{this.audioPlayer.useDefaultDestination(),this.emitter.on("decoded frame",this.onDecodedFrame),this.emitter.on("flush buffers",this.flushBuffers),this.isLoaded=!0,this.isVideoRenderingEnabled&&(this.videoPlayer.load(),this.isVideoPlayerLoaded=!0,this.startTextTrackInterval())});s(this,"unload",()=>{this.emitter.off("decoded frame",this.onDecodedFrame),this.emitter.off("flush buffers",this.flushBuffers),this.audioPlayer.unload(),this.isVideoPlayerLoaded&&(this.videoPlayer.unload(),this.isVideoPlayerLoaded=!1),this.timers.unload(),this.isLoaded=!1});s(this,"suspend",()=>{this.isSuspended=!0,this.isVideoRenderingEnabled&&this.videoPlayer.suspend(),this.audioPlayer.suspend()});s(this,"unsuspend",()=>{this.isSuspended=!1,this.isVideoRenderingEnabled&&this.videoPlayer.unsuspend(),this.audioPlayer.unsuspend()});s(this,"setVideoRenderingEnabled",A=>{if(A!==this.isVideoRenderingEnabled&&(this.isVideoRenderingEnabled=A,!!this.isLoaded)){if(!A){this.timers.unload(),this.videoPlayer.suspend();return}this.isVideoPlayerLoaded||(this.videoPlayer.load(),this.isVideoPlayerLoaded=!0),this.startTextTrackInterval(),this.isSuspended||this.videoPlayer.unsuspend()}});s(this,"element",()=>this.videoPlayer.element());s(this,"getStatistics",()=>this.videoPlayer.getStatistics());s(this,"startTextTrackInterval",()=>{this.timers.setInterval(()=>{if(!this.textTracks.language)return;const A=this.textTracks.getActiveCues(this.currentTime/1e3);this.videoPlayer.setActiveCues(A,{width:this.videoPlayer.element().clientWidth,height:this.videoPlayer.element().clientHeight})},100)});s(this,"flushBuffers",()=>{this.audioPlayer.flushBuffer()});s(this,"activateAudioPlayer",()=>(this.isDisconnected&&(this.isDisconnected=!1,this.audioPlayer.useDefaultDestination()),this._isPaused=!1,this.unmuter.unmute(),this.audioPlayer.play()));s(this,"onDecodedFrame",A=>{try{this.audioPlayer.onDecodedFrame(A)}catch(e){e instanceof Error&&this.emitter.emit("error",hC(!1,e))}this.isVideoRenderingEnabled&&this.videoPlayer.onDecodedFrame(A)});this.logger=e,this.emitter=A,this.pool=t,this.audioPlayer=fo.create(this.logger.createContext("AudioPlayerModule"),g,{muted:n,reInitWhenStuck:!0,bufferTime:B}),o!==void 0&&(this.audioPlayer.volume=o),this.audioPlayer.on("stuck",()=>{this.isDisconnected=!0}),this.audioPlayer.on("state change",()=>{this.emitter.emit("volume state",{volume:this.volume,isMuted:this.muted})}),this.videoPlayer=Do.create(this.logger.createContext("VideoPlayerModule"),this.audioPlayer,this.pool,void 0,a)}get volume(){return this.audioPlayer.volume}set volume(A){this.audioPlayer.volume=A}get muted(){return this.audioPlayer.muted}set muted(A){const e=this.muted;this.audioPlayer.muted=A,!A&&e&&this.activateAudioPlayer().catch(G)}get currentTime(){return this.audioPlayer.currentTime}set currentTime(A){this.audioPlayer.currentTime=A}get isActivated(){return this.audioPlayer.isActivated}set isActivated(A){this.audioPlayer.isActivated=A}get seekTime(){return this.audioPlayer.seekTime}get totalSeekTime(){return this.audioPlayer.totalSeekTime}get isPaused(){return this._isPaused}get isSeeking(){return this.audioPlayer.isSeeking}get audioNode(){return this.audioPlayer.audioNode}play(){this.activateAudioPlayer().then(()=>{this.emitter.emit("media element state","playing")}).catch(()=>{this.emitter.emit("needs user input",{forAudio:!0,forVideo:!1})})}pause(){this._isPaused=!0,this.audioPlayer.pause(),this.emitter.emit("media element state","paused")}};s(la,"create",(A,e,t,g,n,o,a,B)=>new la(A,e,t,g,n,o,a,B));let So=la;const ua=class ua{constructor(A,e,t,g,{muted:n,volume:o,type:a,poster:B,offscreenCanvas:C,bufferTime:Q}){s(this,"logger");s(this,"emitter");s(this,"mediaElement");s(this,"audioPlayer");s(this,"videoPlayer");s(this,"pool");s(this,"isDisconnected",!0);s(this,"_userProvidedMuted",!1);s(this,"timers",new JA);s(this,"offscreenCanvas");s(this,"nativeTextTrack");s(this,"nativeTrackCues",[]);s(this,"volumeState");s(this,"textTracks",new kQ);s(this,"reset",()=>{});s(this,"load",()=>{this.mediaElement.load(),this.emitter.on("decoded frame",this.onDecodedFrame),this.emitter.on("flush buffers",this.flushBuffers),this.emitter.on("ios-hack: reset size",this.resetCanvasSize),this.emitter.on("enter picture in picture",this.onEnterIOSHack),this.emitter.on("exit picture in picture",this.onExitIOSHack),this.element().element.addEventListener("webkitendfullscreen",this.onExitIOSHack),this.element().element.addEventListener("webkitbeginfullscreen",this.onEnterIOSHack),this.videoPlayer.load(),this.nativeTextTrack=this.mediaElement.element.addTextTrack("subtitles","",""),this.nativeTextTrack.mode="showing",this.timers.setInterval(()=>{if(!this.textTracks.language){this.clearNativeTrackCues();return}const A=this.textTracks.getActiveCues(this.currentTime/1e3);this.updateNativeTrackCues(A)},100)});s(this,"unload",()=>{this.emitter.off("decoded frame",this.onDecodedFrame),this.emitter.off("flush buffers",this.flushBuffers),this.emitter.off("ios-hack: reset size",this.resetCanvasSize),this.emitter.off("enter picture in picture",this.onEnterIOSHack),this.emitter.off("exit picture in picture",this.onExitIOSHack),this.element().element.removeEventListener("webkitendfullscreen",this.onExitIOSHack),this.element().element.removeEventListener("webkitbeginfullscreen",this.onEnterIOSHack),this.clearNativeTrackCues(),this.nativeTextTrack=void 0,this.mediaElement.unload(),this.timers.unload(),this.audioPlayer.unload(),this.videoPlayer.unload()});s(this,"suspend",()=>{this.videoPlayer.suspend(),this.audioPlayer.suspend()});s(this,"unsuspend",()=>{this.videoPlayer.unsuspend(),this.audioPlayer.unsuspend()});s(this,"element",()=>this.mediaElement);s(this,"getStatistics",()=>this.videoPlayer.getStatistics());s(this,"activateAudioPlayer",()=>(this.isDisconnected&&this.connectStreams(),this.audioPlayer.play()));s(this,"flushBuffers",()=>{this.audioPlayer.flushBuffer()});s(this,"resetCanvasSize",()=>{this.videoPlayer.resetSize()});s(this,"onEnterIOSHack",()=>{this.mediaElement._iosHackEnterPiPMode()});s(this,"onExitIOSHack",()=>{this.mediaElement._iosHackExitPiPMode()});s(this,"onDecodedFrame",A=>{try{this.audioPlayer.onDecodedFrame(A)}catch(e){e instanceof Error&&this.emitter.emit("error",hC(!1,e))}this.offscreenCanvas||this.videoPlayer.onDecodedFrame(A)});s(this,"onVideoPlayerError",A=>{if(A instanceof x){this.emitter.emit("error",A);return}this.emitter.emit("error",Xa(!1,A))});s(this,"connectStreams",()=>{const A=this.offscreenCanvas||this.videoPlayer.element();this.logger.info(`Connecting streams using ${this.offscreenCanvas?"OffscreenCanvas":"VideoPlayer"} canvas (${A.width}x${A.height})`);const e=A.captureStream(),t=this.audioPlayer.useMediaStreamDestination().stream,g=[...e.getTracks(),...t.getTracks()];this.logger.info(`Video tracks: ${e.getTracks().length}, Audio tracks: ${t.getTracks().length}`);const n=this.mediaElement.element.srcObject;n instanceof MediaStream&&n.getVideoTracks().forEach(o=>o.stop()),this.mediaElement.element.srcObject=new MediaStream(g),this.isDisconnected=!1});s(this,"setOffscreenCanvas",A=>{this.offscreenCanvas!==A&&(this.offscreenCanvas=A,this.reconnectCanvasStream())});s(this,"reconnectCanvasStream",()=>{if(!this.isDisconnected){const A=!this.mediaElement.element.paused;this.logger.info("Reconnecting canvas stream after renderer change",{wasPlaying:A}),this.connectStreams(),A&&this.mediaElement.tryPlay()}});s(this,"clearNativeTrackCues",()=>{if(this.nativeTextTrack){for(const A of this.nativeTrackCues)try{this.nativeTextTrack.removeCue(A)}catch(e){}this.nativeTrackCues=[]}});s(this,"updateNativeTrackCues",A=>{const e=this.nativeTextTrack;if(!e)return;const t=A.map(n=>n.text),g=this.nativeTrackCues.map(n=>n.text);if(!(t.length===g.length&&t.every((n,o)=>n===g[o]))){this.clearNativeTrackCues();for(const n of A){const o=new VTTCue(0,999999999,n.text);e.addCue(o),this.nativeTrackCues.push(o)}}});s(this,"updateVolumeState",()=>{const A={isMuted:this.muted,volume:this.volume};gs(A,this.volumeState)||(this.volumeState=A,this.emitter.emit("volume state",this.volumeState))});this.logger=e,this.emitter=A,this.pool=t,this._userProvidedMuted=n,this.offscreenCanvas=C,this.mediaElement=new BB({poster:B,type:a,muted:n,volume:o,autoplay:!1,logger:this.logger.createContext("MediaElement")}),this.mediaElement.on("volume state",h=>{this.updateVolumeState(),!h.isMuted&&!this.audioPlayer.isContextRunning&&this.activateAudioPlayer().catch(G),h.isMuted||(this._userProvidedMuted=!1)}),this.mediaElement.on("media element state",h=>{h==="paused"&&this.audioPlayer.flushBuffer(),this.emitter.emit("media element state",h)}),this.audioPlayer=fo.create(this.logger.createContext("AudioPlayerModule"),g,{muted:!1,reInitWhenStuck:!1,bufferTime:Q}),this.audioPlayer.on("stuck",()=>{this.isDisconnected=!0}),this.audioPlayer.on("state change",h=>{h==="suspended"||h==="interrupted"?this.mediaElement.muted=!0:h==="running"&&(this.mediaElement.muted=this._userProvidedMuted||document.visibilityState==="hidden"),this.updateVolumeState()}),this.videoPlayer=Do.create(this.logger.createContext("VideoPlayerModule"),this.audioPlayer,this.pool,this.mediaElement.element,()=>this.reconnectCanvasStream(),this.onVideoPlayerError),this.volumeState={volume:this.volume,isMuted:this.muted}}get volume(){return this.mediaElement.volume}set volume(A){this.mediaElement.volume=A}get muted(){return this.mediaElement.muted||this.audioPlayer.muted}set muted(A){const e=this.muted;this._userProvidedMuted=A,this.mediaElement.muted=A,!A&&e&&this.activateAudioPlayer().catch(G)}get currentTime(){return this.audioPlayer.currentTime}set currentTime(A){this.audioPlayer.currentTime=A}get isActivated(){return this.mediaElement.isActivated}set isActivated(A){this.mediaElement.isActivated=A}get seekTime(){return this.mediaElement.seekTime}get totalSeekTime(){return this.mediaElement.totalSeekTime}get isPaused(){return this.mediaElement.isPaused}get isSeeking(){return this.mediaElement.isSeeking}get audioNode(){return this.audioPlayer.audioNode}play(){const A=this._userProvidedMuted;return this.activateAudioPlayer().catch(()=>{A||this.emitter.emit("needs user input",{forAudio:!0,forVideo:!1})}),this.mediaElement.play()}pause(){this.mediaElement.pause()}};s(ua,"create",(A,e,t,g,n)=>new ua(A,e,t,g,n));let rs=ua;const lm=()=>i=>RQ(i.buffered.start(0),i.buffered.end(i.buffered.length-1)),RQ=(i,A)=>e=>e.remove(Math.max(0,i),Math.min(Number.POSITIVE_INFINITY,A)),GQ=i=>A=>A.appendBuffer(i),um=i=>A=>A.changeType(i),mm=i=>A=>i(A);class wm{constructor(A){s(this,"commandQueue",[]);s(this,"sourceBuffer");s(this,"currentInit");s(this,"handleQueue",()=>{var A;this.sourceBuffer.updating||(A=this.commandQueue.shift())==null||A.execute(this.sourceBuffer)});s(this,"appendBuffer",(A,e)=>new Promise((t,g)=>{if(e&&this.currentInit!==e){const o=new ss(GQ(e),t,g);this.commandQueue.push(o),this.currentInit=e}const n=new ss(GQ(A),t,g);this.commandQueue.push(n),this.handleQueue()}));s(this,"execute",A=>new Promise((e,t)=>{const g=new ss(mm(A),e,t);this.commandQueue.push(g),this.handleQueue()}));s(this,"buffered",()=>this.sourceBuffer.buffered);s(this,"removeFromMediaSource",A=>{A.removeSourceBuffer(this.sourceBuffer)});s(this,"changeType",A=>new Promise((e,t)=>{const g=new ss(um(A),e,t);this.commandQueue.push(g),this.handleQueue()}));s(this,"removeBuffer",(A,e)=>new Promise((t,g)=>{const n=new ss(RQ(A,e),t,g);this.commandQueue.push(n),this.handleQueue()}));s(this,"flush",()=>new Promise((A,e)=>{const t=new ss(lm,A,e);this.commandQueue.push(t),this.handleQueue()}));this.sourceBuffer=A,this.sourceBuffer.addEventListener("updateend",this.handleQueue)}}class UQ extends ie{constructor(){super();s(this,"MediaSource",is());s(this,"mediaSource",new this.MediaSource);s(this,"isOpen",()=>this.mediaSource.readyState==="open");s(this,"isClosed",()=>this.mediaSource.readyState==="closed");s(this,"isEnded",()=>this.mediaSource.readyState==="ended");s(this,"createObjectURL",()=>URL.createObjectURL(this.mediaSource));s(this,"attach",e=>{const t=e;if("srcObject"in t)try{t.srcObject=this.mediaSource}catch(g){if(g instanceof Error&&g.name!=="TypeError")throw g;t.src=this.createObjectURL()}else e.src=this.createObjectURL()});s(this,"detach",e=>{if(this.mediaSource&&this.mediaSource.readyState==="open")try{this.mediaSource.endOfStream()}catch(t){}e.srcObject&&(e.srcObject=null),e.src!==""&&(URL.revokeObjectURL(e.src),e.removeAttribute("src")),e.load()});s(this,"addSourceBuffer",e=>{const t=this.mediaSource.addSourceBuffer(e);return new wm(t)});s(this,"removeSourceBuffer",e=>{e.removeFromMediaSource(this.mediaSource)});s(this,"endOfStream",e=>{this.mediaSource.endOfStream(e)});s(this,"onSourceOpen",()=>{this.setDurationIfNeeded(),this.emit("source open")});s(this,"onSourceEnded",()=>this.emit("source ended"));s(this,"onSourceClosed",()=>this.emit("source close"));s(this,"setDurationIfNeeded",()=>{if(Number.isNaN(this.mediaSource.duration)&&this.mediaSource.readyState==="open"){for(let e=0;e<this.mediaSource.sourceBuffers.length;e++){const t=this.mediaSource.sourceBuffers[e];if(t!=null&&t.updating)return}this.mediaSource.duration=Number.POSITIVE_INFINITY}});this.mediaSource.addEventListener("sourceopen",this.onSourceOpen),this.mediaSource.addEventListener("sourceclose",this.onSourceClosed),this.mediaSource.addEventListener("sourceended",this.onSourceEnded)}}s(UQ,"isTypeSupported",e=>{var t,g;return(g=(t=is())==null?void 0:t.isTypeSupported(e))!=null?g:!1});class bQ{constructor(){s(this,"initSegments",new Map);s(this,"set",(A,e,t)=>{var n;const g=(n=this.initSegments.get(A))!=null?n:new Map;g.set(e,t),this.initSegments.set(A,g)});s(this,"get",(A,e)=>{var t;return(t=this.initSegments.get(A))==null?void 0:t.get(e)})}}function fm(i,{mediaSource:A,mimeType:e,codec:t}){return V(f({},i),{state:"initialized",mimeType:e,codec:t,sourceBuffer:A.addSourceBuffer(e),isWorkingOnPendingSamples:!1,sequenceNumber:0,lastBufferCleanupTime:Date.now()})}function NQ({initSegments:i,pendingSamples:A}){return{state:"uninitialized",initSegments:i!=null?i:new bQ,sequenceNumber:0,isWorkingOnPendingSamples:!1,hasFirstSync:!!A,pendingSamples:A!=null?A:[],pendingSamplesOffset:0,consecutiveQuotaExceededErrorCount:0,successfulAppendCalls:0}}const ma=class ma{constructor(A,e,t){s(this,"maxChunkSize",20);s(this,"minConsecutiveErrorsBeforeEmit",5);s(this,"maxSecondsInBuffer",60);s(this,"logger");s(this,"timers",JA.create());s(this,"emitter");s(this,"mediaElement");s(this,"mediaSource",new UQ);s(this,"trackContexts",new Map);s(this,"autoRecoverFromMediaErrors",!0);s(this,"quotaErrorCount",0);s(this,"recoveredFromErrorCount",0);s(this,"sourceOpenStartTime",Date.now());s(this,"sourceOpenEndTime",Date.now());s(this,"pendingTracksToAddSourceBuffers");s(this,"hasAddedInitialPosterFrame",!0);s(this,"videoKeyframeTimestamps",[]);s(this,"load",()=>{this.emitter.on("init segment",this.init),this.emitter.on("coded sample",this.onCodedSample),this.emitter.on("flush buffers",this.flushBuffers),this.emitter.on("fragment",this.onFragment)});s(this,"unload",()=>{this.logger.debug("Unloading module..."),this.emitter.off("init segment",this.init),this.emitter.off("coded sample",this.onCodedSample),this.emitter.off("flush buffers",this.flushBuffers),this.emitter.off("fragment",this.onFragment),this.mediaSource.off("source ended",this.onSourceEnded),this.mediaSource.off("source open",this.onSourceOpen),this.mediaSource.detach(this.mediaElement),this.trackContexts.forEach(A=>{A.pendingSamples=[],A.pendingSamplesOffset=0}),this.videoKeyframeTimestamps=[],this.timers.unload(),this.logger.debug("Unloaded module")});s(this,"getStatistics",()=>{var e,t,g,n;const A={quotaErrorCount:this.quotaErrorCount,mediaSourceOpenTime:this.sourceOpenEndTime-this.sourceOpenStartTime,successfulAudioAppendsCalls:(e=this.trackContexts.get("audio"))==null?void 0:e.successfulAppendCalls,successfulVideoAppendCalls:(t=this.trackContexts.get("video"))==null?void 0:t.successfulAppendCalls,videoKeyframeIntervalMs:Wr(this.videoKeyframeTimestamps),videoRenderer:"MSE",videoDecoder:"MSE",audioRenderer:"MSE",audioDecoder:"MSE"};if(this.mediaElement instanceof HTMLVideoElement){const o=(n=(g=this.mediaElement).getVideoPlaybackQuality)==null?void 0:n.call(g);A.totalVideoFrames=o==null?void 0:o.totalVideoFrames,A.droppedVideoFrames=o==null?void 0:o.droppedVideoFrames}return A});s(this,"flushBuffers",()=>{this.videoKeyframeTimestamps=[],this.trackContexts.forEach(A=>{A.pendingSamples=[],A.pendingSamplesOffset=0,A.hasFirstSync=!1,A.state!=="uninitialized"&&this.mediaSource.isOpen()&&A.sourceBuffer.removeBuffer(0,Number.POSITIVE_INFINITY).catch(e=>{this.logger.error("Failed to remove buffer",e)})})});s(this,"setTrackContexts",(A=new Map)=>{this.logger.debug("setTrackContexts"),["audio","video"].forEach(t=>{var C,Q,h;const g=A.get(t),n=(C=g==null?void 0:g.pendingSamples)!=null?C:[],o=g==null?void 0:g.initSegments;let a=(Q=g==null?void 0:g.pendingSamplesOffset)!=null?Q:0;for(;a<n.length&&!((h=n[a])!=null&&h.isSync);)a++;const B=NQ({pendingSamples:n,initSegments:o});B.pendingSamplesOffset=a,this.trackContexts.set(t,B)})});s(this,"setSourceBuffers",A=>c(this,null,function*(){if(this.mediaSource.isClosed()){this.pendingTracksToAddSourceBuffers=A;return}let e=!0;for(const t of A){const g=this.trackContexts.get(t.type);if(!g||g.state==="uninitialized"||g.mimeType!==t.mimeType){e=!1;break}}if(e){this.logger.debug("Already setup with the correct mime types");return}for(const t of A){let g=this.trackContexts.get(t.type);g||(g=NQ({pendingSamples:[],initSegments:new bQ}),this.trackContexts.set(t.type,g)),g.state==="initialized"?t.mimeType!==g.mimeType&&(yield g.sourceBuffer.changeType(t.mimeType)):this.trackContexts.set(t.type,fm(g,{mimeType:t.mimeType,mediaSource:this.mediaSource,codec:t.codec}))}}));s(this,"getBuffer",A=>{const e=[];if(this.mediaSource.isClosed())return[];const t=this.trackContexts.get(A);if(!t||t.state==="uninitialized")return[];try{const g=t.sourceBuffer.buffered();if(!g)return[];for(let n=0;n<g.length;n++)e.push({start:g.start(n)*1e3,end:g.end(n)*1e3});return e}catch(g){return[]}});s(this,"getVideoKeyframeTimestamps",()=>this.videoKeyframeTimestamps);s(this,"init",({initSegment:A,mimeType:e})=>{this.logger.debug("Added init segment",{channel:A.channelId,renditionId:A.renditionId});const t=this.trackContexts.get(A.type);if(!t)throw Kn(A.type,A.renditionId);t.state==="initialized"&&(t.mimeType=e);const g=ol({codec:A.codec,timescale:A.timescale,initData:A.data});g&&t.initSegments.set(A.channelId,A.renditionId,new Uint8Array(g))});s(this,"append",(A,e)=>c(this,null,function*(){var a;const t=A[0];if(!t)return;const g=this.trackContexts.get(t.type),n=g==null?void 0:g.initSegments.get(t.channelId,t.renditionId);if(this.mediaSource.isClosed())return;if(!n)throw Eh(t.renditionId,t.channelId);if(!g)throw Kn(t.type,t.renditionId);if(g.state==="uninitialized")throw ch(t.type,t.renditionId);if(e){const B=(t.timestamp+((a=t.compositionTimeOffset)!=null?a:0))/t.timescale;yield g.sourceBuffer.removeBuffer(B,Number.POSITIVE_INFINITY);const C=g.previousSample;if(C&&C.codec!==t.codec&&g.sourceBuffer.changeType)try{yield g.sourceBuffer.changeType(g.mimeType)}catch(Q){}"fragmented"in t||(yield g.sourceBuffer.appendBuffer(n))}const o=Math.max(0,t.timestamp/t.timescale-this.maxSecondsInBuffer);o>0&&Date.now()-g.lastBufferCleanupTime>1e4&&(g.lastBufferCleanupTime=Date.now(),yield g.sourceBuffer.removeBuffer(0,o+10));try{let B=g.sequenceNumber;if("fragmented"in t)for(const C of A)"initData"in C&&(yield g.sourceBuffer.appendBuffer(C.data,C.initData));else{const C=El(A,B++);yield g.sourceBuffer.appendBuffer(C)}g.sequenceNumber=B,g.consecutiveQuotaExceededErrorCount=0,g.successfulAppendCalls++}catch(B){throw B instanceof DOMException&&B.code===DOMException.QUOTA_EXCEEDED_ERR&&(this.quotaErrorCount++,g.consecutiveQuotaExceededErrorCount++,this.logger.error("quota exceeded error",{error:B})),B}}));s(this,"onFragment",({fragment:A,mimeType:e,codec:t,channelId:g,renditionId:n})=>{const o=A.mediaType(),a=A.rawBytes(),B=A.header().rawBytes(),C=A.baseMediaDecodeTime(),Q=A.timescale(),h=A.duration(),d=o==="video"?A.startsWithKeyframe():!0,u=A.compositionTimeOffset(0);if(o==="text"){this.logger.warn("Skipping unexpected text fragment");return}if(!t){this.logger.warn("Skipping fragment with no codec");return}const m=this.trackContexts.get(o);if(!m)throw Kn(o);m.state==="initialized"&&e&&(m.mimeType=e,m.initSegments.set(g,n,B));const p={fragmented:!0,type:o,data:a,initData:B,timestamp:C,duration:h,timescale:Q,channelId:g,renditionId:n,isSync:d,codec:t,fragment:A,compositionTimeOffset:u};this.onCodedSample(p)});s(this,"onCodedSample",A=>{var t;if(A.duration===0)return;const e=this.trackContexts.get(A.type);if(!e)throw Kn(A.type,A.renditionId);if(!(!e.hasFirstSync&&!A.isSync)){if(this.hasAddedInitialPosterFrame&&A.isSync&&A.type==="video"){this.hasAddedInitialPosterFrame=!1;const g=f({},A);"fragment"in g?(g.fragment=g.fragment.clone(),g.fragment.updateBaseMediaDecodeTime(0),g.data=g.fragment.rawBytes()):g.timestamp=0,e.pendingSamples.push(g)}if(e.hasFirstSync=!0,e.pendingSamples.push(A),A.type==="video"&&A.isSync){const g=(A.timestamp+((t=A.compositionTimeOffset)!=null?t:0))/A.timescale*1e3,n=this.videoKeyframeTimestamps[this.videoKeyframeTimestamps.length-1];n!==void 0&&g<n&&(this.videoKeyframeTimestamps=[]),this.videoKeyframeTimestamps.push(g),this.videoKeyframeTimestamps.length>20&&(this.videoKeyframeTimestamps=this.videoKeyframeTimestamps.slice(-20))}e.state!=="uninitialized"&&(e.isWorkingOnPendingSamples||pm(e,this.append,this.maxChunkSize).catch(g=>{if(e.isWorkingOnPendingSamples=!1,g instanceof Error){if(this.logger.error("append failed",{message:g.message,name:g.name}),g instanceof DOMException&&g.code===DOMException.QUOTA_EXCEEDED_ERR){if(e.consecutiveQuotaExceededErrorCount>=this.minConsecutiveErrorsBeforeEmit){const n=dC(!1,g,e.consecutiveQuotaExceededErrorCount,A.type);this.emitter.emit("error",n)}}else{const n=dC(!1,g,e.consecutiveQuotaExceededErrorCount,A.type);this.emitter.emit("error",n)}this.mediaElement.error&&this.onSourceEnded()}}))}});s(this,"onSourceOpen",()=>{this.logger.debug("source opened"),this.sourceOpenEndTime=Date.now(),this.pendingTracksToAddSourceBuffers&&(this.setSourceBuffers(this.pendingTracksToAddSourceBuffers),this.pendingTracksToAddSourceBuffers=void 0)});s(this,"onSourceEnded",()=>{const{error:A}=this.mediaElement;if(A){const e=/AUDIO_RENDERER/.test(A.message)||!this.autoRecoverFromMediaErrors,t=Ch(e,A);if(this.logger.error("MediaElement error",{error:t}),this.emitter.emit("error",t),!t.isFatal()){this.logger.info("Re-opening MediaSource"),this.emitter.emit("recovered from media error",{error:t,count:this.recoveredFromErrorCount}),this.recoveredFromErrorCount++;const g=!this.mediaElement.paused,n=[];this.trackContexts.forEach((o,a)=>{o.state==="initialized"&&n.push({type:a,mimeType:o.mimeType,codec:o.codec})}),this.sourceOpenStartTime=Date.now(),this.pendingTracksToAddSourceBuffers=n,this.mediaElement.src="",this.setTrackContexts(this.trackContexts),this.mediaSource.attach(this.mediaElement),g&&this.mediaElement.play().catch(G)}}this.logger.debug("source ended")});this.logger=A,this.mediaElement=t,this.emitter=e}};s(ma,"create",(A,e,t)=>{const g=new ma(A,e,t);return g.setTrackContexts(),g.mediaSource.on("source ended",g.onSourceEnded),g.mediaSource.on("source open",g.onSourceOpen),g.mediaSource.attach(t),g});let YB=ma;const LQ=(i,A)=>{var a;const e=i.renditionId!==A.renditionId,t=i.channelId!==A.channelId,g=((a=i.timestamp)!=null?a:0)>A.timestamp,n=i.type==="video"&&A.type==="video"&&"levelIdc"in i&&"levelIdc"in A&&i.levelIdc!==A.levelIdc;let o=!1;return i.type==="video"&&A.type==="video"&&"width"in i&&"width"in A&&(o=A.width!==i.width||A.height!==i.height),t||e||g||o||n},Dm=32,Sm=i=>{const A=i.pendingSamplesOffset;if(A!==0){if(A>=i.pendingSamples.length){i.pendingSamples=[],i.pendingSamplesOffset=0;return}A<Dm||A*2<i.pendingSamples.length||(i.pendingSamples=i.pendingSamples.slice(A),i.pendingSamplesOffset=0)}},pm=(i,A,e)=>c(null,null,function*(){for(i.isWorkingOnPendingSamples=!0;i.pendingSamplesOffset<i.pendingSamples.length;){const t=[];let g=i.pendingSamplesOffset;for(let a=i.pendingSamplesOffset;a<i.pendingSamples.length;a++){g=a;const B=i.pendingSamples[a],C=i.pendingSamples[a+1];if(B&&(t.push(B),C)){if(LQ(B,C))break;const Q=(B.timestamp+B.duration)/B.timescale;if(C.timestamp/C.timescale-Q>.1)break}if(a-i.pendingSamplesOffset>=e-1)break}const n=t[0];if(!n)break;const o=i.previousSample?LQ(i.previousSample,n):!0;yield A(t,o),i.pendingSamplesOffset=g+1,i.previousSample=t[t.length-1],Sm(i)}i.isWorkingOnPendingSamples=!1}),wa=class wa{constructor(A,e){s(this,"logger");s(this,"emitter");s(this,"element");s(this,"pictureInPictureWindow");s(this,"unload",()=>{this.emitter.off("add picture in picture listener",this.onEnablePictureInPicture),this.detachElementListeners()});s(this,"onEnablePictureInPicture",A=>{this.detachElementListeners(),this.element=A.element,A.element.addEventListener("leavepictureinpicture",this.onLeavePictureInPicture),A.element.addEventListener("enterpictureinpicture",this.onEnterPictureInPicture),xr(A.element,!0)});s(this,"getPictureInPictureSize",()=>this.pictureInPictureWindow);s(this,"isPictureInPictureActive",()=>this.isWebkitPresentationModeActive()||this.isStandardPictureInPictureActive());s(this,"isPictureInPictureSupported",()=>this.isWebkitPresentationModeSupported()||this.isStandardPictureInPictureSupported());s(this,"requestPictureInPicture",()=>(this.emitter.emit("ios-hack: reset size"),this.isStandardPictureInPictureSupported()?this.requestStandardPictureInPicture():this.isWebkitPresentationModeSupported()?this.requestWebkitPresentationMode("picture-in-picture"):Promise.reject(new Error("Picture in picture is not supported"))));s(this,"exitPictureInPicture",()=>this.isStandardPictureInPictureSupported()?this.exitStandardPictureInPicture():this.isWebkitPresentationModeSupported()?this.requestWebkitPresentationMode("inline"):Promise.reject(new Error("Picture in picture is not supported")));s(this,"getStatistics",()=>({isPictureInPictureActive:this.isPictureInPictureActive()}));s(this,"detachElementListeners",()=>{this.element&&(this.element.removeEventListener("leavepictureinpicture",this.onLeavePictureInPicture),this.element.removeEventListener("enterpictureinpicture",this.onEnterPictureInPicture),xr(this.element,!1))});s(this,"onLeavePictureInPicture",()=>{this.pictureInPictureWindow=void 0,this.logger.debug("Leave picture in picture"),this.emitter.emit("exit picture in picture")});s(this,"onEnterPictureInPicture",A=>{this.pictureInPictureWindow=bc(A),this.logger.debug("Enter picture in picture"),this.emitter.emit("enter picture in picture",this)});s(this,"requestStandardPictureInPicture",()=>c(this,null,function*(){if(!this.element)throw new Error("Picture in picture is not supported");const A=Pr(this.element);if(!A)throw new Error("Picture in picture is not supported");yield A()}));s(this,"exitStandardPictureInPicture",()=>c(null,null,function*(){const A=kc();if(!A)throw new Error("Picture in picture is not supported");yield A()}));s(this,"isStandardPictureInPictureSupported",()=>!!this.element&&Uc(this.element));s(this,"isStandardPictureInPictureActive",()=>!!this.element&&Gc());s(this,"isWebkitPresentationModeActive",()=>!!this.element&&Nc(this.element)==="picture-in-picture");s(this,"requestWebkitPresentationMode",A=>c(this,null,function*(){return this.element&&Lc(this.element,A),Promise.resolve()}));s(this,"isWebkitPresentationModeSupported",()=>!!this.element&&Jc(this.element));this.emitter=A,this.logger=e,this.emitter.on("add picture in picture listener",this.onEnablePictureInPicture)}};s(wa,"create",(A,e)=>new wa(A,e));let PB=wa;const fa=class fa{constructor(A,e,t,g){s(this,"emitter");s(this,"logger");s(this,"clockSource");s(this,"state","buffering");s(this,"bufferFullness",0);s(this,"targetBufferTime");s(this,"lastBufferStateEvent","drained");s(this,"firstFrameTime");s(this,"currentTimeIsInRange",!1);s(this,"needsInputForAudioCount",0);s(this,"needsInputForVideoCount",0);s(this,"unload",()=>{this.emitter.off("buffer state",this.onBufferedStateChanged),this.emitter.off("needs user input",this.onNeedsUserInput)});s(this,"setTargetBufferTime",A=>{this.targetBufferTime=A,this.emitter.emit("target buffer time",A)});s(this,"getTargetBufferTime",()=>this.targetBufferTime);s(this,"getBufferFullness",()=>this.bufferFullness);s(this,"getLastBufferStateEvent",()=>this.lastBufferStateEvent);s(this,"getState",()=>this.state);s(this,"getFirstFrameTime",()=>this.firstFrameTime);s(this,"getStatistics",()=>({bufferTime:this.targetBufferTime,needsInputForAudioCount:this.needsInputForAudioCount,needsInputForVideoCount:this.needsInputForVideoCount}));s(this,"onBufferedStateChanged",({buffered:A,isPaused:e,playbackState:t})=>{const g=this.clockSource.currentTime,n=A.some(h=>h.start<=g&&g<h.end),o=A[A.length-1],a=o?o.end-o.start>=this.targetBufferTime:!1,B=o?Math.max(0,o.end-g)/this.targetBufferTime:0;let C=e?"paused":t;const Q=this.state;this.currentTimeIsInRange!==n&&!n?(this.lastBufferStateEvent="drained",this.emitter.emit("buffer state event",this.lastBufferStateEvent)):n&&a&&this.lastBufferStateEvent==="drained"&&(this.lastBufferStateEvent="filled",this.emitter.emit("buffer state event",this.lastBufferStateEvent)),C==="playing"&&!this.firstFrameTime&&(this.firstFrameTime=Date.now()),this.currentTimeIsInRange=n,this.state=C,this.bufferFullness=n?B:0,Q!==C&&this.emitter.emit("playback state",C),this.emitter.emit("buffer fullness",this.bufferFullness)});s(this,"onNeedsUserInput",({forAudio:A,forVideo:e})=>{A&&this.needsInputForAudioCount++,e&&this.needsInputForVideoCount++});this.emitter=A,this.logger=e,this.clockSource=t,this.targetBufferTime=g,this.emitter.on("buffer state",this.onBufferedStateChanged),this.emitter.on("needs user input",this.onNeedsUserInput),this.emitter.emit("target buffer time",g)}};s(fa,"create",(A,e,t,g)=>new fa(A,e,t,g));let xB=fa;const WB=()=>({upgradesFromLevel:[],downgradesFromLevel:[],bufferingRanges:[],activeRanges:[],decodeRate:Number.MAX_SAFE_INTEGER}),ym=()=>({levels:{},levelDowngrades:[],levelUpgrades:[],bufferFullness:0,general:WB()}),Da=class Da{constructor(A,e,t){s(this,"minBufferFullnessLengthForRegression",6);s(this,"logger");s(this,"emitter");s(this,"timers",JA.create());s(this,"metrics",ym());s(this,"bufferFullness",new P(30));s(this,"bufferFullnessRegression");s(this,"currentLevel");s(this,"isSuspended",!1);s(this,"_fatalQosCount",0);s(this,"targetBufferTime",0);s(this,"renditionLevelSource");s(this,"qualityIndexOrder",[]);s(this,"hasAsserted",!1);s(this,"load",()=>{this.emitter.on("playback state",this.onPlaybackState),this.emitter.on("buffer fullness",this.onBufferFullness),this.emitter.on("rendition level changed",this.onRenditionLevelChanged),this.emitter.on("video decode rate",this.onVideoDecodeRate),this.emitter.on("target buffer time",this.onTargetBufferTime)});s(this,"unload",()=>{this.emitter.off("playback state",this.onPlaybackState),this.emitter.off("buffer fullness",this.onBufferFullness),this.emitter.off("rendition level changed",this.onRenditionLevelChanged),this.emitter.off("video decode rate",this.onVideoDecodeRate),this.emitter.off("target buffer time",this.onTargetBufferTime),this.suspend()});s(this,"suspend",()=>{this.isSuspended=!0,this.timers.unload(),this.stopBuffering(),this.unsetActive()});s(this,"unsuspend",()=>{this.isSuspended=!1,this.currentLevel&&this.setActive()});s(this,"fatalQosGraceTime",()=>1e4*(this.fatalQosCount+1));s(this,"incrementFatalQosCount",()=>{this._fatalQosCount++});s(this,"getMetrics",()=>this.metrics);s(this,"getLevelStats",A=>{var t,g,n,o;const e=((g=(t=A.video)==null?void 0:t.bitRate)!=null?g:0)+((o=(n=A.audio)==null?void 0:n.bitRate)!=null?o:0);return this.metrics.levels[e]});s(this,"getBufferFullnessRegression",()=>this.bufferFullnessRegression);s(this,"getTargetBufferTime",()=>this.targetBufferTime);s(this,"activeRatios",()=>{const A=new Map,e=ns(this.metrics.general.activeRanges);if(Object.entries(this.metrics.levels).forEach(([t,g])=>{var B;const n=parseInt(t,10),o=e?ns(g.activeRanges)/e:0,a=this.getQualityIndex(n).toString();A.set(a,((B=A.get(a))!=null?B:0)+o)}),!this.hasAsserted){const t=A.size?Math.abs(Array.from(A.values()).reduce((g,n)=>g+n,0)-1)<=.02:!0;t||(this.hasAsserted=!0,console.assert(t,`Active ratios should be close to 1 - actual: ${Array.from(A.values()).reduce((g,n)=>g+n,0)}`))}return A});s(this,"bufferingRatios",()=>{const A=new Map,e=ns(this.metrics.general.bufferingRanges);if(Object.entries(this.metrics.levels).forEach(([t,g])=>{var B;const n=parseInt(t,10),o=e?ns(g.bufferingRanges)/e:0,a=this.getQualityIndex(n).toString();A.set(a,((B=A.get(a))!=null?B:0)+o)}),!this.hasAsserted){const t=Array.from(A.values()).reduce((g,n)=>g+n,0)<=1;t||(this.hasAsserted=!0,console.assert(t,`Buffering ratios should be less than 1 - actual: ${Array.from(A.values()).reduce((g,n)=>g+n,0)}`))}return A});s(this,"bufferingEventsLast",A=>this.metrics.general.bufferingRanges.filter(e=>e.start>=Date.now()-A).length);s(this,"timeSpentBufferingLast",A=>jr(this.metrics.general.bufferingRanges,A));s(this,"timeSpentActiveLast",A=>jr(this.metrics.general.activeRanges,A));s(this,"timeSpentPlayingInAtLeastLevelRatio",A=>{var B,C,Q,h;const e=this.timeSpentBuffering(),t=this.timeActive(),g=this.bufferingRatios(),n=this.activeRatios(),o=((C=(B=A.video)==null?void 0:B.bitRate)!=null?C:0)+((h=(Q=A.audio)==null?void 0:Q.bitRate)!=null?h:0),a=e/t;return Object.keys(this.metrics.levels).map(d=>parseInt(d,10)).filter(d=>d>=o).reduce((d,u)=>{var p,y;const m=this.getQualityIndex(u).toString();return((p=n.get(m))!=null?p:0)-((y=g.get(m))!=null?y:0)*a+d},0)});s(this,"timeSpentBuffering",()=>ns(this.metrics.general.bufferingRanges));s(this,"timeActive",()=>ns(this.metrics.general.activeRanges));s(this,"getStatistics",()=>{const A=this.timeSpentBuffering(),e=this.timeActive(),t=this.metrics.general.bufferingRanges.length,g=this.activeRatios(),n=e/6e4,o=e>0?A/e:0,a=Math.max(n,1),B=n>0?t/a:0,C=[...g].reduce((k,[N,U])=>k+parseInt(N,10)*U,0),Q=6e4,h=this.timeSpentActiveLast(Q),d=this.timeSpentBufferingLast(Q),u=h>0?d/h:0,m=this.metrics.general.upgradesFromLevel.length+this.metrics.general.downgradesFromLevel.length,p=n>0?m/a:0,y=t>0?A/t:0;return{timeSpentBuffering:A,bufferingEventsCount:t,timeSpentRatio:[...g].reduce((k,[N,U])=>(k[N]=U,k),{}),fatalQosCount:this.fatalQosCount,bufferingRatio:o,bufferingEventsPerMinute:B,averageRenditionIndex:C,bufferingRatioPerMinute:u,renditionChangesPerMinute:p,timePerBufferingEvent:y}});s(this,"onRenditionLevelChanged",A=>{var n,o,a,B,C,Q,h,d,u,m,p,y,k,N;const e=((a=(o=(n=A.from)==null?void 0:n.video)==null?void 0:o.bitRate)!=null?a:0)+((Q=(C=(B=A.from)==null?void 0:B.audio)==null?void 0:C.bitRate)!=null?Q:0),t=((u=(d=(h=A.to)==null?void 0:h.video)==null?void 0:d.bitRate)!=null?u:0)+((y=(p=(m=A.to)==null?void 0:m.audio)==null?void 0:p.bitRate)!=null?y:0);this.logger.info("rendition level changed",{fromLevel:e,toLevel:t}),this.metrics.general.activeRanges.length===0&&this.setActive(),A.from&&A.to&&(e<t?this.metrics.general.upgradesFromLevel.push(Date.now()):this.metrics.general.downgradesFromLevel.push(Date.now()));let g=!1;if(A.from){const U=(k=this.metrics.levels[e])!=null?k:WB();e<t?U.upgradesFromLevel.push(Date.now()):U.downgradesFromLevel.push(Date.now()),Ai(U.activeRanges);const K=U.bufferingRanges[U.bufferingRanges.length-1];g=!!K&&!K.end,Ai(U.bufferingRanges),this.metrics.levels[e]=U}if(A.to){const U=(N=this.metrics.levels[t])!=null?N:WB();Is(U.activeRanges),g&&Is(U.bufferingRanges),this.metrics.levels[t]=U,this.currentLevel=t}});s(this,"onBufferFullness",A=>{this.bufferFullness.push(A),this.metrics.bufferFullness=A,this.bufferFullness.items().length>=this.minBufferFullnessLengthForRegression&&(this.bufferFullnessRegression=this.calculateLinearRegression())});s(this,"onPlaybackState",A=>{switch(this.logger.info("Playback state",{state:A,currentLevel:this.currentLevel}),A){case"playing":this.stopBuffering();break;case"buffering":this.isSuspended||this.startBuffering();break}});s(this,"onVideoDecodeRate",A=>{var t;if(this.metrics.general.decodeRate=A,!this.currentLevel)return;const e=this.metrics.levels[(t=this.currentLevel)!=null?t:0];e&&(e.decodeRate=A)});s(this,"onTargetBufferTime",A=>{this.targetBufferTime=A});s(this,"calculateLinearRegression",()=>Kc(this.bufferFullness.items().map((A,e)=>({x:e,y:A}))));s(this,"stopBuffering",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Ai(A.bufferingRanges)}Ai(this.metrics.general.bufferingRanges)});s(this,"startBuffering",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Is(A.bufferingRanges)}Is(this.metrics.general.bufferingRanges)});s(this,"unsetActive",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Ai(A.activeRanges)}Ai(this.metrics.general.activeRanges)});s(this,"getQualityIndex",A=>{var t,g;if(!this.qualityIndexOrder.length){const o=((g=(t=this.renditionLevelSource)==null?void 0:t.getRenditionLevels())!=null?g:[]).map(a=>{var B,C,Q,h;return((C=(B=a.video)==null?void 0:B.bitRate)!=null?C:0)+((h=(Q=a.audio)==null?void 0:Q.bitRate)!=null?h:0)}).filter(a=>a>0);this.qualityIndexOrder=[...new Set(o)].sort((a,B)=>B-a)}let e=this.qualityIndexOrder.indexOf(A);return e===-1&&(this.qualityIndexOrder.push(A),this.qualityIndexOrder.sort((n,o)=>o-n),e=this.qualityIndexOrder.indexOf(A)),e});this.logger=e,this.emitter=A,this.renditionLevelSource=t}get fatalQosCount(){return this._fatalQosCount}setActive(){if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Is(A.activeRanges)}Is(this.metrics.general.activeRanges)}};s(Da,"create",(A,e,t)=>new Da(A,e,t));let OB=Da;const Sa=class Sa{constructor(A,e){s(this,"renditions",new Map);s(this,"renditionLevels",[]);s(this,"languages",[]);s(this,"emitter");s(this,"subscriptionSource");s(this,"renditionLevelChangeCount",0);s(this,"unload",()=>{this.emitter.off("renditions",this.onRenditions),this.emitter.off("subscription changed",this.onSubscriptionChanged)});s(this,"getRenditionLevels",A=>A?this.createRenditionLevels(A):this.renditionLevels);s(this,"getRenditionLevel",A=>{var a;const e=A!=null?A:this.getCurrentSubscription(),t=A?this.createRenditionLevels(A):this.renditionLevels;if(!e.video)return t.length?t[0]:void 0;const g=e.video.bitRate||Number.MAX_SAFE_INTEGER,n=e.video.width||Number.MAX_SAFE_INTEGER,o=e.video.height||Number.MAX_SAFE_INTEGER;return(a=t.filter(B=>B.video&&e.video?B.video.bitRate<=g&&B.video.width<=n&&B.video.height<=o:!0).pop())!=null?a:t[0]});s(this,"setRenditions",(A,e)=>{this.renditions.set(A,e)});s(this,"getLanguages",()=>this.languages);s(this,"getVideoRendition",(A,e=this.getCurrentSubscription().channelId)=>{const t=this.getRendition(A,e);if(t&&ei(t))return t});s(this,"getAudioRenditions",A=>{const e=this.renditions.get(A);return e==null?void 0:e.filter(g=>ti(g))});s(this,"getVideoRenditions",A=>{const e=this.renditions.get(A);return e==null?void 0:e.filter(g=>ei(g))});s(this,"getAudioRendition",(A,e=this.getCurrentSubscription().channelId)=>{const t=this.getRendition(A,e);if(t&&ti(t))return t});s(this,"getRendition",(A,e=this.getCurrentSubscription().channelId)=>{var t;return(t=this.renditions.get(e))==null?void 0:t.find(g=>g.id===A)});s(this,"getStatistics",()=>{var e,t,g,n,o,a,B,C,Q,h;const A=this.getRenditionLevel();return{videoCodec:(e=A==null?void 0:A.video)==null?void 0:e.codec,audioCodec:(t=A==null?void 0:A.audio)==null?void 0:t.codec,videoRenditionId:(g=A==null?void 0:A.video)==null?void 0:g.id,audioRenditionId:(n=A==null?void 0:A.audio)==null?void 0:n.id,videoWidth:(o=A==null?void 0:A.video)==null?void 0:o.width,videoHeight:(a=A==null?void 0:A.video)==null?void 0:a.height,expectedVideoBitRate:(B=A==null?void 0:A.video)==null?void 0:B.bitRate,expectedAudioBitRate:(C=A==null?void 0:A.audio)==null?void 0:C.bitRate,frameRate:(Q=A==null?void 0:A.video)==null?void 0:Q.frameRate,language:(h=A==null?void 0:A.audio)==null?void 0:h.language,renditionLevelChangeCount:this.renditionLevelChangeCount}});s(this,"onRenditions",A=>{const e=this.subscriptionSource.getCurrentSubscription();this.renditions.set(A.channelId,A.renditions),this.updateRenditionLevels({to:e,from:e})});s(this,"onSubscriptionChanged",A=>{this.updateRenditionLevels(A)});s(this,"updateRenditionLevels",({to:A,from:e})=>{var C;const{channelId:t,initiator:g}=A,n=this.getRenditionLevel(e),o=new Set;((C=this.renditions.get(t))!=null?C:[]).filter(Q=>Q.codec!=="webvtt").forEach(Q=>Q.language?o.add(Q.language):void 0),this.languages=Array.from(o),this.renditionLevels=this.createRenditionLevels(A);const B=this.getRenditionLevel(A);gs(n,B)||(this.renditionLevelChangeCount++,this.emitter.emit("rendition level changed",{to:B,from:n,reason:g?"manual":"abr"}))});s(this,"createRenditionLevels",A=>{var Q;const{video:e,audio:t,channelId:g}=A,n=(Q=this.renditions.get(g))!=null?Q:[],o=n.filter(ei).filter(h=>e&&h.codec===e.codec),a=n.filter(ti).filter(h=>t&&h.codec===t.codec&&h.language===t.language),B=Math.max(o.length,a.length),C=[];for(let h=0;h<B;h++){const d=o[Math.min(o.length-1,h)],u=a[Math.min(a.length-1,h)];C.push({audio:u,video:d})}return C});s(this,"getCurrentSubscription",()=>this.subscriptionSource.getCurrentSubscription());this.subscriptionSource=e,this.emitter=A,this.emitter.on("renditions",this.onRenditions),this.emitter.on("subscription changed",this.onSubscriptionChanged)}};s(Sa,"create",(A,e)=>new Sa(A,e));let VB=Sa;const Lg=i=>JSON.parse(JSON.stringify(i)),Fm=1e4,pa=class pa{constructor(A,e,t){s(this,"logger");s(this,"timers",new JA);s(this,"emitter");s(this,"targetSubscription");s(this,"currentSubscription");s(this,"_isSwitchingSubscription",!1);s(this,"pendingSubscriptionTimeoutId");s(this,"burstMs",0);s(this,"unload",()=>{this.logger.debug("Unloading module..."),this.timers.unload(),this.emitter.off("subscription changed",this.onSubscriptionChanged),this.logger.debug("Unloaded module")});s(this,"isSwitchingSubscription",()=>this._isSwitchingSubscription);s(this,"getTargetSubscription",()=>this.targetSubscription);s(this,"getCurrentSubscription",()=>this.currentSubscription);s(this,"enableBurst",A=>{this.burstMs=A});s(this,"setSize",A=>{this.targetSubscription.video.width=A.width,this.targetSubscription.video.height=A.height,this.scheduleSubscriptionChange()});s(this,"setVideoConstraint",A=>{this.targetSubscription.video=A,this.scheduleSubscriptionChange()});s(this,"setAudioConstraint",A=>{this.targetSubscription.audio=A,this.scheduleSubscriptionChange()});s(this,"setVideoBitRate",A=>{this.targetSubscription.video.bitRate=A,this.scheduleSubscriptionChange()});s(this,"setAudioBitRate",A=>{this.targetSubscription.audio.bitRate=A,this.scheduleSubscriptionChange()});s(this,"setChannelId",A=>{this.targetSubscription.channelId=A,this.scheduleSubscriptionChange()});s(this,"setLanguage",A=>{this.targetSubscription.audio.language=A,this.scheduleSubscriptionChange()});s(this,"setVideoCodec",A=>{this.targetSubscription.video.codec=A,this.scheduleSubscriptionChange()});s(this,"setAudioCodec",A=>{this.targetSubscription.audio.codec=A,this.scheduleSubscriptionChange()});s(this,"setBurst",A=>{A?this.targetSubscription.burstMs=A:delete this.targetSubscription.burstMs});s(this,"isNewSubscription",()=>{const A=["burstMs","meta","initiator","channelGroupId"];return!gs(Xr(this.currentSubscription,A),Xr(this.targetSubscription,A))});s(this,"onSubscriptionChanged",({to:A,reset:e})=>{this.logger.debug("onSubscriptionChanged",{to:A,reset:e}),e?this.targetSubscription=Lg(this.currentSubscription):this.currentSubscription=Lg(A),this._isSwitchingSubscription=this.isNewSubscription()});s(this,"scheduleSubscriptionChange",()=>{this.targetSubscription=Lg(this.targetSubscription),this._isSwitchingSubscription=this.isNewSubscription();const A=this.currentSubscription.channelId,e=this.targetSubscription.channelId,t=A!==e;this._isSwitchingSubscription&&(t&&this.burstMs?this.setBurst(this.burstMs):this.setBurst(0),this.pendingSubscriptionTimeoutId&&(this.timers.clearTimeout(this.pendingSubscriptionTimeoutId),this.pendingSubscriptionTimeoutId=void 0),t&&this.timers.setTimeout(()=>{this.currentSubscription.channelId===A&&this.targetSubscription.channelId===e&&(this.logger.warn("Channel switch timeout",e),this.targetSubscription=Lg(this.currentSubscription),this.emitter.emit("channel switch timeout",e))},Fm),this.pendingSubscriptionTimeoutId=this.timers.setTimeout(()=>this.emitter.emit("send signal",{type:"subscribe",subscription:this.getTargetSubscription()}),0))});this.logger=A,this.targetSubscription=e,this.currentSubscription=Lg(e),this.emitter=t,this.emitter.on("subscription changed",this.onSubscriptionChanged)}};s(pa,"create",(A,e,t)=>new pa(A,t,e));let ZB=pa;const JQ=5e3,km=()=>vr()||lc(),Rm=()=>km()?100:0,MQ=i=>A=>A>i,po={seek:{toleranceMs:200,toleranceMaxMs:2500,toleranceMultiplierStep:1,backoffEveryN:2,cooldownMs:1e3,timeoutMs:5e3,aheadToleranceMs:150,keyframeSearchBeforeMs:50,keyframeSearchAfterMs:100},timeshift:{enabled:!1,toleranceMs:50,toleranceMaxMs:600,backoffEveryN:3},playbackRate:{enabled:!1,startDiff:60,stopDiff:40,maxDiff:300,speed:.02,cooldownMs:2e3},backoff:{enabled:!0,decayEnabled:!0,decayCooldownMultiplier:3,decayCheckInterval:15e3}},ya=class ya{constructor(A,e,t,g,n){s(this,"emitter");s(this,"logger");s(this,"playbackSource");s(this,"bufferSource");s(this,"keyframeTimestamps",new P(10));s(this,"lastSeekTime",Date.now());s(this,"lastAdjustmentTime",Date.now());s(this,"lastDecayCheckTime",Date.now());s(this,"config");s(this,"state");s(this,"allowTimeshiftOnAudio",!1);s(this,"syncInfoToleranceMaxMs",150);s(this,"syncInfoToleranceStep",20);s(this,"seekOvershoot",Rm());s(this,"timers",JA.create());s(this,"rtt",0);s(this,"channelSyncInfo",new Map);s(this,"seekAdjustmentCount",0);s(this,"timeshiftAdjustmentCount",0);s(this,"syncInfoCorrectionCount",0);s(this,"playbackRateAdjustmentCount",0);s(this,"lastPlaybackRateChangeTime",0);s(this,"seekAdjustmentTimestamps",[]);s(this,"timeshiftAdjustmentTimestamps",[]);s(this,"_driftSamplesToAverage",5);s(this,"driftSamples",new P(this._driftSamplesToAverage));s(this,"timestampOffset");s(this,"currentChannelId");s(this,"highestSeenTimestamps",new Map);s(this,"isSuspended",!1);s(this,"isSyncAdjustmentActivated",!1);s(this,"queuedTimeshift",!1);s(this,"load",()=>{this.timers.setInterval(this.onSync,100)});s(this,"unload",()=>{this.logger.debug("Unloading module..."),this.emitter.off("rtt",this.updateRtt),this.timers.unload(),this.logger.debug("Unloaded module")});s(this,"suspend",()=>{this.isSuspended=!0});s(this,"unsuspend",()=>{this.resetSyncState(),this.isSuspended=!1});s(this,"deactivateSyncAdjustments",()=>{this.isSyncAdjustmentActivated=!1});s(this,"activateSyncAdjustments",()=>{this.tryApplySyncInfo(0),this.lastSeekTime=Date.now(),this.isSyncAdjustmentActivated=!0});s(this,"reset",()=>{this.logger.info("Reset sync state"),this.currentChannelId=void 0,this.timestampOffset=void 0,this.resetSyncState(),this.highestSeenTimestamps.clear()});s(this,"getTimeshiftOffset",()=>{var A;return(A=this.timestampOffset)!=null?A:0});s(this,"getCurrentChannelId",()=>this.currentChannelId);s(this,"resetSyncState",()=>{this.state.seekToleranceMultiplier=1,this.state.timeshiftToleranceMultiplier=1,this.seekAdjustmentTimestamps=[],this.timeshiftAdjustmentTimestamps=[],this.driftSamples.clear()});s(this,"getEffectiveSeekToleranceMs",()=>this.config.timeshift.enabled?this.config.seek.toleranceMs*2:this.config.seek.toleranceMs);s(this,"getLiveEdgeTime",A=>{const e=this.channelSyncInfo.get(A);if(!e)return;const t=Date.now()-e.localTimestamp;return e.timestamp+t});s(this,"getLiveEdgeTimeLatencyAdjusted",A=>{const e=this.getLiveEdgeTime(A);if(e)return e+this.rtt/2});s(this,"getWallclockTime",A=>{const e=this.channelSyncInfo.get(A);if(!e)return;const t=Date.now()-e.localTimestamp;return e.wallclockTime+t});s(this,"getWallclockTimeLatencyAdjusted",A=>{const e=this.getWallclockTime(A);if(e)return e+this.rtt/2});s(this,"processSample",A=>{var g;if(!A.channelId)throw new Error("Sample must be assigned to a channel");this.currentChannelId||(this.currentChannelId=A.channelId),this.timestampOffset||(this.timestampOffset=A.timestamp/A.timescale*1e3-JQ);const e=A.type==="video"&&A.isSync;if(this.currentChannelId!==A.channelId){let n=Number.MAX_SAFE_INTEGER;console.assert(this.highestSeenTimestamps.size!==0,"no known timestamps"),this.highestSeenTimestamps.forEach(a=>{n=Math.min(n,a)});const o=A.timestamp/A.timescale*1e3;this.currentChannelId=A.channelId,this.timestampOffset=o-n}else(e||this.allowTimeshiftOnAudio)&&this.tryTimeshiftSync();const t=this.timestampOffset*A.timescale/1e3;return A.timestamp-=t,e&&this.keyframeTimestamps.push(A.timestamp/A.timescale*1e3),this.highestSeenTimestamps.set(A.type,Math.max((g=this.highestSeenTimestamps.get(A.type))!=null?g:0,A.timestamp/A.timescale*1e3)),A});s(this,"processFragment",(A,e)=>{var o;this.currentChannelId||(this.currentChannelId=A);const t=e.mediaType();if(!t)throw new Error("Fragment must have a media type");this.timestampOffset||(this.timestampOffset=e.baseMediaDecodeTime()/e.timescale()*1e3-JQ);const g=e.mediaType()==="video"&&e.startsWithKeyframe();this.currentChannelId!==A?(console.assert(this.highestSeenTimestamps.size!==0,"no known timestamps"),this.highestSeenTimestamps.forEach(a=>{}),this.currentChannelId=A):(g||this.allowTimeshiftOnAudio)&&this.tryTimeshiftSync();const n=this.timestampOffset*e.timescale()/1e3;return e.updateBaseMediaDecodeTime(e.baseMediaDecodeTime()-n),g&&this.keyframeTimestamps.push(e.baseMediaDecodeTime()/e.timescale()*1e3),this.highestSeenTimestamps.set(t,Math.max((o=this.highestSeenTimestamps.get(t))!=null?o:0,e.baseMediaDecodeTime()/e.timescale()*1e3)),e});s(this,"forceSeek",()=>{this.logger.debug("Forcing seek",{amount:this.serverCurrentTime-this.playbackSource.currentTime}),this.playbackSource.currentTime=this.serverCurrentTime});s(this,"forceTimeshift",()=>{this.queuedTimeshift=!0});s(this,"setPlaybackRateAdjustmentEnabled",A=>{this.config.playbackRate.enabled=A});s(this,"getStatistics",()=>{const A=this.driftSamples.items(),e=A.length>0?we(A.map(Math.abs)):0;return{drift:this.drift,seekAdjustmentCount:this.seekAdjustmentCount,timeshiftAdjustmentCount:this.timeshiftAdjustmentCount,seekTime:this.playbackSource.seekTime,totalSeekTime:this.playbackSource.totalSeekTime,seekToleranceMultiplier:this.state.seekToleranceMultiplier,currentSeekToleranceMs:this.currentSeekToleranceMs(),currentAheadToleranceMs:this.currentAheadToleranceMs(),isPlaybackRateAdjustmentEnabled:this.config.playbackRate.enabled,playbackRate:this.playbackSource.playbackRate||1,playbackRateAdjustmentCount:this.playbackRateAdjustmentCount,averageDrift:e}});s(this,"updateRtt",A=>{this.rtt=A});s(this,"isPlaybackSourceReadyToSeek",()=>!this.isSeeking()&&this.isSeekCooldownExpired()&&this.isSyncAdjustmentActivated);s(this,"isSeeking",()=>this.playbackSource.isSeeking?!this.isSeekTimeoutExpired():!1);s(this,"isAllowedToSync",()=>this.isPlaybackSourceReadyToSeek()&&!!this.currentChannelId&&!this.isSuspended&&!this.playbackSource.isPaused);s(this,"isSeekCooldownExpired",()=>Date.now()-this.lastSeekTime>this.config.seek.cooldownMs);s(this,"isSeekTimeoutExpired",()=>Date.now()-this.lastSeekTime>this.config.seek.timeoutMs);s(this,"currentTimeshiftToleranceMs",()=>Math.min(this.config.timeshift.toleranceMs*this.state.timeshiftToleranceMultiplier,this.config.timeshift.toleranceMaxMs));s(this,"currentSeekToleranceMs",()=>Math.min(this.state.seekToleranceMultiplier*this.getEffectiveSeekToleranceMs(),this.config.seek.toleranceMaxMs));s(this,"currentAheadToleranceMs",()=>{const A=Math.max(this.config.seek.aheadToleranceMs*this.state.seekToleranceMultiplier,400),e=this.playbackSource.seekTime>500?A:this.config.seek.aheadToleranceMs;return Math.min(e,this.bufferSource.getTargetBufferTime()/2)});s(this,"tryDecayMultipliers",()=>{if(!this.config.backoff.decayEnabled)return;const A=Date.now();if(A-this.lastDecayCheckTime<this.config.backoff.decayCheckInterval)return;this.lastDecayCheckTime=A;const e=this.seekAdjustmentTimestamps.length>0?Math.max(...this.seekAdjustmentTimestamps):0,t=this.timeshiftAdjustmentTimestamps.length>0?Math.max(...this.timeshiftAdjustmentTimestamps):0,g=Math.max(e,t,this.lastAdjustmentTime),n=A-g,o=Math.max(this.state.seekToleranceMultiplier,this.state.timeshiftToleranceMultiplier),B=this.config.seek.timeoutMs*this.config.backoff.decayCooldownMultiplier*o;if(n<B)return;let C=!1;if(this.state.seekToleranceMultiplier>1){const Q=Math.max(1,this.state.seekToleranceMultiplier-.5);Q!==this.state.seekToleranceMultiplier&&(this.logger.info("Decaying seek tolerance multiplier",{from:this.state.seekToleranceMultiplier,to:Q,timeSinceLastAdjustment:n,requiredStabilityMs:B}),this.state.seekToleranceMultiplier=Q,C=!0)}if(this.state.timeshiftToleranceMultiplier>1){const Q=Math.max(1,this.state.timeshiftToleranceMultiplier-.5);Q!==this.state.timeshiftToleranceMultiplier&&(this.logger.info("Decaying timeshift tolerance multiplier",{from:this.state.timeshiftToleranceMultiplier,to:Q,timeSinceLastAdjustment:n,requiredStabilityMs:B}),this.state.timeshiftToleranceMultiplier=Q,C=!0)}if(C){const Q=A-B*2;this.seekAdjustmentTimestamps=this.seekAdjustmentTimestamps.filter(h=>h>Q),this.timeshiftAdjustmentTimestamps=this.timeshiftAdjustmentTimestamps.filter(h=>h>Q)}});s(this,"applyBackoff",()=>{if(this.config.backoff.enabled&&(this.lastAdjustmentTime=Date.now(),this.seekAdjustmentCount>0&&this.seekAdjustmentCount%this.config.seek.backoffEveryN===0)){const A=this.state.seekToleranceMultiplier,e=this.config.seek.toleranceMaxMs/this.getEffectiveSeekToleranceMs();this.state.seekToleranceMultiplier=Math.min(this.state.seekToleranceMultiplier+this.config.seek.toleranceMultiplierStep,e),A!==this.state.seekToleranceMultiplier&&this.logger.info("Backoff: Increasing seek tolerance multiplier",{from:A,to:this.state.seekToleranceMultiplier,currentSeekToleranceMs:this.currentSeekToleranceMs()})}});s(this,"tryPlaybackRateSync",A=>{if(!this.config.playbackRate.enabled)return!1;const e=this.playbackSource.playbackRate!==1,t=Math.abs(A),g=e&&t<this.config.playbackRate.stopDiff,n=!e&&t>=this.config.playbackRate.startDiff;if(t>this.config.playbackRate.maxDiff)return e&&(this.playbackSource.playbackRate=1,this.lastPlaybackRateChangeTime=Date.now()),!1;const o=Date.now(),a=o-this.lastPlaybackRateChangeTime>=this.config.playbackRate.cooldownMs;if(g&&a)return this.playbackSource.playbackRate=1,this.lastPlaybackRateChangeTime=o,this.logger.info("Resetting playback rate to 1",{drift:A}),!0;if(n&&a){const B=A>0?1+this.config.playbackRate.speed:1-this.config.playbackRate.speed;return this.playbackSource.playbackRate=B,this.lastPlaybackRateChangeTime=o,this.playbackRateAdjustmentCount++,this.logger.info("Adjusting playback rate",{drift:A,targetRate:B}),!0}if(e&&t>=this.config.playbackRate.stopDiff&&t<=this.config.playbackRate.maxDiff){const B=A>0?1+this.config.playbackRate.speed:1-this.config.playbackRate.speed;return this.playbackSource.playbackRate!==B&&a&&(this.playbackSource.playbackRate=B,this.lastPlaybackRateChangeTime=o,this.logger.info("Changing playback rate direction",{drift:A,targetRate:B})),!0}return!e&&t<this.config.playbackRate.startDiff?!0:e});s(this,"tryTimeshiftSync",()=>{var n;if(!this.config.timeshift.enabled||!this.isAllowedToSync()||this.playbackSource.playbackRate!==1)return;const A=(n=this.drift)!=null?n:0;this.driftSamples.push(A);const e=we(this.driftSamples.items());if(this.queuedTimeshift&&e>0){this.queuedTimeshift=!1,this.applyTimeshift(e);return}if(e>=this.getEffectiveSeekToleranceMs()||e<this.currentTimeshiftToleranceMs())return;const t=Date.now()-this.config.seek.timeoutMs*this.state.timeshiftToleranceMultiplier,g=this.timeshiftAdjustmentTimestamps.filter(MQ(t)).length;if(g&&this.state.timeshiftToleranceMultiplier>2){this.logger.info("Too many timeshifts within sliding window",{timeshiftCooldownThreshold:t,recentTimeshiftCount:g});return}this.applyTimeshift(e)});s(this,"applySeek",A=>{const e=this.playbackSource.seekTime,t=this.playbackSource.currentTime+A,g=this.findKeyframeCloseToTimestamp(t);if(!g&&!this.keyframeTimestamps.isEmpty())return;const n=g&&g>t+this.seekOvershoot?g:t+this.seekOvershoot;this.logger.info("Adjusting for drift using seek",{drift:A,currentTime:this.playbackSource.currentTime,targetCurrentTime:n,seekTime:e,rtt:this.rtt,seekToleranceMultiplier:this.state.seekToleranceMultiplier}),this.lastSeekTime=Date.now(),this.driftSamples.clear(),this.seekAdjustmentTimestamps.push(this.lastSeekTime),this.seekAdjustmentCount++,this.playbackSource.currentTime=n+Math.min(e,this.bufferSource.getTargetBufferTime()),this.applyBackoff()});s(this,"applyTimeshift",A=>{var g;const e=(g=A!=null?A:this.drift)!=null?g:0;if(!this.timestampOffset)return;const t=e;if(this.logger.info("Adjusting for drift using timeshift",{drift:e,syncAmount:t,currentTime:this.playbackSource.currentTime,rtt:this.rtt,timeshiftToleranceMultiplier:this.state.timeshiftToleranceMultiplier}),this.timestampOffset+=t,this.lastSeekTime=Date.now(),this.lastAdjustmentTime=Date.now(),!this.playbackSource.isPaused&&(this.driftSamples.clear(),this.timeshiftAdjustmentTimestamps.push(this.lastSeekTime),this.timeshiftAdjustmentCount++,this.config.backoff.enabled&&this.timeshiftAdjustmentCount>0&&this.timeshiftAdjustmentCount%this.config.timeshift.backoffEveryN===0)){const n=this.state.timeshiftToleranceMultiplier,o=this.config.timeshift.toleranceMaxMs/this.config.timeshift.toleranceMs;this.state.timeshiftToleranceMultiplier=Math.min(this.state.timeshiftToleranceMultiplier+1,o),n!==this.state.timeshiftToleranceMultiplier&&this.logger.info("Backoff: Increasing timeshift tolerance multiplier",{from:n,to:this.state.timeshiftToleranceMultiplier,currentTimeshiftToleranceMs:this.currentTimeshiftToleranceMs()})}});s(this,"onSync",()=>{var n;if(this.tryDecayMultipliers(),!this.isAllowedToSync())return;const A=(n=this.drift)!=null?n:0;if(this.driftSamples.push(A),this.driftSamples.items().length<this.driftSamplesToAverage&&Math.abs(A)<2e3)return;const e=we(this.driftSamples.items());if(this.tryPlaybackRateSync(e)||e<0&&-e<this.currentAheadToleranceMs()||e>0&&e<this.currentSeekToleranceMs()||Math.abs(e)<1||!this.isSeekCooldownExpired())return;const t=Date.now()-this.config.seek.timeoutMs*this.state.seekToleranceMultiplier,g=this.seekAdjustmentTimestamps.filter(MQ(t)).length;if(g&&this.state.seekToleranceMultiplier>2){this.logger.info("Too many seek adjustments within sliding window",{seekCooldownThreshold:t,recentSeekCount:g});return}this.applySeek(e)});s(this,"findKeyframeCloseToTimestamp",A=>{const e=this.keyframeTimestamps.items();for(const t of e){const g=t>=A-this.config.seek.keyframeSearchBeforeMs,n=t<=A+this.config.seek.keyframeSearchAfterMs;if(g&&n)return t}});this.logger=e,this.emitter=A,this.playbackSource=t,this.bufferSource=g,this.config={seek:f({},po.seek),timeshift:f({},po.timeshift),playbackRate:f({},po.playbackRate),backoff:f({},po.backoff)},this.config.timeshift.enabled=n,this.state={seekToleranceMultiplier:1,timeshiftToleranceMultiplier:1},typeof window!="undefined"&&window.location.search.includes("playbackRateAdjustmentEnabled")&&(this.config.playbackRate.enabled=!0),this.emitter.on("rtt",this.updateRtt),this.logger.info("SyncModule initialized",{config:this.config})}get driftSamplesToAverage(){return this._driftSamplesToAverage}set driftSamplesToAverage(A){this._driftSamplesToAverage=A,this.driftSamples=new P(A)}updateChannelSyncInfo(A,e){const t=Date.now(),g=this.channelSyncInfo.get(A),n=this.getLiveEdgeTime(A);if(this.isSuspended)return;if(!g||!n){this.logger.info("Initial timing info",{syncInfo:e}),this.channelSyncInfo.set(A,V(f({},e),{localTimestamp:t,timeDifferences:new P(12)}));return}const o=e.wallclockTime-g.wallclockTime,a=e.timestamp-g.timestamp,B=t-g.localTimestamp,C=a-B;if(g.timeDifferences.push(C),this.logger.debug("Timing info",{rtt:this.rtt,channelId:A,syncInfo:e,localTimestamp:t,diffFromEstimated:C,timestampDelta:a,wallclockDelta:o,localWallclockDelta:B}),Math.abs(C)>=Math.max(this.bufferSource.getTargetBufferTime()*2,3e3)){this.logger.info("Resetting sync info",{diffFromEstimated:C}),this.channelSyncInfo.set(A,V(f({},e),{localTimestamp:t,timeDifferences:new P(g.timeDifferences.maxSize+1)})),this.currentChannelId&&this.currentChannelId===A&&(this.reset(),this.emitter.emit("channel reset"));return}g.timeDifferences.items().length<3||this.tryApplySyncInfo(Math.min(this.syncInfoToleranceMaxMs,this.syncInfoCorrectionCount*this.syncInfoToleranceStep))}tryApplySyncInfo(A){const e=this.getCurrentChannelId();if(!e)return;const t=this.channelSyncInfo.get(e);if(!t)return;const g=$t(t.timeDifferences.items());Math.abs(g.average)>A&&(this.logger.info("Adjusting sync info",V(f({},g),{tolerance:A})),t.timestamp+=g.average,this.syncInfoCorrectionCount++,t.timeDifferences.clear())}get serverCurrentTime(){return this.channelCurrentTime-this.getTimeshiftOffset()}get channelCurrentTime(){const A=this.getCurrentChannelId();if(!A)return 0;const e=this.getLiveEdgeTime(A);return e?e-this.bufferSource.getTargetBufferTime():0}get drift(){return this.serverCurrentTime-this.playbackSource.currentTime}};s(ya,"create",(A,e,t,g,n)=>new ya(A,e,t,g,n));let XB=ya;const Gm={enabled:!0,interval:3e4,includeErrors:!0,includeEvents:!0,includeStats:!0,maxRetries:10,maxErrorReports:50,maxEvents:50},jB=(i,A)=>V(f({},A),{type:i,timestamp:new Date().toISOString(),discriminator:"web"}),Fa=class Fa{constructor(A,e,t,g){s(this,"logger");s(this,"timers",new JA);s(this,"emitter");s(this,"options");s(this,"parentContext");s(this,"unsentLines",new P(100));s(this,"retries",0);s(this,"errorCount",0);s(this,"eventCount",0);s(this,"statsCount",0);s(this,"unload",()=>{this.logger.debug("Unloading module..."),window.removeEventListener("error",this.onError),window.removeEventListener("unhandledrejection",this.onRejection),this.timers.unload(),this.emitter.off("error",this.addError),this.emitter.off("visibilitystate",this.onVisibilityChange),this.emitter.off("pagehide",this.onPageHide),this.emitter.off("telemetry event",this.addEvent),this.addStats({isFinal:!0,initiator:"unload"}),this.send("beacon"),this.logger.debug("Unloaded module")});s(this,"load",()=>{window.addEventListener("error",this.onError),window.addEventListener("unhandledrejection",this.onRejection),this.emitter.on("error",this.addError),this.emitter.on("visibilitystate",this.onVisibilityChange),this.emitter.on("pagehide",this.onPageHide),this.emitter.on("telemetry event",this.addEvent),this.timers.setInterval(()=>{this.addStats(),this.send("fetch")},this.options.interval)});s(this,"addStats",({isFinal:A,initiator:e}={isFinal:!1,initiator:"interval"},t={})=>{if(!this.options.includeStats)return;const g=this.parentContext.getStatistics(),n=jB("stats",V(f(f({},t),g),{isFinal:A,initiator:e,count:this.statsCount++}));this.unsentLines.push(n)});s(this,"addEvent",A=>{if(!this.options.includeEvents||this.eventCount>this.options.maxEvents)return;const e=this.parentContext.getStatistics(),t=jB("event",f(f({},e),A));this.eventCount++,this.unsentLines.push(t)});s(this,"getStatistics",()=>({errorCount:this.errorCount}));s(this,"send",A=>c(this,null,function*(){if(this.options.enabled&&!(this.retries>=this.options.maxRetries)&&!this.unsentLines.isEmpty()){this.logger.debug("Sending telemetry",{lines:this.unsentLines.items()});try{const e=this.unsentLines.items().map(t=>JSON.stringify(t)).reverse().join(`
50
- `);A==="beacon"?navigator.sendBeacon(this.options.url,e):this.parentContext.connectionState==="connected"?this.emitter.emit("send signal",{type:"telemetry",body:e}):yield zC(new URL(this.options.url),{body:e,headers:{"Content-Type":"text/plain"}}),this.retries=0,this.unsentLines.clear()}catch(e){this.retries++}}}));s(this,"onVisibilityChange",A=>{A==="hidden"&&(this.addStats({isFinal:!0,initiator:"visibilitychange"}),this.send("beacon"))});s(this,"onPageHide",A=>{this.addStats({isFinal:!0,initiator:"pagehide"},{persisted:A.persisted}),this.send("beacon")});s(this,"onRejection",A=>this.addError(A.reason));s(this,"onError",A=>this.addError(A.error));s(this,"addError",A=>{const{includeErrors:e,maxErrorReports:t}=this.options;if(e&&A instanceof x){if(this.errorCount++,this.errorCount>t)return;const g=this.parentContext.getStatistics();this.unsentLines.push(jB("error",f(f({},g),A.toStringifiable())))}});this.logger=A,this.emitter=e,this.options=f(f({},Gm),t),this.parentContext=g}};s(Fa,"create",(A,e,t,g)=>new Fa(A,e,t,g));let yo=Fa;const ka=class ka{constructor(A,e,t){s(this,"logger");s(this,"element");s(this,"documentState");s(this,"timers",new JA);s(this,"unload",()=>{this.timers.unload()});s(this,"unpause",()=>{this.element.userHasProvidedInput&&this.element.isPaused&&this.documentState.isVisible&&this.documentState.isOnline&&(this.logger.debug("Unpause video"),this.element.tryPlay())});this.logger=A,this.element=e,this.documentState=t,this.timers.setInterval(this.unpause,100)}};s(ka,"create",(A,e,t)=>new ka(A,e,t));let Fo=ka;const Um=["minBufferTime","maxBufferTime","burstEnabled","sizeBasedResolutionCapEnabled","separateVideoSocketEnabled","webcodecsHardwareAcceleration","offscreenCanvasEnabled","videoCodecs"];function bm(i){return Um.includes(i)}class Nm{constructor(A){s(this,"options");s(this,"overrides",new Map);this.options=A}getOptions(){return this.options}addOverrides(A,e){this.overrides.set(A,e)}set(A,e){this.options[A]=e}get(A,e){var t;if(e&&bm(A)){const g=(t=this.overrides.get(e))==null?void 0:t[A];if(typeof g!="undefined")return g}return this.options[A]}getOverride(A,e){var t;return(t=this.overrides.get(e))==null?void 0:t[A]}}const Lm=["mse","wasm"],Jm=i=>i!=null?i:Lm,Mm=i=>{if(!i)return!1;const A=i.headers&&Object.keys(i.headers).length>0,e=i.queryParams&&Object.keys(i.queryParams).length>0;return!!(A||e)},vm=(i,A,e)=>{if(Mm(e))return"mse";const t=Jm(i);for(const g of t)switch(g){case"mse":if(A)return"mse";break;case"webcodecs":if(typeof VideoDecoder!="undefined")return"webcodecs";break;case"wasm":return"wasm"}return"wasm"},Hm=6,qm=i=>{let A=[i],e=0,t=0,g=!1;const n=(a,B)=>{var y,k,N;a.flags&&bg(a.flags)&&(e=(y=a.compositionTimeOffset)!=null?y:0),a.timestamp+=e,a.compositionTimeOffset=((k=a.compositionTimeOffset)!=null?k:0)-e;const C=a.timestamp/a.timescale,h=B.flags&&bg(B.flags)?(N=B.compositionTimeOffset)!=null?N:0:e,u=(B.timestamp+h)/B.timescale,m=Math.max(0,Math.round((u-C)*a.timescale));return m>0&&(t=m),V(f({},a),{duration:m>0?m:t})};return(a,B=!1)=>{if(a.flags&&bg(a.flags)&&B&&(g=!g),!(B&&A.length<Hm&&g)&&A.length>0){g=!1;let Q=a;for(let d=A.length-1;d>0;d--){const u=A[d];if(!u||!Q)break;u.timestamp>=Q.timestamp?A.splice(d,1):Q=u}const h=A.map((d,u)=>n(d,A[u+1]||a));return A=[a],h}return A.push(a),[]}},Km=(i,A,e)=>{if(ei(A))return f(V(f({},i),{type:"video",codec:A.codec,isSync:bg(i.flags),data:i.payload,duration:0,width:A.width,height:A.height}),e);if(A.codec==="webvtt")throw new Error("WebVTT is not supported");return V(f({},i),{type:"audio",channels:A.channels,sampleRate:A.sampleRate,codec:A.codec,language:A.language,isSync:bg(i.flags),data:i.payload,duration:0})},vQ=(i,A)=>i&&typeof i=="object"&&A in i,HQ=i=>!(typeof i!="object"||!vQ(i,"channelId")||typeof i.channelId!="string"||!vQ(i,"url")||typeof i.url!="string"||i.channelId.length===0||i.url.length===0),Tm=i=>{if(!HQ(i))throw new x("Invalid options",{isFatal:!0,code:"invalid_options"});const A=f({},i);return Object.keys(A).forEach(e=>{const t=A;typeof t[e]=="undefined"&&delete t[e]}),A},Ym=i=>{if(typeof i!="object"||i===null)throw new Error("not an object");if(!("video"in i))throw new Error("missing video in subscription");if(!("audio"in i))throw new Error("missing audio in subscription");if(!("channelId"in i))throw new Error("missing channelId");return!0},qQ=i=>{switch(i){case"opus":return"opus";case"aac":return"mp4a.40.2";case"mp3":return"mp3";default:{const A=i;throw new Error(`Unsupported audio codec: ${A}`)}}};class Pm{constructor(A){s(this,"cache",new Map);s(this,"inFlight",new Map);s(this,"checkVideoSupport",A=>c(this,null,function*(){var n;if(typeof VideoDecoder=="undefined")return!1;const e=VideoDecoder.isConfigSupported;if(typeof e!="function")return!0;const t=(n=A.codecString)!=null?n:A.codec==="av1"?"av01.0.08M.08":"avc1.42E01E",g=`video|${t}|${A.width}x${A.height}`;return this.check(g,()=>e({codec:t,optimizeForLatency:!0,codedWidth:A.width,codedHeight:A.height}),!0,{message:"Failed to check WebCodecs rendition support. Falling back to optimistic support check.",codec:t,renditionId:A.id})}));s(this,"checkAudioSupport",A=>c(this,null,function*(){var o;if(typeof AudioDecoder=="undefined")return!1;const e=AudioDecoder.isConfigSupported;if(typeof e!="function")return!0;const t=(o=A.codecString)!=null?o:qQ(A.codec),g=`audio|${t}|${A.sampleRate}|${A.channels}`,n=A.codec==="aac"?LC(A.channels,A.sampleRate):A.codec==="opus"?OC(A.channels,A.sampleRate):void 0;return this.check(g,()=>e({codec:t,sampleRate:A.sampleRate,numberOfChannels:A.channels,description:n}),!1,{message:"Failed to check WebCodecs audio rendition support. Treating rendition as unsupported.",codec:t,renditionId:A.id})}));s(this,"check",(A,e,t,g)=>{const n=this.cache.get(A);if(n!==void 0)return Promise.resolve(n);const o=this.inFlight.get(A);if(o)return o;const a=Promise.resolve().then(e).then(({supported:B})=>(this.cache.set(A,B),B)).catch(B=>(this.logger.warn(g.message,{codec:g.codec,renditionId:g.renditionId,error:B}),this.cache.set(A,t),t)).finally(()=>{this.inFlight.delete(A)});return this.inFlight.set(A,a),a});this.logger=A}}const ct=class ct extends ie{constructor(e){var le;super();s(this,"pictureInPicture");s(this,"drm");s(this,"browser",qa());s(this,"options");s(this,"element");s(this,"playbackSource");s(this,"emitter",new ie);s(this,"logger");s(this,"modules");s(this,"clientIp");s(this,"sessionId");s(this,"clientId",$r());s(this,"_channels",[]);s(this,"createdAt",Date.now());s(this,"offscreenCanvasElement");s(this,"webCodecsRenditionSupport");s(this,"hasCalledConnect",!1);s(this,"latestEmittedLanguages",[]);s(this,"wakeLock");s(this,"pool",new _e(ct.MAX_POOL_SIZE));s(this,"userAgentInformation",new Zc);s(this,"encryptedMediaExtensions");r(this,Zi,0);r(this,oe,[]);s(this,"sampleProcessingSesssions",new Map);s(this,"sizes",new Map);s(this,"isSuspended",!0);s(this,"disconnectTimeout");s(this,"offscreenSubtitleInterval");r(this,Xi);s(this,"attach",e=>{var t;(t=this.wakeLock)==null||t.attach(e),e.appendChild(this.element)});s(this,"setElement",e=>{this.element!==e&&(this.element=e,this.modules.constraintCap.setElement(e))});s(this,"getOptions",()=>this.options.getOptions());s(this,"getThumbnailUrl",()=>{let e=this.options.get("edgeUrl")||this.options.get("url");e=e.replace("wss://","https://"),e=e.replace("ws://","http://"),e=e.endsWith("/")?e.slice(0,-1):e;const t=window.devicePixelRatio||1,g=Math.round(window.innerWidth*t),n=Math.round(window.innerHeight*t),o=this.options.get("authenticationToken"),a=o?`&auth.token=${o}`:"";return`${e}/api/thumbnail?channelId=${this.channelId}${a}&width=${g}&height=${n}`});s(this,"updateAuthenticationToken",e=>{this.logger.debug("Got new auth token",{token:e}),this.options.set("authenticationToken",e),this.emitter.emit("send signal",{type:"refresh auth",token:e})});s(this,"connect",()=>{this.hasCalledConnect||(this.play(),this._connect())});s(this,"_connect",()=>{var e,t;this.hasCalledConnect||(this.hasCalledConnect=!0,Object.values(this.modules).forEach(g=>{g&&"load"in g&&g.load()}),this.unsuspend(),this.playbackSource instanceof BB&&((t=(e=this.playbackSource).load)==null||t.call(e)),this.modules.connection.connect())});s(this,"getCastOptions",()=>({url:this.options.get("url"),channelId:this.options.get("channelId"),channelGroupId:this.options.get("channelGroupId"),authenticationToken:this.options.get("authenticationToken"),language:this.options.get("language"),logLevel:this.options.get("logLevel"),minBufferTime:this.options.get("minBufferTime"),tags:this.options.get("tags"),ownerSessionId:this.sessionId,edgeUrl:this.options.get("edgeUrl"),media:this.options.get("media"),drm:this.options.get("drm")}));s(this,"onConnectInfo",e=>c(this,null,function*(){var C;this.sessionId=$r();const t=this.modules.subscription.getTargetSubscription(),g=e.channels.find(Q=>Q.channelId===t.channelId);if(this.emitter.emit("connect info",e),"timeshift"in e&&e.timeshift?(e.timeshift,this._channels=e.channels.map(Q=>V(f({},Q),{timeshift:e.timeshift})),this.emit("timeshift info",e.timeshift)):this._channels=e.channels,this.updateTextTracks((C=g==null?void 0:g.renditions)!=null?C:[]),!this.textTrack&&this.options.get("textTrack")&&(this.textTrack=this.options.get("textTrack")),yield Promise.all(e.channels.map(Q=>c(this,null,function*(){Q.overrides&&this.options.addOverrides(Q.channelId,Q.overrides),Q.renditions=yield this.filterRenditions(Q.renditions),this.modules.renditions.setRenditions(Q.channelId,Q.renditions)}))),!g)throw lC("external");const n=this.options.getOverride("sizeBasedResolutionCapEnabled",this.channelId);n!==void 0&&(this.modules.constraintCap.sizeBasedResolutionCapEnabled=n);const o=this.options.getOverride("minBufferTime",this.channelId),a=this.options.getOverride("maxBufferTime",this.channelId);if((o||a)&&(this.modules.bufferTime.updateConfig({minBufferTime:this.options.get("minBufferTime",this.channelId),maxBufferTime:this.options.get("maxBufferTime",this.channelId)}),this.targetBufferTime=this.options.get("minBufferTime",this.channelId)),this.options.get("burstEnabled",this.channelId)&&this.modules.subscription.enableBurst(this.targetBufferTime),this.emit("is live",g.isLive),!g.isLive)throw new Error("Waiting for channel to go live");this.patchSubscription(g,this.modules.connection.estimatedBandwidth),yield this.initializeDecodingModule(),this.resetModules(),this.emit("rendition levels",this.modules.renditions.getRenditionLevels()),this.emit("channels",this.channels),this.emitLanguagesIfChanged(),this.sampleProcessingSesssions.clear();const B=this.options.get("burstEnabled",this.channelId);return{video:this.targetSubscription.video,audio:this.targetSubscription.audio,burstMs:B?this.targetBufferTime:void 0,sessionId:this.sessionId,clientId:this.clientId,channelId:this.channelId,channelGroupId:this.options.get("channelGroupId"),authToken:this.options.get("authenticationToken"),textTrack:this.textTrack}}));s(this,"emitLanguagesIfChanged",()=>{const e=this.modules.renditions.getLanguages(),t=this.latestEmittedLanguages;e.length==t.length&&e.every(n=>t.includes(n))||(this.logger.debug("Emitting new languages",{currentLanguages:e}),this.latestEmittedLanguages=e,this.emit("languages",this.latestEmittedLanguages))});s(this,"updateTextTracks",e=>{const t=e.filter(g=>g.codec==="webvtt");t.forEach(g=>{if(!I(this,oe).find(o=>o.language===g.language)){if(this.modules.canvasModule){const o=this.modules.canvasModule.textTracks.addTextTrack(g.kind,g.label||g.language||"",g.language||"");I(this,oe).push(o)}else if(this.mediaElement instanceof HTMLVideoElement){const o=this.mediaElement.addTextTrack(g.kind,g.label||g.language,g.language);I(this,oe).push(o)}}});for(const g of I(this,oe))t.find(o=>o.language===g.language)?g.mode==="disabled"&&(g.mode="hidden"):g.mode="disabled";this.emit("text tracks",this.textTracks)});s(this,"cleanupTextTracks",(e=this.currentTime-2e4)=>{I(this,oe).forEach(t=>{if(t.cues)for(const g of t.cues)g.endTime*1e3<e-2e3&&t.removeCue(g)})});s(this,"filterRenditions",e=>c(this,null,function*(){const t=yield Promise.all(e.map(a=>c(this,null,function*(){var Q;if(ti(a))return this.willUseMediaSource()&&!((Q=is())!=null&&Q.isTypeSupported(mt(a)))?!1:this.willUseMediaSource()||a.codec==="opus"?!0:this.isWebCodecsAudioAvailable(this.channelId)?this.webCodecsRenditionSupport.checkAudioSupport(a):!1;if(!ei(a)||!this.isSupportedVideoCodecProfile(a.codec,a.codecString))return!1;if(!this.willUseMediaSource())return this.isWebCodecsVideoAvailable(this.channelId)?this.webCodecsRenditionSupport.checkVideoSupport(a):!0;const B=yield pl(a);if(!B.supported||a.codec=="av1"&&!B.smooth&&!B.powerEfficient)return!1;const C=this.options.getOverride("maxVideoBitRate",this.channelId);return C?C>=a.bitRate:!0})));let g=e.filter((a,B)=>t[B]);const n=g.filter(a=>a.codec==="h264").reverse()[0],o=g.filter(a=>a.codec==="av1").reverse()[0];return n&&o&&n.width>o.width&&n.height>o.height&&(g=g.filter(a=>a.codec!=="av1")),g}));s(this,"patchSubscription",(e,t)=>{const g=this.options.get("maxInitialBitRate"),n=Math.min(this.options.get("maxVideoBitRate"),g,t,this.targetSubscription.video.bitRate),o=Math.min(this.options.get("maxAudioBitRate"),g,t,this.targetSubscription.audio.bitRate),a=this.options.get("media")==="audio"?[]:this.options.get("videoCodecs",this.channelId),B=this.supportedAudioCodecs(),C=e.renditions.filter(ti),Q=e.renditions.filter(ei),h=B.find(p=>C.find(y=>y.codec===p)!==void 0),d=a.find(p=>Q.find(y=>y.codec===p)!==void 0),u=C.map(p=>p.language);if(this.logger.debug("supported and selected codecs",{audioCodecs:B,videoCodecs:a,audioCodec:h,videoCodec:d}),d){const p=this.options.get("maxSize");this.modules.subscription.setVideoConstraint(f({codec:d,bitRate:this.abrEnabled?n:this.options.get("maxVideoBitRate")},p))}h&&(this.modules.subscription.setAudioConstraint({codec:h,bitRate:this.abrEnabled?o:this.options.get("maxAudioBitRate"),language:this.options.get("language")}),(!u.includes(this.options.get("language"))||this.language===void 0)&&this.modules.subscription.setLanguage(u[0])),this.alignSizeAndBitRate(this.targetSubscription);const m=this.modules.subscription.getTargetSubscription();this.emitter.emit("subscription changed",{to:m,from:this.modules.subscription.getCurrentSubscription()})});s(this,"isSupportedVideoCodecProfile",(e,t)=>{if(this.willUseMediaSource()){const g=is();return g?g.isTypeSupported(mt({codec:e,codecString:t})):!0}if(this.isWebCodecsVideoAvailable(this.channelId)&&(e==="h264"||e==="av1"))return!0;if(e==="h264"){const g=!!(t!=null&&t.startsWith("avc1.42")),n=!!(t!=null&&t.startsWith("avc1.66."));return g||n}return e!=="av1"});s(this,"supportedAudioCodecs",()=>{if(this.options.get("media")==="video")return[];const e=[];return(this.willUseMediaSource()||this.isWebCodecsAudioAvailable(this.channelId))&&e.push("aac"),(this.browser.supportsMp4Opus&&this.options.get("mseOpusEnabled")||!this.willUseMediaSource())&&e.push("opus"),this.isWebCodecsAudioAvailable(this.channelId)&&e.push("mp3"),e});s(this,"initializeDecodingModule",()=>c(this,null,function*(){var p,y;const e=this.currentRenditionLevel,t=[];if(!e)throw new x("No currentRenditionLevel",{code:"no_current_rendition_level",isFatal:!1});if(e!=null&&e.video&&t.push({type:"video",mimeType:mt(e.video),codec:e.video.codec}),e!=null&&e.audio&&t.push({type:"audio",codec:e.audio.codec,mimeType:mt(e.audio)}),t.length===0)throw new x("Can't initialize decoding module without tracks",{code:"no_tracks",isFatal:!1});if(this.willUseMediaSource()&&this.element instanceof HTMLMediaElement){this.emitter.emit("flush buffers"),yield(p=this.modules.mseModule)==null?void 0:p.setSourceBuffers(t);return}const g=this.shouldUseWebCodecs(this.channelId),n=this.options.get("webcodecsHardwareAcceleration",this.channelId),a=this.shouldUseOffscreenCanvas(this.channelId)&&g,B=typeof OffscreenCanvas!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen=="function",C=a&&B&&typeof VideoDecoder!="undefined";let Q,h;if(C)try{h=document.createElement("canvas"),Va(h),Q=h.transferControlToOffscreen()}catch(k){Q=void 0,h=void 0,this.logger.warn("Failed to enable OffscreenCanvas; falling back to main thread rendering",{error:k})}else a&&this.logger.warn("OffscreenCanvas requested but not supported; falling back to main thread rendering");const d=yield MB.create(this.emitter,this.logger.createContext("DecoderModule"),this.options.get("logLevel"),t,this.playbackSource,this.pool,g,n,Q),{videoRenderer:u}=d.getStatistics(),m=this.modules.canvasModule;if(m instanceof So)if(u==="OffscreenCanvas"&&h){m.setVideoRenderingEnabled(!1);const k=this.element;k.parentElement?k.parentElement.replaceChild(h,k):this.logger.warn("OffscreenCanvas rendering is active but the current element is not attached to the DOM. Updating internal element reference only."),this.offscreenCanvasElement=h,this.setElement(h)}else{m.setVideoRenderingEnabled(!0),this.offscreenCanvasElement=void 0;const k=m.element();if(k!==this.element){const N=this.element;N.parentElement&&N.parentElement.replaceChild(k,N),this.setElement(k)}}else m instanceof rs&&(u==="OffscreenCanvas"&&h?(m.setOffscreenCanvas(h),this.offscreenCanvasElement=h):(m.setOffscreenCanvas(void 0),this.offscreenCanvasElement=void 0));(y=this.modules.decoder)==null||y.unload(),this.modules.decoder=d,this.modules.decoder.load(),this.setupOffscreenSubtitleRouting()}));s(this,"setupOffscreenSubtitleRouting",()=>{if(this.offscreenSubtitleInterval!==void 0&&(clearInterval(this.offscreenSubtitleInterval),this.offscreenSubtitleInterval=void 0),!this.offscreenCanvasElement||!this.modules.decoder||this.modules.canvasModule instanceof rs)return;const e=this.modules.decoder,t=this.modules.canvasModule;if(!t)return;let g=!1;this.offscreenSubtitleInterval=setInterval(()=>{var h,d,u,m;if(!t.textTracks.language){g&&(e.setSubtitleCues([],0,0,1,0),g=!1);return}g=!0;const o=t.textTracks.getActiveCues(this.currentTime/1e3).map(p=>({text:p.text})),a=((h=this.element)==null?void 0:h.clientWidth)||0,B=((d=this.element)==null?void 0:d.clientHeight)||0,C=((u=this.element)==null?void 0:u.style.getPropertyValue("--vindral-subtitle-offset"))||((m=this.element)==null?void 0:m.style.getPropertyValue("--vindral-control-bar-offset")),Q=parseInt(C||"0",10)||0;e.setSubtitleCues(o,a,B,globalThis.devicePixelRatio||1,-Q)},100)});s(this,"unload",()=>c(this,null,function*(){var e,t,g;this.logger.debug("Unloading modules..."),this.offscreenSubtitleInterval!==void 0&&(clearInterval(this.offscreenSubtitleInterval),this.offscreenSubtitleInterval=void 0),yield Promise.all(Object.values(this.modules).map(n=>n==null?void 0:n.unload())),(e=this.wakeLock)==null||e.unload(),this.pool=new _e(ct.MAX_POOL_SIZE),(g=(t=this.playbackSource).unload)==null||g.call(t),this.element.remove(),this.emitter.reset(),this.encryptedMediaExtensions.unload(),this.reset(),this.logger.debug("Unloaded modules")}));s(this,"userInput",()=>{this.play()});s(this,"pause",()=>{this.options.get("pauseSupportEnabled")&&this.playbackState!=="paused"&&(this.playbackSource.pause(),this.hasCalledConnect&&this.suspend())});s(this,"registerDebugInstance",()=>{Sl(this)});s(this,"play",()=>{var e;this.hasCalledConnect?this.unsuspend():this.playbackState!=="playing"&&(this._connect(),self.addEventListener("__vindral_register_debug__",this.registerDebugInstance),this.modules.timer.setInterval(()=>this.cleanupTextTracks(),ct.REMOVE_CUE_THRESHOLD)),(e=this.wakeLock)==null||e.enable(),this.playbackState==="paused"&&(this.resetModules(),this.emitter.emit("flush buffers"),this.cleanupTextTracks(Number.MAX_SAFE_INTEGER)),this.playbackSource.play()});s(this,"getStatistics",()=>{const e=Object.values(this.modules).reduce((h,d)=>d&&"getStatistics"in d?f(f({},h),d.getStatistics()):h,this.getRuntimeInfo()),t=Math.round(this.timeActive>0?(e.bytesReceived||0)*8/(this.timeActive/1e3):0),g=this.uptime/36e5,n=Math.max(0,(e.connectCount||0)-1),o=g>0?n/g:0,a=this.timeActive/6e4,B=Math.max(a,1),C=a>0?(e.seekAdjustmentCount||0)/B:0,Q=a>0?(e.timeshiftAdjustmentCount||0)/B:0;return V(f({},e),{averageBitRate:t,reconnectsPerHour:o,seekAdjustmentsPerMinute:C,timeshiftAdjustmentsPerMinute:Q})});s(this,"resetModules",()=>{Object.values(this.modules).forEach(e=>{e&&"reset"in e&&e.reset()}),this.sampleProcessingSesssions.clear(),this.playbackSource.currentTime=0,this.playbackSource.isActivated=!1});s(this,"getRuntimeInfo",()=>{const e=this.modules.canvasModule instanceof rs?!0:void 0;return f({uptime:Date.now()-this.createdAt,version:"4.2.0-1-g70011111",clientId:this.clientId,sessionId:this.sessionId,channelId:this.channelId,channelGroupId:this.options.get("channelGroupId"),ip:this.clientIp,url:this.options.get("url"),timeToFirstFrame:this.timeToFirstFrame(),streamToMediaElementEnabled:e,iosMediaElementEnabled:e},this.userAgentInformation.getUserAgentInformation())});s(this,"onMediaElementState",e=>{this.logger.info("media element state",{state:e}),this.options.get("pauseSupportEnabled")&&(e==="paused"?this.modules.documentState.isVisible&&(this.suspend(),this.modules.connection.disconnect()):(this.unsuspend(),this.modules.connection.getState()==="disconnected"&&this.modules.connection.unsuspend()))});s(this,"onBufferEvent",e=>{var g,n,o,a;this.emit("buffer state event",e);const t=!this.playbackSource.isActivated||this.playbackSource.isPaused;if(e==="filled"&&t){const B=Math.max(this.currentTime,(n=(g=this.videoBufferedRanges[0])==null?void 0:g.start)!=null?n:0,(a=(o=this.audioBufferedRanges[0])==null?void 0:o.start)!=null?a:0);this.logger.info("Buffer filled - starting playback",{currentTime:B}),this.playbackSource.currentTime=B,this.modules.sync.activateSyncAdjustments(),this.playbackSource.isActivated=!0}else e==="drained"&&this.playbackSource.isPaused&&(this.playbackSource.isActivated=!1,this.modules.sync.deactivateSyncAdjustments())});s(this,"timeToFirstFrame",()=>{const e=this.modules.playback.getFirstFrameTime(),t=this.modules.connection.firstConnectionTime;if(t&&e)return e-t});this.options=new Nm(f(f({},Xc),Tm(e)));const t=["localhost","127.0.0.1"];e.telemetryEnabled===void 0&&t.includes(location.hostname)&&this.options.set("telemetryEnabled",!1);const g={channelId:this.options.get("channelId"),audio:{language:this.options.get("language"),bitRate:this.options.get("maxAudioBitRate")},video:{bitRate:this.options.get("maxVideoBitRate"),width:this.options.get("maxSize").width,height:this.options.get("maxSize").height}},n=GA.get();n.setLevel(this.options.get("logLevel")),n.setDebug(!1),this.logger=n,this.webCodecsRenditionSupport=new Pm(n),e.iosMediaElementEnabled!==void 0&&this.logger.warn("Option iosMediaElementEnabled is deprecated and will be removed in a future release. Use streamToMediaElementEnabled instead.");const o=(le=e.streamToMediaElementEnabled)!=null?le:e.iosMediaElementEnabled;o!==void 0&&(this.options.set("streamToMediaElementEnabled",o),this.options.set("iosMediaElementEnabled",o));const a=e.mseEnabled!==void 0,B=e.decoders!==void 0;a&&this.logger.warn('Option mseEnabled is deprecated and will be removed in a future release. Use decoders instead (e.g. decoders: ["wasm"]).'),a&&!B&&e.mseEnabled===!1&&this.options.set("decoders",["wasm"]);const C=PB.create(this.emitter,this.logger.createContext("PictureInPictureModule")),Q=JA.create(),h=NB.create(this.emitter,this.logger.createContext("ConnectionModule"),{reconnectHandler:this.options.get("reconnectHandler"),options:this.options,onConnectInfo:this.onConnectInfo}),d=ZB.create(this.logger.createContext("SubscriptionModule"),this.emitter,g),u=VB.create(this.emitter,d),m=OB.create(this.emitter,this.logger.createContext("QualityOfServiceModule"),u),p=xB.create(this.emitter,this.logger.createContext("PlaybackModule"),this,this.options.get("minBufferTime"));this.encryptedMediaExtensions=new NC(this.emitter,this.logger.createContext("EncryptedMediaExtensions"),e.drm),this.drm={setHeaders:D=>{this.encryptedMediaExtensions.headers=D},setQueryParams:D=>{this.encryptedMediaExtensions.queryParams=D}};const y=vB.create(this.emitter),k=this.options.get("poster"),N=k===!0?this.getThumbnailUrl():k||void 0;let U,K,W;if(this.willUseMediaSource()){const D=new BB({type:this.options.get("media")=="audio"?"audio":"video",autoplay:!1,muted:this.options.get("muted")||this.options.get("media")==="video",volume:this.options.get("volume"),logger:this.logger.createContext("MediaElement"),poster:N});D.on("buffer state",L=>this.emitter.emit("buffer state",L)),D.on("needs user input",L=>this.emitter.emit("needs user input",L)),D.on("volume state",L=>this.emit("volume state",L)),D.on("media element state",L=>this.onMediaElementState(L)),this.element=D.element,this.playbackSource=D,NC.isSupported()&&this.encryptedMediaExtensions.attach(D.element),U=YB.create(this.logger.createContext("MseModule"),this.emitter,this.element),this.options.get("pauseSupportEnabled")||(K=Fo.create(this.logger.createContext("UnpauseModule"),D,y)),this.options.get("pictureInPictureEnabled")&&this.emitter.emit("add picture in picture listener",{element:D.element})}else if(this.options.get("streamToMediaElementEnabled")&&qc(this.browser)){const D=rs.create(this.emitter,this.logger.createContext("ModernCanvasModule"),this.pool,this,{type:this.options.get("media")=="audio"?"audio":"video",muted:this.options.get("muted")||this.options.get("media")==="video",volume:this.options.get("volume"),poster:N,offscreenCanvas:this.offscreenCanvasElement,bufferTime:this.options.get("minBufferTime")}),L=D.element();this.element=L.element,this.playbackSource=D,W=D;const z=this.browser.platform.isIOS&&this.browser.platform.iosVersion<=15;this.options.get("pictureInPictureEnabled")&&!z&&this.emitter.emit("add picture in picture listener",{element:this.element}),this.options.get("pauseSupportEnabled")||(K=Fo.create(this.logger.createContext("UnpauseModule"),L,y))}else{let D;const L=()=>{this.setElement(D.element())};D=So.create(this.emitter,this.logger.createContext("LegacyCanvasModule"),this.pool,this,this.options.get("muted")||this.options.get("media")==="video",this.options.get("volume"),L,this.options.get("minBufferTime")),this.element=D.element(),this.playbackSource=D,W=D,this.options.get("iosWakeLockEnabled")&&(this.wakeLock=new fl)}this.emitter.on("channel reset",this.resetModules),this.emitter.on("no data timeout",this.resetModules),this.emitter.on("media element state",D=>this.onMediaElementState(D)),this.emitter.on("volume state",D=>this.emit("volume state",D)),this.options.get("pauseSupportEnabled")||this.emitter.on("exit picture in picture",()=>Q.setTimeout(()=>this.play(),0)),this.emitter.on("constraint cap changed",D=>{this.logger.info("new cap set",{cap:D}),this.alignSizeAndBitRate(this.targetSubscription)}),this.pictureInPicture={enter:()=>C.requestPictureInPicture(),exit:()=>C.exitPictureInPicture(),isActive:()=>C.isPictureInPictureActive(),isSupported:()=>C.isPictureInPictureSupported()},this.emitter.on("error",D=>{if(D.type()==="external"&&this.emit("error",D),D.isFatal())return()=>{this.unload()}});const Z=this.browser.platform.isWebKit,j=XB.create(this.emitter,this.logger.createContext("SyncModule"),this.playbackSource,p,this.willUseMediaSource()&&!Z),QA=KB.create(this.logger.createContext("JitterModule")),NA=(this.options.get("edgeUrl")||this.options.get("url")).replace("wss://","https://").replace("ws://","http://").replace("//lb.","//errors."),ee=new URL("/telemetry",NA).toString(),qA=yo.create(this.logger.createContext("TelemetryModule"),this.emitter,{url:ee,enabled:this.options.get("telemetryEnabled"),includeStats:!1,interval:5e3},this);this.modules={telemetry:qA,bufferTime:EB.create(this.emitter,this.logger.createContext("BufferTimeModule"),m,this,{maxBufferTime:this.options.get("maxBufferTime"),minBufferTime:this.options.get("minBufferTime")}),incomingData:qB.create(this.emitter),adaptivity:QB.create(this.emitter,this.logger.createContext("AdaptivityModule"),m,{cooldownTime:Math.max(this.options.get("minBufferTime"),2e3)}),constraintCap:JB.create(this.emitter,this.element,u,this.options.get("abrEnabled")?this.options.get("sizeBasedResolutionCapEnabled"):!1),event:HB.create(this.emitter,this.logger.createContext("EventModule"),j),sync:j,jitter:QA,documentState:y,connection:h,playback:p,pictureInPicture:C,timer:Q,subscription:d,renditions:u,qualityOfService:m,mseModule:U,unpause:K,canvasModule:W},this.modules.adaptivity.isEnabled=this.options.get("abrEnabled"),this.emitter.on("page active",D=>{var L;D&&typeof this.disconnectTimeout=="number"&&(this.modules.timer.clearInterval(this.disconnectTimeout),this.disconnectTimeout=void 0),D?this.playbackSource.isPaused||(this.logger.debug("Unsuspending"),this.unsuspend()):(this.logger.debug("Suspending"),this.suspend(),this.modules.decoder?this.options.get("iosBackgroundPlayEnabled")?(this.modules.decoder.unsuspend(),(L=this.modules.canvasModule)==null||L.unsuspend()):this.modules.connection.disconnect():(this.disconnectTimeout&&this.modules.timer.clearInterval(this.disconnectTimeout),this.disconnectTimeout=this.modules.timer.setInterval(()=>{const z=this.playbackState==="paused"||this.muted;this.connectionState==="connected"&&z&&(this.emitter.emit("flush buffers"),this.modules.connection.disconnect("Page inactive timeout"))},ct.DISCONNECT_TIMEOUT)))});let XA;this.emitter.on("context switch complete",()=>{XA||(XA=window.setTimeout(()=>{window.clearTimeout(XA),XA=void 0,this.emit("context switch","completed"),this.emitLanguagesIfChanged()},this.targetBufferTime))}),this.emitter.on("context switch started",()=>this.emit("context switch","started")),this.emitter.on("needs user input",D=>this.emit("needs user input",D)),this.emitter.on("event",D=>{switch(D.type){case"metadata":this.emit("metadata",D);break;case"channel switch":this.emit("channel switch",{channelId:D.channelId});break;case"language switch":this.emit("language switch",{language:D.language});break}}),this.emitter.on("buffer state event",this.onBufferEvent),this.emitter.on("playback state",D=>this.emit("playback state",D)),this.emitter.on("rendition level changed",({to:D})=>{D&&this.emit("rendition level",D)}),this.emitter.on("connection state",D=>{this.emit("connection state",D)}),this.emitter.on("recovered from media error",()=>{this.modules.adaptivity.reset(this.targetBufferTime*2)}),this.emitter.once("connect info",D=>{var F,b,v;const z=((b=(F=D.telemetry)==null?void 0:F.probability)!=null?b:1)>=Math.random();D.telemetry&&((v=this.modules.telemetry)==null||v.unload(),this.modules.telemetry=yo.create(this.logger.createContext("TelemetryModule"),this.emitter,V(f({},D.telemetry),{enabled:this.options.get("telemetryEnabled")&&z}),this),this.modules.telemetry.load())}),this.emitter.on("adapt level",D=>{var O,oA,RA,zA,sA;this.logger.debug("adapt level",{direction:D});const L=this.modules.renditions.getRenditionLevels(),z=this.modules.renditions.getRenditionLevel(),F=L.findIndex(gA=>gA===z),b=L.length-1;let v=F;switch(D){case"upgrade":{const gA=Math.min(F+1,b),BA=L[gA],SA=(O=this.modules.connection.estimatedBandwidth)!=null?O:wt(),LA=((RA=(oA=BA==null?void 0:BA.audio)==null?void 0:oA.bitRate)!=null?RA:0)+((sA=(zA=BA==null?void 0:BA.video)==null?void 0:zA.bitRate)!=null?sA:0),ht=SA*2>LA;BA&&ht&&this.modules.adaptivity.isQoSOk(BA)&&(v=gA)}break;case"downgrade":v=Math.max(F-1,0);break;case"double downgrade":v=Math.max(F-2,0);break;case"reconnect":if(F===0||this.modules.qualityOfService.timeSpentBufferingLast(6e3)>5e3){if(!this.modules.connection.lastConnectionTime||Date.now()-this.modules.connection.lastConnectionTime<this.modules.qualityOfService.fatalQosGraceTime()||this.modules.connection.getState()!=="connected")return;this.modules.qualityOfService.incrementFatalQosCount(),this.logger.info("Reconnecting due to poor qos"),this.modules.connection.reconnect("Fatal QOS"),this.emitter.emit("adapted level");return}else v=0}if(v===F)return;const eA=L[v];this.alignSizeAndBitRate(V(f({},this.targetSubscription),{video:f(f({},this.targetSubscription.video),eA==null?void 0:eA.video),audio:f(f({},this.targetSubscription.audio),eA==null?void 0:eA.audio)})),this.emitter.emit("adapted level")}),this.emitter.on("text track data",D=>{const L=I(this,oe).find(v=>v.language===D.language),F=this.modules.sync.getTimeshiftOffset()/1e3,b=F-I(this,Zi);if(E(this,Zi,F),L){if(L.cues)for(const v of L.cues)v.startTime-=b,v.endTime-=b;for(const v of D.cues){const eA=new VTTCue(v.startTime-F,v.endTime-F,v.text);L.addCue(eA)}}}),this.emitter.on("received signal",D=>{var F;const L=D,z=this.modules.subscription.getCurrentSubscription();switch(this.logger.debug("received",f({},L)),L.type){case"client ip":this.clientIp=L.ip;break;case"renditions":this.updateTextTracks(L.renditions),E(this,Xi,this.filterRenditions(L.renditions).then(b=>{this.emitter.emit("renditions",{renditions:b,channelId:this.currentSubscription.channelId}),this.emit("rendition levels",this.modules.renditions.getRenditionLevels()),this.emitLanguagesIfChanged()}).finally(()=>{E(this,Xi,void 0)}));break;case"subscription changed":try{Ym(L.subscription)}catch(b){this.emitter.emit("error",new x("Subscription failed validation",{source:b instanceof Error?b:void 0,isFatal:!1,code:"subscription_failed_validation"}))}this.emitter.emit("subscription changed",{reset:L.reset,to:L.subscription,from:this.modules.subscription.getCurrentSubscription()}),L.reset&&z.channelId!==L.subscription.channelId&&(this.emit("error",wC(L.subscription.channelId)),this.emit("channel switch failed",{channelId:z.channelId})),this.modules.sync.allowTimeshiftOnAudio=!((F=L.subscription.video)!=null&&F.codec),this.modules.adaptivity.reset();break;case"timing info":this.modules.sync.updateChannelSyncInfo(L.timingInfo.channelId,L.timingInfo),this.emit("server wallclock time",L.timingInfo.wallclockTime);break}}),this.emitter.on("channel switch timeout",D=>{this.emit("error",wC(D)),this.emit("channel switch failed",{channelId:this.currentSubscription.channelId})}),this.emitter.on("received data",D=>{const L=this.modules.subscription.getCurrentSubscription(),z=ml(D);if(!L){this.logger.warn("Received unwanted message",f({},z));return}Xt(V(f({},z),{channelId:L.channelId}))}),this.emitter.on("received moq data",D=>{var v,eA,O,oA,RA,zA;const L=D.payload.mediaType(),z=D.channelId,F=D.renditionId,b=this.modules.sync.processFragment(z,D.payload);if(L!=="text"&&this.modules.jitter.recordSample({type:L,renditionId:F,timestamp:b.baseMediaDecodeTime(),timescale:b.timescale()}),D.switchInfo.channelId&&(D.switchInfo.drmTransition&&this.emitter.emit("error",fC("Switching between DRM and non-DRM channels is not supported",!0)),this.encryptedMediaExtensions.onChannelSwitch(),this.emit("rendition levels",this.modules.renditions.getRenditionLevels()),this.modules.event.addEvent({type:"channel switch",channelId:D.switchInfo.channelId,timestamp:b.baseMediaDecodeTime()/b.timescale()*1e3})),D.switchInfo.language&&this.modules.event.addEvent({type:"language switch",language:D.switchInfo.language,timestamp:b.baseMediaDecodeTime()/b.timescale()*1e3}),this.modules.incomingData.add(L,D.payload.rawBytes().byteLength),(L==="video"||L==="audio")&&this.hasListeners("cmaf fragment")&&this.emit("cmaf fragment",{mediaType:L,initSegment:b.header().rawBytes().slice(),fragment:b.rawBytes().slice(),isKeyframe:b.startsWithKeyframe()}),b.fragment().emsgs.forEach(sA=>{if(!sA.presentationTime)return;const gA=xh(sA.data);gA&&this.modules.event.addEvent({id:sA.id,timestamp:sA.presentationTime/sA.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:gA.txx.value,type:"metadata"})}),this.modules.decoder){const sA=(v=b.header().init().moov.traks[0])==null?void 0:v.mdia.minf.stbl.stsd,gA=(eA=sA==null?void 0:sA.codec)!=null?eA:"h264";let BA;if(gA==="h264")BA=(O=sA==null?void 0:sA.avc1)==null?void 0:O.avcC.bytes;else if(gA==="av1"&&(sA!=null&&sA.av01)){const SA=sA.av01.data();BA=Od(SA)}else gA==="aac"?BA=(RA=(oA=sA==null?void 0:sA.mp4a)==null?void 0:oA.esds)==null?void 0:RA.decoderConfig:gA==="opus"&&(BA=cl((zA=sA==null?void 0:sA.opus)==null?void 0:zA.dops));if(BA){const SA=BA.buffer.slice(BA.byteOffset,BA.byteOffset+BA.byteLength);if(L==="text")throw new Error("Subtitles are not supported");this.emitter.emit("init segment",{initSegment:{channelId:z,renditionId:F,data:SA,timescale:1e3,type:L,codec:gA},mimeType:L})}else gA&&this.logger.warn("Failed to extract init data for codec",{codec:gA,channelId:z,renditionId:F});for(let SA=0;SA<b.samplesCount();SA++){const LA=b.sample(SA);LA&&this.emitter.emit("coded sample",V(f({},LA),{renditionId:F,channelId:z,data:LA.data.buffer.slice(LA.data.byteOffset,LA.data.byteOffset+LA.data.byteLength)}))}}else this.emitter.emit("fragment",{mimeType:D.mimeType,codec:D.codec,fragment:b,channelId:z,renditionId:F})});const jA=this.options.get("container");jA&&this.attach(jA),this.logger.info("Created Vindral instance",{options:this.options});const Xt=D=>c(this,null,function*(){const L=D.channelId;I(this,Xi)&&(yield I(this,Xi));const z=this.modules.renditions.getRendition(D.renditionId,L);if(!dl(D.flags)){if(ll(D.flags)){const b=new TextDecoder().decode(D.payload),v=this.modules.sync.getTimeshiftOffset();if(D.renditionId!==0){const eA=_r(b);if(eA&&eA.language!==void 0){const oA=new ZC().parse(eA.content||""),RA=v/1e3,zA=I(this,oe).find(gA=>gA.language===eA.language),sA=RA-I(this,Zi);if(E(this,Zi,RA),zA){if(zA.cues)for(const gA of zA.cues)gA.startTime-=sA,gA.endTime-=sA;for(const gA of oA){const BA=new VTTCue(gA.startTime-RA,gA.endTime-RA,gA.text);zA.addCue(BA)}}}}else this.modules.event.addEvent({timestamp:D.timestamp/D.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:b,type:"metadata"})}else if(z!=null&&z.codec){const F=Wa(z.codec);if(F==="text")throw new Error("Subtitles are not supported");if(this.modules.incomingData.add(F,D.payload.byteLength),hl(D.flags)){const b=V(f({type:F,data:D.payload,codec:z.codec},D),{channelId:L}),v=al(b.codec,b.payload);v&&this.sizes.set(b.renditionId,v);const eA=mt({codec:z.codec,codecString:z.codecString});this.emitter.emit("init segment",{initSegment:b,mimeType:eA}),this.emit("initialized media")}else{const b=Km(D,z,this.sizes.get(D.renditionId));this.modules.jitter.recordSample(b);let v=this.sampleProcessingSesssions.get(F);if(!v)v=qm(this.modules.sync.processSample(b)),this.sampleProcessingSesssions.set(F,v);else{const eA=this.willUseMediaSource()&&this.isSwitchingRenditionLevel&&b.type==="video",O=v(this.modules.sync.processSample(b),eA);let oA=b;O.forEach(RA=>{this.modules.event.extractEvent(RA,oA),this.emitter.emit("coded sample",RA),oA=RA})}}}}});this.options.get("maxVideoBitRate")!==Number.MAX_SAFE_INTEGER&&(this.maxVideoBitRate=this.options.get("maxVideoBitRate")),this.options.get("maxAudioBitRate")!==Number.MAX_SAFE_INTEGER&&(this.maxAudioBitRate=this.options.get("maxAudioBitRate")),gs(this.options.get("maxSize"),qn())||(this.maxSize=this.options.get("maxSize")),this.options.get("burstEnabled")&&d.enableBurst(this.targetBufferTime)}set volume(e){this.playbackSource.volume=e}get volume(){return this.playbackSource.volume}set muted(e){if(e===this.muted)return;const t=this.playbackSource.muted;this.playbackSource.muted=e,!e&&t&&!this.playbackSource.isPaused&&this.playbackSource.play()}get muted(){return this.playbackSource.muted}get media(){return this.options.get("media")}get videoBitRate(){return this.modules.incomingData.averageBitRate("video")}get audioBitRate(){return this.modules.incomingData.averageBitRate("audio")}get connectionState(){return this.modules.connection.getState()}get playbackState(){return this.modules.playback.getState()}get bufferFullness(){return this.modules.playback.getBufferFullness()}get sizeBasedResolutionCapEnabled(){return this.modules.constraintCap.sizeBasedResolutionCapEnabled}set sizeBasedResolutionCapEnabled(e){this.modules.constraintCap.sizeBasedResolutionCapEnabled=e}get abrEnabled(){return this.modules.adaptivity.isEnabled}set abrEnabled(e){this.modules.constraintCap.sizeBasedResolutionCapEnabled=e?this.options.get("sizeBasedResolutionCapEnabled"):!1,this.modules.adaptivity.isEnabled=e,this.alignSizeAndBitRate(this.targetSubscription)}get serverEdgeTime(){return this.modules.sync.getLiveEdgeTimeLatencyAdjusted(this.currentSubscription.channelId)}get serverWallclockTime(){return this.modules.sync.getWallclockTimeLatencyAdjusted(this.currentSubscription.channelId)}get currentTime(){return this.modules.sync.serverCurrentTime}get channelCurrentTime(){return this.modules.sync.channelCurrentTime}get targetBufferTime(){return this.modules.playback.getTargetBufferTime()}set targetBufferTime(e){this.modules.playback.getTargetBufferTime()!==e&&(this.modules.playback.setTargetBufferTime(e),this.playbackSource.currentTime=this.modules.sync.serverCurrentTime,this.options.get("burstEnabled",this.channelId)?this.modules.subscription.enableBurst(this.targetBufferTime):this.modules.subscription.enableBurst(0))}get playbackLatency(){var e;if(this.playbackSource.currentTime!==0)return this.targetBufferTime+((e=this.modules.sync.drift)!=null?e:0)+this.modules.connection.rtt/2}get playbackWallclockTime(){if(!(!this.serverWallclockTime||!this.playbackLatency))return this.serverWallclockTime-this.playbackLatency}get channels(){return this._channels}get languages(){return this.modules.renditions.getLanguages()}get language(){return this.modules.subscription.getTargetSubscription().audio.language}set language(e){if(e===this.language)return;const t=this.languages;if(e!==void 0&&t.length>0&&!t.includes(e)){this.logger.warn(`Language "${e}" is not available. Available languages: ${t.join(", ")}`);return}this.modules.subscription.setLanguage(e),this.alignSizeAndBitRate(this.targetSubscription)}set textTrack(e){e!==this.textTrack&&(I(this,oe).forEach(t=>{if(t.label===e)t.mode="showing";else{if(t.mode==="showing"&&t.cues)for(const g of[...t.cues])t.removeCue(g);t.mode="hidden"}}),this.emitter.emit("text track",e))}get textTracks(){return I(this,oe).filter(e=>e.mode!=="disabled").map(e=>e.label)}get textTrack(){var e;return(e=I(this,oe).find(t=>t.mode==="showing"))==null?void 0:e.label}get channelId(){var e,t;return(t=(e=this.modules)==null?void 0:e.subscription.getTargetSubscription().channelId)!=null?t:this.options.get("channelId")}set channelId(e){if(e===this.channelId)return;this.modules.subscription.setChannelId(e);const t=this.options.get("media")==="audio"?[]:this.options.get("videoCodecs"),g=this.modules.renditions.getAudioRenditions(e),n=this.modules.renditions.getVideoRenditions(e),o=this.targetSubscription.audio.language,a=g==null?void 0:g.some(C=>C.language===o),B=t.find(C=>(n==null?void 0:n.find(Q=>Q.codec===C))!==void 0);B&&this.modules.subscription.setVideoCodec(B),this.logger.debug("Channel switch - started",{audioRenditions:g,targetSubscriptionLanguage:o,targetHasCurrentLanguage:a}),this.alignSizeAndBitRate(this.targetSubscription)}get maxSize(){var g,n;const{width:e,height:t}=(n=(g=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:g.video)!=null?n:qn();return{width:e,height:t}}set maxSize(e){this.modules.constraintCap.setUserSpecifiedCap({video:{width:e.width,height:e.height}}),this.alignSizeAndBitRate(this.targetSubscription)}get maxVideoBitRate(){var e,t;return(t=(e=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:e.video.bitRate)!=null?t:wt()}set maxVideoBitRate(e){this.modules.constraintCap.setUserSpecifiedCap({video:{bitRate:e}}),this.alignSizeAndBitRate(this.targetSubscription)}get maxAudioBitRate(){var e,t;return(t=(e=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:e.audio.bitRate)!=null?t:wt()}set maxAudioBitRate(e){this.modules.constraintCap.setUserSpecifiedCap({audio:{bitRate:e}}),this.alignSizeAndBitRate(this.targetSubscription)}get renditionLevels(){return this.modules.renditions.getRenditionLevels()}get currentRenditionLevel(){return this.modules.renditions.getRenditionLevel()}get targetRenditionLevel(){return this.modules.renditions.getRenditionLevel(this.modules.subscription.getTargetSubscription())}get isSwitchingRenditionLevel(){return this.modules.subscription.isSwitchingSubscription()}get videoBufferedRanges(){var e,t,g,n;return(n=(g=(e=this.modules.mseModule)==null?void 0:e.getBuffer("video"))!=null?g:(t=this.modules.decoder)==null?void 0:t.getBuffer("video"))!=null?n:[]}get audioBufferedRanges(){var e,t,g,n;return(n=(g=(e=this.modules.mseModule)==null?void 0:e.getBuffer("audio"))!=null?g:(t=this.modules.decoder)==null?void 0:t.getBuffer("audio"))!=null?n:[]}get videoKeyframeTimestamps(){var e,t,g,n;return(n=(g=(e=this.modules.mseModule)==null?void 0:e.getVideoKeyframeTimestamps())!=null?g:(t=this.modules.decoder)==null?void 0:t.getVideoKeyframeTimestamps())!=null?n:[]}getApiClient(){return this.modules.connection.apiClient}get lastBufferEvent(){return this.modules.playback.getLastBufferStateEvent()}get activeRatios(){return this.modules.qualityOfService.activeRatios()}get bufferingRatios(){return this.modules.qualityOfService.bufferingRatios()}get timeSpentBuffering(){return this.modules.qualityOfService.timeSpentBuffering()}get timeActive(){return this.modules.qualityOfService.timeActive()}get mediaElement(){return this.element}get audioNode(){var e;return(e=this.modules)!=null&&e.canvasModule?this.modules.canvasModule.audioNode:void 0}get drmStatistics(){var e;return(e=this.encryptedMediaExtensions)==null?void 0:e.getStatistics()}get uptime(){return Date.now()-this.createdAt}suspend(){this.isSuspended||(Object.values(this.modules).forEach(e=>{e&&"suspend"in e&&e.suspend()}),this.isSuspended=!0)}unsuspend(){this.isSuspended&&(Object.values(this.modules).forEach(e=>{e&&"unsuspend"in e&&e.unsuspend()}),this.isSuspended=!1)}alignSizeAndBitRate(e){const t=this.modules.constraintCap.constrainSubscription(V(f({},e),{video:f({},e.video),audio:f({},e.audio)})),g=this.modules.constraintCap.getUserSpecifiedCap();!this.abrEnabled&&g&&(t.audio.bitRate=g.audio.bitRate,t.video.bitRate=g.video.bitRate,t.video.width=g.video.width,t.video.height=g.video.height);const n=this.modules.renditions.getRenditionLevel(t);if(n){if(n.video&&(this.modules.subscription.setVideoBitRate(n.video.bitRate),this.modules.subscription.setSize(n.video)),n.audio)this.modules.subscription.setAudioBitRate(n.audio.bitRate),this.modules.subscription.setLanguage(n.audio.language);else if(t.audio.language){let o=this.modules.renditions.getAudioRenditions(t.channelId);!this.abrEnabled&&g&&(o=o==null?void 0:o.filter(h=>h.bitRate<g.audio.bitRate));const a=t.audio.language,B=o==null?void 0:o.some(h=>h.language===a),C=o==null?void 0:o.find(h=>h.language),Q=(o==null?void 0:o.length)&&o[0]||void 0;B||(C?(this.logger.debug("Randomizing language since target did not have current language"),this.modules.subscription.setAudioBitRate(C.bitRate),this.modules.subscription.setLanguage(C.language)):(this.logger.debug("Randomizing audio rendition since target did not have current language"),Q!=null&&Q.bitRate&&this.modules.subscription.setAudioBitRate(Q.bitRate),this.modules.subscription.setLanguage(Q==null?void 0:Q.language)))}}}get currentSubscription(){return this.modules.subscription.getCurrentSubscription()}get targetSubscription(){return this.modules.subscription.getTargetSubscription()}resolvedDecoder(e){return vm(this.options.get("decoders",e),this.browser.supportsMediaSource,this.options.get("drm"))}willUseMediaSource(){return this.resolvedDecoder()==="mse"}shouldUseWebCodecs(e){return this.resolvedDecoder(e)==="webcodecs"}isWebCodecsVideoAvailable(e){return this.shouldUseWebCodecs(e)&&typeof VideoDecoder!="undefined"}isWebCodecsAudioAvailable(e){return this.shouldUseWebCodecs(e)&&typeof AudioDecoder!="undefined"}shouldUseOffscreenCanvas(e){const t=this.options.get("offscreenCanvasEnabled",e);return t!==void 0?t:this.shouldUseWebCodecs(e)}};Zi=new WeakMap,oe=new WeakMap,Xi=new WeakMap,s(ct,"MAX_POOL_SIZE",10),s(ct,"DISCONNECT_TIMEOUT",15*1e3),s(ct,"REMOVE_CUE_THRESHOLD",1e3*10);let ko=ct;const KQ={bar:"_bar_qm7bl_1",hidden:"_hidden_qm7bl_47"},Jg={"channel-selection-item":"_channel-selection-item_suenn_1","channel-selection-item-selected":"_channel-selection-item-selected_suenn_8","channel-selection-item-image":"_channel-selection-item-image_suenn_13",withThumbnails:"_withThumbnails_suenn_19","hide-on-small":"_hide-on-small_suenn_27"},xm={"icon-button":"_icon-button_5fg7v_1"},TQ={enter:{viewBox:"-12 -12 38 38",content:`<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" transform="translate(-5.000000, -5.000000)">
50
+ `);A==="beacon"?navigator.sendBeacon(this.options.url,e):this.parentContext.connectionState==="connected"?this.emitter.emit("send signal",{type:"telemetry",body:e}):yield zC(new URL(this.options.url),{body:e,headers:{"Content-Type":"text/plain"}}),this.retries=0,this.unsentLines.clear()}catch(e){this.retries++}}}));s(this,"onVisibilityChange",A=>{A==="hidden"&&(this.addStats({isFinal:!0,initiator:"visibilitychange"}),this.send("beacon"))});s(this,"onPageHide",A=>{this.addStats({isFinal:!0,initiator:"pagehide"},{persisted:A.persisted}),this.send("beacon")});s(this,"onRejection",A=>this.addError(A.reason));s(this,"onError",A=>this.addError(A.error));s(this,"addError",A=>{const{includeErrors:e,maxErrorReports:t}=this.options;if(e&&A instanceof x){if(this.errorCount++,this.errorCount>t)return;const g=this.parentContext.getStatistics();this.unsentLines.push(jB("error",f(f({},g),A.toStringifiable())))}});this.logger=A,this.emitter=e,this.options=f(f({},Gm),t),this.parentContext=g}};s(Fa,"create",(A,e,t,g)=>new Fa(A,e,t,g));let yo=Fa;const ka=class ka{constructor(A,e,t){s(this,"logger");s(this,"element");s(this,"documentState");s(this,"timers",new JA);s(this,"unload",()=>{this.timers.unload()});s(this,"unpause",()=>{this.element.userHasProvidedInput&&this.element.isPaused&&this.documentState.isVisible&&this.documentState.isOnline&&(this.logger.debug("Unpause video"),this.element.tryPlay())});this.logger=A,this.element=e,this.documentState=t,this.timers.setInterval(this.unpause,100)}};s(ka,"create",(A,e,t)=>new ka(A,e,t));let Fo=ka;const Um=["minBufferTime","maxBufferTime","burstEnabled","sizeBasedResolutionCapEnabled","separateVideoSocketEnabled","webcodecsHardwareAcceleration","offscreenCanvasEnabled","videoCodecs"];function bm(i){return Um.includes(i)}class Nm{constructor(A){s(this,"options");s(this,"overrides",new Map);this.options=A}getOptions(){return this.options}addOverrides(A,e){this.overrides.set(A,e)}set(A,e){this.options[A]=e}get(A,e){var t;if(e&&bm(A)){const g=(t=this.overrides.get(e))==null?void 0:t[A];if(typeof g!="undefined")return g}return this.options[A]}getOverride(A,e){var t;return(t=this.overrides.get(e))==null?void 0:t[A]}}const Lm=["mse","wasm"],Jm=i=>i!=null?i:Lm,Mm=i=>{if(!i)return!1;const A=i.headers&&Object.keys(i.headers).length>0,e=i.queryParams&&Object.keys(i.queryParams).length>0;return!!(A||e)},vm=(i,A,e)=>{if(Mm(e))return"mse";const t=Jm(i);for(const g of t)switch(g){case"mse":if(A)return"mse";break;case"webcodecs":if(typeof VideoDecoder!="undefined")return"webcodecs";break;case"wasm":return"wasm"}return"wasm"},Hm=6,qm=i=>{let A=[i],e=0,t=0,g=!1;const n=(a,B)=>{var y,k,N;a.flags&&bg(a.flags)&&(e=(y=a.compositionTimeOffset)!=null?y:0),a.timestamp+=e,a.compositionTimeOffset=((k=a.compositionTimeOffset)!=null?k:0)-e;const C=a.timestamp/a.timescale,h=B.flags&&bg(B.flags)?(N=B.compositionTimeOffset)!=null?N:0:e,u=(B.timestamp+h)/B.timescale,m=Math.max(0,Math.round((u-C)*a.timescale));return m>0&&(t=m),V(f({},a),{duration:m>0?m:t})};return(a,B=!1)=>{if(a.flags&&bg(a.flags)&&B&&(g=!g),!(B&&A.length<Hm&&g)&&A.length>0){g=!1;let Q=a;for(let d=A.length-1;d>0;d--){const u=A[d];if(!u||!Q)break;u.timestamp>=Q.timestamp?A.splice(d,1):Q=u}const h=A.map((d,u)=>n(d,A[u+1]||a));return A=[a],h}return A.push(a),[]}},Km=(i,A,e)=>{if(ei(A))return f(V(f({},i),{type:"video",codec:A.codec,isSync:bg(i.flags),data:i.payload,duration:0,width:A.width,height:A.height}),e);if(A.codec==="webvtt")throw new Error("WebVTT is not supported");return V(f({},i),{type:"audio",channels:A.channels,sampleRate:A.sampleRate,codec:A.codec,language:A.language,isSync:bg(i.flags),data:i.payload,duration:0})},vQ=(i,A)=>i&&typeof i=="object"&&A in i,HQ=i=>!(typeof i!="object"||!vQ(i,"channelId")||typeof i.channelId!="string"||!vQ(i,"url")||typeof i.url!="string"||i.channelId.length===0||i.url.length===0),Tm=i=>{if(!HQ(i))throw new x("Invalid options",{isFatal:!0,code:"invalid_options"});const A=f({},i);return Object.keys(A).forEach(e=>{const t=A;typeof t[e]=="undefined"&&delete t[e]}),A},Ym=i=>{if(typeof i!="object"||i===null)throw new Error("not an object");if(!("video"in i))throw new Error("missing video in subscription");if(!("audio"in i))throw new Error("missing audio in subscription");if(!("channelId"in i))throw new Error("missing channelId");return!0},qQ=i=>{switch(i){case"opus":return"opus";case"aac":return"mp4a.40.2";case"mp3":return"mp3";default:{const A=i;throw new Error(`Unsupported audio codec: ${A}`)}}};class Pm{constructor(A){s(this,"cache",new Map);s(this,"inFlight",new Map);s(this,"checkVideoSupport",A=>c(this,null,function*(){var n;if(typeof VideoDecoder=="undefined")return!1;const e=VideoDecoder.isConfigSupported;if(typeof e!="function")return!0;const t=(n=A.codecString)!=null?n:A.codec==="av1"?"av01.0.08M.08":"avc1.42E01E",g=`video|${t}|${A.width}x${A.height}`;return this.check(g,()=>e({codec:t,optimizeForLatency:!0,codedWidth:A.width,codedHeight:A.height}),!0,{message:"Failed to check WebCodecs rendition support. Falling back to optimistic support check.",codec:t,renditionId:A.id})}));s(this,"checkAudioSupport",A=>c(this,null,function*(){var o;if(typeof AudioDecoder=="undefined")return!1;const e=AudioDecoder.isConfigSupported;if(typeof e!="function")return!0;const t=(o=A.codecString)!=null?o:qQ(A.codec),g=`audio|${t}|${A.sampleRate}|${A.channels}`,n=A.codec==="aac"?LC(A.channels,A.sampleRate):A.codec==="opus"?OC(A.channels,A.sampleRate):void 0;return this.check(g,()=>e({codec:t,sampleRate:A.sampleRate,numberOfChannels:A.channels,description:n}),!1,{message:"Failed to check WebCodecs audio rendition support. Treating rendition as unsupported.",codec:t,renditionId:A.id})}));s(this,"check",(A,e,t,g)=>{const n=this.cache.get(A);if(n!==void 0)return Promise.resolve(n);const o=this.inFlight.get(A);if(o)return o;const a=Promise.resolve().then(e).then(({supported:B})=>(this.cache.set(A,B),B)).catch(B=>(this.logger.warn(g.message,{codec:g.codec,renditionId:g.renditionId,error:B}),this.cache.set(A,t),t)).finally(()=>{this.inFlight.delete(A)});return this.inFlight.set(A,a),a});this.logger=A}}const ct=class ct extends ie{constructor(e){var le;super();s(this,"pictureInPicture");s(this,"drm");s(this,"browser",qa());s(this,"options");s(this,"element");s(this,"playbackSource");s(this,"emitter",new ie);s(this,"logger");s(this,"modules");s(this,"clientIp");s(this,"sessionId");s(this,"clientId",$r());s(this,"_channels",[]);s(this,"createdAt",Date.now());s(this,"offscreenCanvasElement");s(this,"webCodecsRenditionSupport");s(this,"hasCalledConnect",!1);s(this,"latestEmittedLanguages",[]);s(this,"wakeLock");s(this,"pool",new _e(ct.MAX_POOL_SIZE));s(this,"userAgentInformation",new Zc);s(this,"encryptedMediaExtensions");r(this,Zi,0);r(this,oe,[]);s(this,"sampleProcessingSesssions",new Map);s(this,"sizes",new Map);s(this,"isSuspended",!0);s(this,"disconnectTimeout");s(this,"offscreenSubtitleInterval");r(this,Xi);s(this,"attach",e=>{var t;(t=this.wakeLock)==null||t.attach(e),e.appendChild(this.element)});s(this,"setElement",e=>{this.element!==e&&(this.element=e,this.modules.constraintCap.setElement(e))});s(this,"getOptions",()=>this.options.getOptions());s(this,"getThumbnailUrl",()=>{let e=this.options.get("edgeUrl")||this.options.get("url");e=e.replace("wss://","https://"),e=e.replace("ws://","http://"),e=e.endsWith("/")?e.slice(0,-1):e;const t=window.devicePixelRatio||1,g=Math.round(window.innerWidth*t),n=Math.round(window.innerHeight*t),o=this.options.get("authenticationToken"),a=o?`&auth.token=${o}`:"";return`${e}/api/thumbnail?channelId=${this.channelId}${a}&width=${g}&height=${n}`});s(this,"updateAuthenticationToken",e=>{this.logger.debug("Got new auth token",{token:e}),this.options.set("authenticationToken",e),this.emitter.emit("send signal",{type:"refresh auth",token:e})});s(this,"connect",()=>{this.hasCalledConnect||(this.play(),this._connect())});s(this,"_connect",()=>{var e,t;this.hasCalledConnect||(this.hasCalledConnect=!0,Object.values(this.modules).forEach(g=>{g&&"load"in g&&g.load()}),this.unsuspend(),this.playbackSource instanceof BB&&((t=(e=this.playbackSource).load)==null||t.call(e)),this.modules.connection.connect())});s(this,"getCastOptions",()=>({url:this.options.get("url"),channelId:this.options.get("channelId"),channelGroupId:this.options.get("channelGroupId"),authenticationToken:this.options.get("authenticationToken"),language:this.options.get("language"),logLevel:this.options.get("logLevel"),minBufferTime:this.options.get("minBufferTime"),tags:this.options.get("tags"),ownerSessionId:this.sessionId,edgeUrl:this.options.get("edgeUrl"),media:this.options.get("media"),drm:this.options.get("drm")}));s(this,"onConnectInfo",e=>c(this,null,function*(){var C;this.sessionId=$r();const t=this.modules.subscription.getTargetSubscription(),g=e.channels.find(Q=>Q.channelId===t.channelId);if(this.emitter.emit("connect info",e),"timeshift"in e&&e.timeshift?(e.timeshift,this._channels=e.channels.map(Q=>V(f({},Q),{timeshift:e.timeshift})),this.emit("timeshift info",e.timeshift)):this._channels=e.channels,this.updateTextTracks((C=g==null?void 0:g.renditions)!=null?C:[]),!this.textTrack&&this.options.get("textTrack")&&(this.textTrack=this.options.get("textTrack")),yield Promise.all(e.channels.map(Q=>c(this,null,function*(){Q.overrides&&this.options.addOverrides(Q.channelId,Q.overrides),Q.renditions=yield this.filterRenditions(Q.renditions),this.modules.renditions.setRenditions(Q.channelId,Q.renditions)}))),!g)throw lC("external");const n=this.options.getOverride("sizeBasedResolutionCapEnabled",this.channelId);n!==void 0&&(this.modules.constraintCap.sizeBasedResolutionCapEnabled=n);const o=this.options.getOverride("minBufferTime",this.channelId),a=this.options.getOverride("maxBufferTime",this.channelId);if((o||a)&&(this.modules.bufferTime.updateConfig({minBufferTime:this.options.get("minBufferTime",this.channelId),maxBufferTime:this.options.get("maxBufferTime",this.channelId)}),this.targetBufferTime=this.options.get("minBufferTime",this.channelId)),this.options.get("burstEnabled",this.channelId)&&this.modules.subscription.enableBurst(this.targetBufferTime),this.emit("is live",g.isLive),!g.isLive)throw new Error("Waiting for channel to go live");this.patchSubscription(g,this.modules.connection.estimatedBandwidth),yield this.initializeDecodingModule(),this.resetModules(),this.emit("rendition levels",this.modules.renditions.getRenditionLevels()),this.emit("channels",this.channels),this.emitLanguagesIfChanged(),this.sampleProcessingSesssions.clear();const B=this.options.get("burstEnabled",this.channelId);return{video:this.targetSubscription.video,audio:this.targetSubscription.audio,burstMs:B?this.targetBufferTime:void 0,sessionId:this.sessionId,clientId:this.clientId,channelId:this.channelId,channelGroupId:this.options.get("channelGroupId"),authToken:this.options.get("authenticationToken"),textTrack:this.textTrack}}));s(this,"emitLanguagesIfChanged",()=>{const e=this.modules.renditions.getLanguages(),t=this.latestEmittedLanguages;e.length==t.length&&e.every(n=>t.includes(n))||(this.logger.debug("Emitting new languages",{currentLanguages:e}),this.latestEmittedLanguages=e,this.emit("languages",this.latestEmittedLanguages))});s(this,"updateTextTracks",e=>{const t=e.filter(g=>g.codec==="webvtt");t.forEach(g=>{if(!I(this,oe).find(o=>o.language===g.language)){if(this.modules.canvasModule){const o=this.modules.canvasModule.textTracks.addTextTrack(g.kind,g.label||g.language||"",g.language||"");I(this,oe).push(o)}else if(this.mediaElement instanceof HTMLVideoElement){const o=this.mediaElement.addTextTrack(g.kind,g.label||g.language,g.language);I(this,oe).push(o)}}});for(const g of I(this,oe))t.find(o=>o.language===g.language)?g.mode==="disabled"&&(g.mode="hidden"):g.mode="disabled";this.emit("text tracks",this.textTracks)});s(this,"cleanupTextTracks",(e=this.currentTime-2e4)=>{I(this,oe).forEach(t=>{if(t.cues)for(const g of t.cues)g.endTime*1e3<e-2e3&&t.removeCue(g)})});s(this,"filterRenditions",e=>c(this,null,function*(){const t=yield Promise.all(e.map(a=>c(this,null,function*(){var Q;if(ti(a))return this.willUseMediaSource()&&!((Q=is())!=null&&Q.isTypeSupported(mt(a)))?!1:this.willUseMediaSource()||a.codec==="opus"?!0:this.isWebCodecsAudioAvailable(this.channelId)?this.webCodecsRenditionSupport.checkAudioSupport(a):!1;if(!ei(a)||!this.isSupportedVideoCodecProfile(a.codec,a.codecString))return!1;if(!this.willUseMediaSource())return this.isWebCodecsVideoAvailable(this.channelId)?this.webCodecsRenditionSupport.checkVideoSupport(a):!0;const B=yield pl(a);if(!B.supported||a.codec=="av1"&&!B.smooth&&!B.powerEfficient)return!1;const C=this.options.getOverride("maxVideoBitRate",this.channelId);return C?C>=a.bitRate:!0})));let g=e.filter((a,B)=>t[B]);const n=g.filter(a=>a.codec==="h264").reverse()[0],o=g.filter(a=>a.codec==="av1").reverse()[0];return n&&o&&n.width>o.width&&n.height>o.height&&(g=g.filter(a=>a.codec!=="av1")),g}));s(this,"patchSubscription",(e,t)=>{const g=this.options.get("maxInitialBitRate"),n=Math.min(this.options.get("maxVideoBitRate"),g,t,this.targetSubscription.video.bitRate),o=Math.min(this.options.get("maxAudioBitRate"),g,t,this.targetSubscription.audio.bitRate),a=this.options.get("media")==="audio"?[]:this.options.get("videoCodecs",this.channelId),B=this.supportedAudioCodecs(),C=e.renditions.filter(ti),Q=e.renditions.filter(ei),h=B.find(p=>C.find(y=>y.codec===p)!==void 0),d=a.find(p=>Q.find(y=>y.codec===p)!==void 0),u=C.map(p=>p.language);if(this.logger.debug("supported and selected codecs",{audioCodecs:B,videoCodecs:a,audioCodec:h,videoCodec:d}),d){const p=this.options.get("maxSize");this.modules.subscription.setVideoConstraint(f({codec:d,bitRate:this.abrEnabled?n:this.options.get("maxVideoBitRate")},p))}h&&(this.modules.subscription.setAudioConstraint({codec:h,bitRate:this.abrEnabled?o:this.options.get("maxAudioBitRate"),language:this.options.get("language")}),(!u.includes(this.options.get("language"))||this.language===void 0)&&this.modules.subscription.setLanguage(u[0])),this.alignSizeAndBitRate(this.targetSubscription);const m=this.modules.subscription.getTargetSubscription();this.emitter.emit("subscription changed",{to:m,from:this.modules.subscription.getCurrentSubscription()})});s(this,"isSupportedVideoCodecProfile",(e,t)=>{if(this.willUseMediaSource()){const g=is();return g?g.isTypeSupported(mt({codec:e,codecString:t})):!0}if(this.isWebCodecsVideoAvailable(this.channelId)&&(e==="h264"||e==="av1"))return!0;if(e==="h264"){const g=!!(t!=null&&t.startsWith("avc1.42")),n=!!(t!=null&&t.startsWith("avc1.66."));return g||n}return e!=="av1"});s(this,"supportedAudioCodecs",()=>{if(this.options.get("media")==="video")return[];const e=[];return(this.willUseMediaSource()||this.isWebCodecsAudioAvailable(this.channelId))&&e.push("aac"),(this.browser.supportsMp4Opus&&this.options.get("mseOpusEnabled")||!this.willUseMediaSource())&&e.push("opus"),this.isWebCodecsAudioAvailable(this.channelId)&&e.push("mp3"),e});s(this,"initializeDecodingModule",()=>c(this,null,function*(){var p,y;const e=this.currentRenditionLevel,t=[];if(!e)throw new x("No currentRenditionLevel",{code:"no_current_rendition_level",isFatal:!1});if(e!=null&&e.video&&t.push({type:"video",mimeType:mt(e.video),codec:e.video.codec}),e!=null&&e.audio&&t.push({type:"audio",codec:e.audio.codec,mimeType:mt(e.audio)}),t.length===0)throw new x("Can't initialize decoding module without tracks",{code:"no_tracks",isFatal:!1});if(this.willUseMediaSource()&&this.element instanceof HTMLMediaElement){this.emitter.emit("flush buffers"),yield(p=this.modules.mseModule)==null?void 0:p.setSourceBuffers(t);return}const g=this.shouldUseWebCodecs(this.channelId),n=this.options.get("webcodecsHardwareAcceleration",this.channelId),a=this.shouldUseOffscreenCanvas(this.channelId)&&g,B=typeof OffscreenCanvas!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen=="function",C=a&&B&&typeof VideoDecoder!="undefined";let Q,h;if(C)try{h=document.createElement("canvas"),Va(h),Q=h.transferControlToOffscreen()}catch(k){Q=void 0,h=void 0,this.logger.warn("Failed to enable OffscreenCanvas; falling back to main thread rendering",{error:k})}else a&&this.logger.warn("OffscreenCanvas requested but not supported; falling back to main thread rendering");const d=yield MB.create(this.emitter,this.logger.createContext("DecoderModule"),this.options.get("logLevel"),t,this.playbackSource,this.pool,g,n,Q),{videoRenderer:u}=d.getStatistics(),m=this.modules.canvasModule;if(m instanceof So)if(u==="OffscreenCanvas"&&h){m.setVideoRenderingEnabled(!1);const k=this.element;k.parentElement?k.parentElement.replaceChild(h,k):this.logger.warn("OffscreenCanvas rendering is active but the current element is not attached to the DOM. Updating internal element reference only."),this.offscreenCanvasElement=h,this.setElement(h)}else{m.setVideoRenderingEnabled(!0),this.offscreenCanvasElement=void 0;const k=m.element();if(k!==this.element){const N=this.element;N.parentElement&&N.parentElement.replaceChild(k,N),this.setElement(k)}}else m instanceof rs&&(u==="OffscreenCanvas"&&h?(m.setOffscreenCanvas(h),this.offscreenCanvasElement=h):(m.setOffscreenCanvas(void 0),this.offscreenCanvasElement=void 0));(y=this.modules.decoder)==null||y.unload(),this.modules.decoder=d,this.modules.decoder.load(),this.setupOffscreenSubtitleRouting()}));s(this,"setupOffscreenSubtitleRouting",()=>{if(this.offscreenSubtitleInterval!==void 0&&(clearInterval(this.offscreenSubtitleInterval),this.offscreenSubtitleInterval=void 0),!this.offscreenCanvasElement||!this.modules.decoder||this.modules.canvasModule instanceof rs)return;const e=this.modules.decoder,t=this.modules.canvasModule;if(!t)return;let g=!1;this.offscreenSubtitleInterval=setInterval(()=>{var h,d,u,m;if(!t.textTracks.language){g&&(e.setSubtitleCues([],0,0,1,0),g=!1);return}g=!0;const o=t.textTracks.getActiveCues(this.currentTime/1e3).map(p=>({text:p.text})),a=((h=this.element)==null?void 0:h.clientWidth)||0,B=((d=this.element)==null?void 0:d.clientHeight)||0,C=((u=this.element)==null?void 0:u.style.getPropertyValue("--vindral-subtitle-offset"))||((m=this.element)==null?void 0:m.style.getPropertyValue("--vindral-control-bar-offset")),Q=parseInt(C||"0",10)||0;e.setSubtitleCues(o,a,B,globalThis.devicePixelRatio||1,-Q)},100)});s(this,"unload",()=>c(this,null,function*(){var e,t,g;this.logger.debug("Unloading modules..."),this.offscreenSubtitleInterval!==void 0&&(clearInterval(this.offscreenSubtitleInterval),this.offscreenSubtitleInterval=void 0),yield Promise.all(Object.values(this.modules).map(n=>n==null?void 0:n.unload())),(e=this.wakeLock)==null||e.unload(),this.pool=new _e(ct.MAX_POOL_SIZE),(g=(t=this.playbackSource).unload)==null||g.call(t),this.element.remove(),this.emitter.reset(),this.encryptedMediaExtensions.unload(),this.reset(),this.logger.debug("Unloaded modules")}));s(this,"userInput",()=>{this.play()});s(this,"pause",()=>{this.options.get("pauseSupportEnabled")&&this.playbackState!=="paused"&&(this.playbackSource.pause(),this.hasCalledConnect&&this.suspend())});s(this,"registerDebugInstance",()=>{Sl(this)});s(this,"play",()=>{var e;this.hasCalledConnect?this.unsuspend():this.playbackState!=="playing"&&(this._connect(),self.addEventListener("__vindral_register_debug__",this.registerDebugInstance),this.modules.timer.setInterval(()=>this.cleanupTextTracks(),ct.REMOVE_CUE_THRESHOLD)),(e=this.wakeLock)==null||e.enable(),this.playbackState==="paused"&&(this.resetModules(),this.emitter.emit("flush buffers"),this.cleanupTextTracks(Number.MAX_SAFE_INTEGER)),this.playbackSource.play()});s(this,"getStatistics",()=>{const e=Object.values(this.modules).reduce((h,d)=>d&&"getStatistics"in d?f(f({},h),d.getStatistics()):h,this.getRuntimeInfo()),t=Math.round(this.timeActive>0?(e.bytesReceived||0)*8/(this.timeActive/1e3):0),g=this.uptime/36e5,n=Math.max(0,(e.connectCount||0)-1),o=g>0?n/g:0,a=this.timeActive/6e4,B=Math.max(a,1),C=a>0?(e.seekAdjustmentCount||0)/B:0,Q=a>0?(e.timeshiftAdjustmentCount||0)/B:0;return V(f({},e),{averageBitRate:t,reconnectsPerHour:o,seekAdjustmentsPerMinute:C,timeshiftAdjustmentsPerMinute:Q})});s(this,"resetModules",()=>{Object.values(this.modules).forEach(e=>{e&&"reset"in e&&e.reset()}),this.sampleProcessingSesssions.clear(),this.playbackSource.currentTime=0,this.playbackSource.isActivated=!1});s(this,"getRuntimeInfo",()=>{const e=this.modules.canvasModule instanceof rs?!0:void 0;return f({uptime:Date.now()-this.createdAt,version:"4.2.0",clientId:this.clientId,sessionId:this.sessionId,channelId:this.channelId,channelGroupId:this.options.get("channelGroupId"),ip:this.clientIp,url:this.options.get("url"),timeToFirstFrame:this.timeToFirstFrame(),streamToMediaElementEnabled:e,iosMediaElementEnabled:e},this.userAgentInformation.getUserAgentInformation())});s(this,"onMediaElementState",e=>{this.logger.info("media element state",{state:e}),this.options.get("pauseSupportEnabled")&&(e==="paused"?this.modules.documentState.isVisible&&(this.suspend(),this.modules.connection.disconnect()):(this.unsuspend(),this.modules.connection.getState()==="disconnected"&&this.modules.connection.unsuspend()))});s(this,"onBufferEvent",e=>{var g,n,o,a;this.emit("buffer state event",e);const t=!this.playbackSource.isActivated||this.playbackSource.isPaused;if(e==="filled"&&t){const B=Math.max(this.currentTime,(n=(g=this.videoBufferedRanges[0])==null?void 0:g.start)!=null?n:0,(a=(o=this.audioBufferedRanges[0])==null?void 0:o.start)!=null?a:0);this.logger.info("Buffer filled - starting playback",{currentTime:B}),this.playbackSource.currentTime=B,this.modules.sync.activateSyncAdjustments(),this.playbackSource.isActivated=!0}else e==="drained"&&this.playbackSource.isPaused&&(this.playbackSource.isActivated=!1,this.modules.sync.deactivateSyncAdjustments())});s(this,"timeToFirstFrame",()=>{const e=this.modules.playback.getFirstFrameTime(),t=this.modules.connection.firstConnectionTime;if(t&&e)return e-t});this.options=new Nm(f(f({},Xc),Tm(e)));const t=["localhost","127.0.0.1"];e.telemetryEnabled===void 0&&t.includes(location.hostname)&&this.options.set("telemetryEnabled",!1);const g={channelId:this.options.get("channelId"),audio:{language:this.options.get("language"),bitRate:this.options.get("maxAudioBitRate")},video:{bitRate:this.options.get("maxVideoBitRate"),width:this.options.get("maxSize").width,height:this.options.get("maxSize").height}},n=GA.get();n.setLevel(this.options.get("logLevel")),n.setDebug(!1),this.logger=n,this.webCodecsRenditionSupport=new Pm(n),e.iosMediaElementEnabled!==void 0&&this.logger.warn("Option iosMediaElementEnabled is deprecated and will be removed in a future release. Use streamToMediaElementEnabled instead.");const o=(le=e.streamToMediaElementEnabled)!=null?le:e.iosMediaElementEnabled;o!==void 0&&(this.options.set("streamToMediaElementEnabled",o),this.options.set("iosMediaElementEnabled",o));const a=e.mseEnabled!==void 0,B=e.decoders!==void 0;a&&this.logger.warn('Option mseEnabled is deprecated and will be removed in a future release. Use decoders instead (e.g. decoders: ["wasm"]).'),a&&!B&&e.mseEnabled===!1&&this.options.set("decoders",["wasm"]);const C=PB.create(this.emitter,this.logger.createContext("PictureInPictureModule")),Q=JA.create(),h=NB.create(this.emitter,this.logger.createContext("ConnectionModule"),{reconnectHandler:this.options.get("reconnectHandler"),options:this.options,onConnectInfo:this.onConnectInfo}),d=ZB.create(this.logger.createContext("SubscriptionModule"),this.emitter,g),u=VB.create(this.emitter,d),m=OB.create(this.emitter,this.logger.createContext("QualityOfServiceModule"),u),p=xB.create(this.emitter,this.logger.createContext("PlaybackModule"),this,this.options.get("minBufferTime"));this.encryptedMediaExtensions=new NC(this.emitter,this.logger.createContext("EncryptedMediaExtensions"),e.drm),this.drm={setHeaders:D=>{this.encryptedMediaExtensions.headers=D},setQueryParams:D=>{this.encryptedMediaExtensions.queryParams=D}};const y=vB.create(this.emitter),k=this.options.get("poster"),N=k===!0?this.getThumbnailUrl():k||void 0;let U,K,W;if(this.willUseMediaSource()){const D=new BB({type:this.options.get("media")=="audio"?"audio":"video",autoplay:!1,muted:this.options.get("muted")||this.options.get("media")==="video",volume:this.options.get("volume"),logger:this.logger.createContext("MediaElement"),poster:N});D.on("buffer state",L=>this.emitter.emit("buffer state",L)),D.on("needs user input",L=>this.emitter.emit("needs user input",L)),D.on("volume state",L=>this.emit("volume state",L)),D.on("media element state",L=>this.onMediaElementState(L)),this.element=D.element,this.playbackSource=D,NC.isSupported()&&this.encryptedMediaExtensions.attach(D.element),U=YB.create(this.logger.createContext("MseModule"),this.emitter,this.element),this.options.get("pauseSupportEnabled")||(K=Fo.create(this.logger.createContext("UnpauseModule"),D,y)),this.options.get("pictureInPictureEnabled")&&this.emitter.emit("add picture in picture listener",{element:D.element})}else if(this.options.get("streamToMediaElementEnabled")&&qc(this.browser)){const D=rs.create(this.emitter,this.logger.createContext("ModernCanvasModule"),this.pool,this,{type:this.options.get("media")=="audio"?"audio":"video",muted:this.options.get("muted")||this.options.get("media")==="video",volume:this.options.get("volume"),poster:N,offscreenCanvas:this.offscreenCanvasElement,bufferTime:this.options.get("minBufferTime")}),L=D.element();this.element=L.element,this.playbackSource=D,W=D;const z=this.browser.platform.isIOS&&this.browser.platform.iosVersion<=15;this.options.get("pictureInPictureEnabled")&&!z&&this.emitter.emit("add picture in picture listener",{element:this.element}),this.options.get("pauseSupportEnabled")||(K=Fo.create(this.logger.createContext("UnpauseModule"),L,y))}else{let D;const L=()=>{this.setElement(D.element())};D=So.create(this.emitter,this.logger.createContext("LegacyCanvasModule"),this.pool,this,this.options.get("muted")||this.options.get("media")==="video",this.options.get("volume"),L,this.options.get("minBufferTime")),this.element=D.element(),this.playbackSource=D,W=D,this.options.get("iosWakeLockEnabled")&&(this.wakeLock=new fl)}this.emitter.on("channel reset",this.resetModules),this.emitter.on("no data timeout",this.resetModules),this.emitter.on("media element state",D=>this.onMediaElementState(D)),this.emitter.on("volume state",D=>this.emit("volume state",D)),this.options.get("pauseSupportEnabled")||this.emitter.on("exit picture in picture",()=>Q.setTimeout(()=>this.play(),0)),this.emitter.on("constraint cap changed",D=>{this.logger.info("new cap set",{cap:D}),this.alignSizeAndBitRate(this.targetSubscription)}),this.pictureInPicture={enter:()=>C.requestPictureInPicture(),exit:()=>C.exitPictureInPicture(),isActive:()=>C.isPictureInPictureActive(),isSupported:()=>C.isPictureInPictureSupported()},this.emitter.on("error",D=>{if(D.type()==="external"&&this.emit("error",D),D.isFatal())return()=>{this.unload()}});const Z=this.browser.platform.isWebKit,j=XB.create(this.emitter,this.logger.createContext("SyncModule"),this.playbackSource,p,this.willUseMediaSource()&&!Z),QA=KB.create(this.logger.createContext("JitterModule")),NA=(this.options.get("edgeUrl")||this.options.get("url")).replace("wss://","https://").replace("ws://","http://").replace("//lb.","//errors."),ee=new URL("/telemetry",NA).toString(),qA=yo.create(this.logger.createContext("TelemetryModule"),this.emitter,{url:ee,enabled:this.options.get("telemetryEnabled"),includeStats:!1,interval:5e3},this);this.modules={telemetry:qA,bufferTime:EB.create(this.emitter,this.logger.createContext("BufferTimeModule"),m,this,{maxBufferTime:this.options.get("maxBufferTime"),minBufferTime:this.options.get("minBufferTime")}),incomingData:qB.create(this.emitter),adaptivity:QB.create(this.emitter,this.logger.createContext("AdaptivityModule"),m,{cooldownTime:Math.max(this.options.get("minBufferTime"),2e3)}),constraintCap:JB.create(this.emitter,this.element,u,this.options.get("abrEnabled")?this.options.get("sizeBasedResolutionCapEnabled"):!1),event:HB.create(this.emitter,this.logger.createContext("EventModule"),j),sync:j,jitter:QA,documentState:y,connection:h,playback:p,pictureInPicture:C,timer:Q,subscription:d,renditions:u,qualityOfService:m,mseModule:U,unpause:K,canvasModule:W},this.modules.adaptivity.isEnabled=this.options.get("abrEnabled"),this.emitter.on("page active",D=>{var L;D&&typeof this.disconnectTimeout=="number"&&(this.modules.timer.clearInterval(this.disconnectTimeout),this.disconnectTimeout=void 0),D?this.playbackSource.isPaused||(this.logger.debug("Unsuspending"),this.unsuspend()):(this.logger.debug("Suspending"),this.suspend(),this.modules.decoder?this.options.get("iosBackgroundPlayEnabled")?(this.modules.decoder.unsuspend(),(L=this.modules.canvasModule)==null||L.unsuspend()):this.modules.connection.disconnect():(this.disconnectTimeout&&this.modules.timer.clearInterval(this.disconnectTimeout),this.disconnectTimeout=this.modules.timer.setInterval(()=>{const z=this.playbackState==="paused"||this.muted;this.connectionState==="connected"&&z&&(this.emitter.emit("flush buffers"),this.modules.connection.disconnect("Page inactive timeout"))},ct.DISCONNECT_TIMEOUT)))});let XA;this.emitter.on("context switch complete",()=>{XA||(XA=window.setTimeout(()=>{window.clearTimeout(XA),XA=void 0,this.emit("context switch","completed"),this.emitLanguagesIfChanged()},this.targetBufferTime))}),this.emitter.on("context switch started",()=>this.emit("context switch","started")),this.emitter.on("needs user input",D=>this.emit("needs user input",D)),this.emitter.on("event",D=>{switch(D.type){case"metadata":this.emit("metadata",D);break;case"channel switch":this.emit("channel switch",{channelId:D.channelId});break;case"language switch":this.emit("language switch",{language:D.language});break}}),this.emitter.on("buffer state event",this.onBufferEvent),this.emitter.on("playback state",D=>this.emit("playback state",D)),this.emitter.on("rendition level changed",({to:D})=>{D&&this.emit("rendition level",D)}),this.emitter.on("connection state",D=>{this.emit("connection state",D)}),this.emitter.on("recovered from media error",()=>{this.modules.adaptivity.reset(this.targetBufferTime*2)}),this.emitter.once("connect info",D=>{var F,b,v;const z=((b=(F=D.telemetry)==null?void 0:F.probability)!=null?b:1)>=Math.random();D.telemetry&&((v=this.modules.telemetry)==null||v.unload(),this.modules.telemetry=yo.create(this.logger.createContext("TelemetryModule"),this.emitter,V(f({},D.telemetry),{enabled:this.options.get("telemetryEnabled")&&z}),this),this.modules.telemetry.load())}),this.emitter.on("adapt level",D=>{var O,oA,RA,zA,sA;this.logger.debug("adapt level",{direction:D});const L=this.modules.renditions.getRenditionLevels(),z=this.modules.renditions.getRenditionLevel(),F=L.findIndex(gA=>gA===z),b=L.length-1;let v=F;switch(D){case"upgrade":{const gA=Math.min(F+1,b),BA=L[gA],SA=(O=this.modules.connection.estimatedBandwidth)!=null?O:wt(),LA=((RA=(oA=BA==null?void 0:BA.audio)==null?void 0:oA.bitRate)!=null?RA:0)+((sA=(zA=BA==null?void 0:BA.video)==null?void 0:zA.bitRate)!=null?sA:0),ht=SA*2>LA;BA&&ht&&this.modules.adaptivity.isQoSOk(BA)&&(v=gA)}break;case"downgrade":v=Math.max(F-1,0);break;case"double downgrade":v=Math.max(F-2,0);break;case"reconnect":if(F===0||this.modules.qualityOfService.timeSpentBufferingLast(6e3)>5e3){if(!this.modules.connection.lastConnectionTime||Date.now()-this.modules.connection.lastConnectionTime<this.modules.qualityOfService.fatalQosGraceTime()||this.modules.connection.getState()!=="connected")return;this.modules.qualityOfService.incrementFatalQosCount(),this.logger.info("Reconnecting due to poor qos"),this.modules.connection.reconnect("Fatal QOS"),this.emitter.emit("adapted level");return}else v=0}if(v===F)return;const eA=L[v];this.alignSizeAndBitRate(V(f({},this.targetSubscription),{video:f(f({},this.targetSubscription.video),eA==null?void 0:eA.video),audio:f(f({},this.targetSubscription.audio),eA==null?void 0:eA.audio)})),this.emitter.emit("adapted level")}),this.emitter.on("text track data",D=>{const L=I(this,oe).find(v=>v.language===D.language),F=this.modules.sync.getTimeshiftOffset()/1e3,b=F-I(this,Zi);if(E(this,Zi,F),L){if(L.cues)for(const v of L.cues)v.startTime-=b,v.endTime-=b;for(const v of D.cues){const eA=new VTTCue(v.startTime-F,v.endTime-F,v.text);L.addCue(eA)}}}),this.emitter.on("received signal",D=>{var F;const L=D,z=this.modules.subscription.getCurrentSubscription();switch(this.logger.debug("received",f({},L)),L.type){case"client ip":this.clientIp=L.ip;break;case"renditions":this.updateTextTracks(L.renditions),E(this,Xi,this.filterRenditions(L.renditions).then(b=>{this.emitter.emit("renditions",{renditions:b,channelId:this.currentSubscription.channelId}),this.emit("rendition levels",this.modules.renditions.getRenditionLevels()),this.emitLanguagesIfChanged()}).finally(()=>{E(this,Xi,void 0)}));break;case"subscription changed":try{Ym(L.subscription)}catch(b){this.emitter.emit("error",new x("Subscription failed validation",{source:b instanceof Error?b:void 0,isFatal:!1,code:"subscription_failed_validation"}))}this.emitter.emit("subscription changed",{reset:L.reset,to:L.subscription,from:this.modules.subscription.getCurrentSubscription()}),L.reset&&z.channelId!==L.subscription.channelId&&(this.emit("error",wC(L.subscription.channelId)),this.emit("channel switch failed",{channelId:z.channelId})),this.modules.sync.allowTimeshiftOnAudio=!((F=L.subscription.video)!=null&&F.codec),this.modules.adaptivity.reset();break;case"timing info":this.modules.sync.updateChannelSyncInfo(L.timingInfo.channelId,L.timingInfo),this.emit("server wallclock time",L.timingInfo.wallclockTime);break}}),this.emitter.on("channel switch timeout",D=>{this.emit("error",wC(D)),this.emit("channel switch failed",{channelId:this.currentSubscription.channelId})}),this.emitter.on("received data",D=>{const L=this.modules.subscription.getCurrentSubscription(),z=ml(D);if(!L){this.logger.warn("Received unwanted message",f({},z));return}Xt(V(f({},z),{channelId:L.channelId}))}),this.emitter.on("received moq data",D=>{var v,eA,O,oA,RA,zA;const L=D.payload.mediaType(),z=D.channelId,F=D.renditionId,b=this.modules.sync.processFragment(z,D.payload);if(L!=="text"&&this.modules.jitter.recordSample({type:L,renditionId:F,timestamp:b.baseMediaDecodeTime(),timescale:b.timescale()}),D.switchInfo.channelId&&(D.switchInfo.drmTransition&&this.emitter.emit("error",fC("Switching between DRM and non-DRM channels is not supported",!0)),this.encryptedMediaExtensions.onChannelSwitch(),this.emit("rendition levels",this.modules.renditions.getRenditionLevels()),this.modules.event.addEvent({type:"channel switch",channelId:D.switchInfo.channelId,timestamp:b.baseMediaDecodeTime()/b.timescale()*1e3})),D.switchInfo.language&&this.modules.event.addEvent({type:"language switch",language:D.switchInfo.language,timestamp:b.baseMediaDecodeTime()/b.timescale()*1e3}),this.modules.incomingData.add(L,D.payload.rawBytes().byteLength),(L==="video"||L==="audio")&&this.hasListeners("cmaf fragment")&&this.emit("cmaf fragment",{mediaType:L,initSegment:b.header().rawBytes().slice(),fragment:b.rawBytes().slice(),isKeyframe:b.startsWithKeyframe()}),b.fragment().emsgs.forEach(sA=>{if(!sA.presentationTime)return;const gA=xh(sA.data);gA&&this.modules.event.addEvent({id:sA.id,timestamp:sA.presentationTime/sA.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:gA.txx.value,type:"metadata"})}),this.modules.decoder){const sA=(v=b.header().init().moov.traks[0])==null?void 0:v.mdia.minf.stbl.stsd,gA=(eA=sA==null?void 0:sA.codec)!=null?eA:"h264";let BA;if(gA==="h264")BA=(O=sA==null?void 0:sA.avc1)==null?void 0:O.avcC.bytes;else if(gA==="av1"&&(sA!=null&&sA.av01)){const SA=sA.av01.data();BA=Od(SA)}else gA==="aac"?BA=(RA=(oA=sA==null?void 0:sA.mp4a)==null?void 0:oA.esds)==null?void 0:RA.decoderConfig:gA==="opus"&&(BA=cl((zA=sA==null?void 0:sA.opus)==null?void 0:zA.dops));if(BA){const SA=BA.buffer.slice(BA.byteOffset,BA.byteOffset+BA.byteLength);if(L==="text")throw new Error("Subtitles are not supported");this.emitter.emit("init segment",{initSegment:{channelId:z,renditionId:F,data:SA,timescale:1e3,type:L,codec:gA},mimeType:L})}else gA&&this.logger.warn("Failed to extract init data for codec",{codec:gA,channelId:z,renditionId:F});for(let SA=0;SA<b.samplesCount();SA++){const LA=b.sample(SA);LA&&this.emitter.emit("coded sample",V(f({},LA),{renditionId:F,channelId:z,data:LA.data.buffer.slice(LA.data.byteOffset,LA.data.byteOffset+LA.data.byteLength)}))}}else this.emitter.emit("fragment",{mimeType:D.mimeType,codec:D.codec,fragment:b,channelId:z,renditionId:F})});const jA=this.options.get("container");jA&&this.attach(jA),this.logger.info("Created Vindral instance",{options:this.options});const Xt=D=>c(this,null,function*(){const L=D.channelId;I(this,Xi)&&(yield I(this,Xi));const z=this.modules.renditions.getRendition(D.renditionId,L);if(!dl(D.flags)){if(ll(D.flags)){const b=new TextDecoder().decode(D.payload),v=this.modules.sync.getTimeshiftOffset();if(D.renditionId!==0){const eA=_r(b);if(eA&&eA.language!==void 0){const oA=new ZC().parse(eA.content||""),RA=v/1e3,zA=I(this,oe).find(gA=>gA.language===eA.language),sA=RA-I(this,Zi);if(E(this,Zi,RA),zA){if(zA.cues)for(const gA of zA.cues)gA.startTime-=sA,gA.endTime-=sA;for(const gA of oA){const BA=new VTTCue(gA.startTime-RA,gA.endTime-RA,gA.text);zA.addCue(BA)}}}}else this.modules.event.addEvent({timestamp:D.timestamp/D.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:b,type:"metadata"})}else if(z!=null&&z.codec){const F=Wa(z.codec);if(F==="text")throw new Error("Subtitles are not supported");if(this.modules.incomingData.add(F,D.payload.byteLength),hl(D.flags)){const b=V(f({type:F,data:D.payload,codec:z.codec},D),{channelId:L}),v=al(b.codec,b.payload);v&&this.sizes.set(b.renditionId,v);const eA=mt({codec:z.codec,codecString:z.codecString});this.emitter.emit("init segment",{initSegment:b,mimeType:eA}),this.emit("initialized media")}else{const b=Km(D,z,this.sizes.get(D.renditionId));this.modules.jitter.recordSample(b);let v=this.sampleProcessingSesssions.get(F);if(!v)v=qm(this.modules.sync.processSample(b)),this.sampleProcessingSesssions.set(F,v);else{const eA=this.willUseMediaSource()&&this.isSwitchingRenditionLevel&&b.type==="video",O=v(this.modules.sync.processSample(b),eA);let oA=b;O.forEach(RA=>{this.modules.event.extractEvent(RA,oA),this.emitter.emit("coded sample",RA),oA=RA})}}}}});this.options.get("maxVideoBitRate")!==Number.MAX_SAFE_INTEGER&&(this.maxVideoBitRate=this.options.get("maxVideoBitRate")),this.options.get("maxAudioBitRate")!==Number.MAX_SAFE_INTEGER&&(this.maxAudioBitRate=this.options.get("maxAudioBitRate")),gs(this.options.get("maxSize"),qn())||(this.maxSize=this.options.get("maxSize")),this.options.get("burstEnabled")&&d.enableBurst(this.targetBufferTime)}set volume(e){this.playbackSource.volume=e}get volume(){return this.playbackSource.volume}set muted(e){if(e===this.muted)return;const t=this.playbackSource.muted;this.playbackSource.muted=e,!e&&t&&!this.playbackSource.isPaused&&this.playbackSource.play()}get muted(){return this.playbackSource.muted}get media(){return this.options.get("media")}get videoBitRate(){return this.modules.incomingData.averageBitRate("video")}get audioBitRate(){return this.modules.incomingData.averageBitRate("audio")}get connectionState(){return this.modules.connection.getState()}get playbackState(){return this.modules.playback.getState()}get bufferFullness(){return this.modules.playback.getBufferFullness()}get sizeBasedResolutionCapEnabled(){return this.modules.constraintCap.sizeBasedResolutionCapEnabled}set sizeBasedResolutionCapEnabled(e){this.modules.constraintCap.sizeBasedResolutionCapEnabled=e}get abrEnabled(){return this.modules.adaptivity.isEnabled}set abrEnabled(e){this.modules.constraintCap.sizeBasedResolutionCapEnabled=e?this.options.get("sizeBasedResolutionCapEnabled"):!1,this.modules.adaptivity.isEnabled=e,this.alignSizeAndBitRate(this.targetSubscription)}get serverEdgeTime(){return this.modules.sync.getLiveEdgeTimeLatencyAdjusted(this.currentSubscription.channelId)}get serverWallclockTime(){return this.modules.sync.getWallclockTimeLatencyAdjusted(this.currentSubscription.channelId)}get currentTime(){return this.modules.sync.serverCurrentTime}get channelCurrentTime(){return this.modules.sync.channelCurrentTime}get targetBufferTime(){return this.modules.playback.getTargetBufferTime()}set targetBufferTime(e){this.modules.playback.getTargetBufferTime()!==e&&(this.modules.playback.setTargetBufferTime(e),this.playbackSource.currentTime=this.modules.sync.serverCurrentTime,this.options.get("burstEnabled",this.channelId)?this.modules.subscription.enableBurst(this.targetBufferTime):this.modules.subscription.enableBurst(0))}get playbackLatency(){var e;if(this.playbackSource.currentTime!==0)return this.targetBufferTime+((e=this.modules.sync.drift)!=null?e:0)+this.modules.connection.rtt/2}get playbackWallclockTime(){if(!(!this.serverWallclockTime||!this.playbackLatency))return this.serverWallclockTime-this.playbackLatency}get channels(){return this._channels}get languages(){return this.modules.renditions.getLanguages()}get language(){return this.modules.subscription.getTargetSubscription().audio.language}set language(e){if(e===this.language)return;const t=this.languages;if(e!==void 0&&t.length>0&&!t.includes(e)){this.logger.warn(`Language "${e}" is not available. Available languages: ${t.join(", ")}`);return}this.modules.subscription.setLanguage(e),this.alignSizeAndBitRate(this.targetSubscription)}set textTrack(e){e!==this.textTrack&&(I(this,oe).forEach(t=>{if(t.label===e)t.mode="showing";else{if(t.mode==="showing"&&t.cues)for(const g of[...t.cues])t.removeCue(g);t.mode="hidden"}}),this.emitter.emit("text track",e))}get textTracks(){return I(this,oe).filter(e=>e.mode!=="disabled").map(e=>e.label)}get textTrack(){var e;return(e=I(this,oe).find(t=>t.mode==="showing"))==null?void 0:e.label}get channelId(){var e,t;return(t=(e=this.modules)==null?void 0:e.subscription.getTargetSubscription().channelId)!=null?t:this.options.get("channelId")}set channelId(e){if(e===this.channelId)return;this.modules.subscription.setChannelId(e);const t=this.options.get("media")==="audio"?[]:this.options.get("videoCodecs"),g=this.modules.renditions.getAudioRenditions(e),n=this.modules.renditions.getVideoRenditions(e),o=this.targetSubscription.audio.language,a=g==null?void 0:g.some(C=>C.language===o),B=t.find(C=>(n==null?void 0:n.find(Q=>Q.codec===C))!==void 0);B&&this.modules.subscription.setVideoCodec(B),this.logger.debug("Channel switch - started",{audioRenditions:g,targetSubscriptionLanguage:o,targetHasCurrentLanguage:a}),this.alignSizeAndBitRate(this.targetSubscription)}get maxSize(){var g,n;const{width:e,height:t}=(n=(g=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:g.video)!=null?n:qn();return{width:e,height:t}}set maxSize(e){this.modules.constraintCap.setUserSpecifiedCap({video:{width:e.width,height:e.height}}),this.alignSizeAndBitRate(this.targetSubscription)}get maxVideoBitRate(){var e,t;return(t=(e=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:e.video.bitRate)!=null?t:wt()}set maxVideoBitRate(e){this.modules.constraintCap.setUserSpecifiedCap({video:{bitRate:e}}),this.alignSizeAndBitRate(this.targetSubscription)}get maxAudioBitRate(){var e,t;return(t=(e=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:e.audio.bitRate)!=null?t:wt()}set maxAudioBitRate(e){this.modules.constraintCap.setUserSpecifiedCap({audio:{bitRate:e}}),this.alignSizeAndBitRate(this.targetSubscription)}get renditionLevels(){return this.modules.renditions.getRenditionLevels()}get currentRenditionLevel(){return this.modules.renditions.getRenditionLevel()}get targetRenditionLevel(){return this.modules.renditions.getRenditionLevel(this.modules.subscription.getTargetSubscription())}get isSwitchingRenditionLevel(){return this.modules.subscription.isSwitchingSubscription()}get videoBufferedRanges(){var e,t,g,n;return(n=(g=(e=this.modules.mseModule)==null?void 0:e.getBuffer("video"))!=null?g:(t=this.modules.decoder)==null?void 0:t.getBuffer("video"))!=null?n:[]}get audioBufferedRanges(){var e,t,g,n;return(n=(g=(e=this.modules.mseModule)==null?void 0:e.getBuffer("audio"))!=null?g:(t=this.modules.decoder)==null?void 0:t.getBuffer("audio"))!=null?n:[]}get videoKeyframeTimestamps(){var e,t,g,n;return(n=(g=(e=this.modules.mseModule)==null?void 0:e.getVideoKeyframeTimestamps())!=null?g:(t=this.modules.decoder)==null?void 0:t.getVideoKeyframeTimestamps())!=null?n:[]}getApiClient(){return this.modules.connection.apiClient}get lastBufferEvent(){return this.modules.playback.getLastBufferStateEvent()}get activeRatios(){return this.modules.qualityOfService.activeRatios()}get bufferingRatios(){return this.modules.qualityOfService.bufferingRatios()}get timeSpentBuffering(){return this.modules.qualityOfService.timeSpentBuffering()}get timeActive(){return this.modules.qualityOfService.timeActive()}get mediaElement(){return this.element}get audioNode(){var e;return(e=this.modules)!=null&&e.canvasModule?this.modules.canvasModule.audioNode:void 0}get drmStatistics(){var e;return(e=this.encryptedMediaExtensions)==null?void 0:e.getStatistics()}get uptime(){return Date.now()-this.createdAt}suspend(){this.isSuspended||(Object.values(this.modules).forEach(e=>{e&&"suspend"in e&&e.suspend()}),this.isSuspended=!0)}unsuspend(){this.isSuspended&&(Object.values(this.modules).forEach(e=>{e&&"unsuspend"in e&&e.unsuspend()}),this.isSuspended=!1)}alignSizeAndBitRate(e){const t=this.modules.constraintCap.constrainSubscription(V(f({},e),{video:f({},e.video),audio:f({},e.audio)})),g=this.modules.constraintCap.getUserSpecifiedCap();!this.abrEnabled&&g&&(t.audio.bitRate=g.audio.bitRate,t.video.bitRate=g.video.bitRate,t.video.width=g.video.width,t.video.height=g.video.height);const n=this.modules.renditions.getRenditionLevel(t);if(n){if(n.video&&(this.modules.subscription.setVideoBitRate(n.video.bitRate),this.modules.subscription.setSize(n.video)),n.audio)this.modules.subscription.setAudioBitRate(n.audio.bitRate),this.modules.subscription.setLanguage(n.audio.language);else if(t.audio.language){let o=this.modules.renditions.getAudioRenditions(t.channelId);!this.abrEnabled&&g&&(o=o==null?void 0:o.filter(h=>h.bitRate<g.audio.bitRate));const a=t.audio.language,B=o==null?void 0:o.some(h=>h.language===a),C=o==null?void 0:o.find(h=>h.language),Q=(o==null?void 0:o.length)&&o[0]||void 0;B||(C?(this.logger.debug("Randomizing language since target did not have current language"),this.modules.subscription.setAudioBitRate(C.bitRate),this.modules.subscription.setLanguage(C.language)):(this.logger.debug("Randomizing audio rendition since target did not have current language"),Q!=null&&Q.bitRate&&this.modules.subscription.setAudioBitRate(Q.bitRate),this.modules.subscription.setLanguage(Q==null?void 0:Q.language)))}}}get currentSubscription(){return this.modules.subscription.getCurrentSubscription()}get targetSubscription(){return this.modules.subscription.getTargetSubscription()}resolvedDecoder(e){return vm(this.options.get("decoders",e),this.browser.supportsMediaSource,this.options.get("drm"))}willUseMediaSource(){return this.resolvedDecoder()==="mse"}shouldUseWebCodecs(e){return this.resolvedDecoder(e)==="webcodecs"}isWebCodecsVideoAvailable(e){return this.shouldUseWebCodecs(e)&&typeof VideoDecoder!="undefined"}isWebCodecsAudioAvailable(e){return this.shouldUseWebCodecs(e)&&typeof AudioDecoder!="undefined"}shouldUseOffscreenCanvas(e){const t=this.options.get("offscreenCanvasEnabled",e);return t!==void 0?t:this.shouldUseWebCodecs(e)}};Zi=new WeakMap,oe=new WeakMap,Xi=new WeakMap,s(ct,"MAX_POOL_SIZE",10),s(ct,"DISCONNECT_TIMEOUT",15*1e3),s(ct,"REMOVE_CUE_THRESHOLD",1e3*10);let ko=ct;const KQ={bar:"_bar_qm7bl_1",hidden:"_hidden_qm7bl_47"},Jg={"channel-selection-item":"_channel-selection-item_suenn_1","channel-selection-item-selected":"_channel-selection-item-selected_suenn_8","channel-selection-item-image":"_channel-selection-item-image_suenn_13",withThumbnails:"_withThumbnails_suenn_19","hide-on-small":"_hide-on-small_suenn_27"},xm={"icon-button":"_icon-button_5fg7v_1"},TQ={enter:{viewBox:"-12 -12 38 38",content:`<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" transform="translate(-5.000000, -5.000000)">
51
51
  <path d="M6,14 C5.45,14 5,14.45 5,15 L5,18 C5,18.55 5.45,19 6,19 L9,19 C9.55,19 10,18.55 10,18 C10,17.45 9.55,17 9,17 L7,17 L7,15 C7,14.45 6.55,14 6,14 Z M6,10 C6.55,10 7,9.55 7,9 L7,7 L9,7 C9.55,7 10,6.55 10,6 C10,5.45 9.55,5 9,5 L6,5 C5.45,5 5,5.45 5,6 L5,9 C5,9.55 5.45,10 6,10 Z M17,17 L15,17 C14.45,17 14,17.45 14,18 C14,18.55 14.45,19 15,19 L18,19 C18.55,19 19,18.55 19,18 L19,15 C19,14.45 18.55,14 18,14 C17.45,14 17,14.45 17,15 L17,17 Z M14,6 C14,6.55 14.45,7 15,7 L17,7 L17,9 C17,9.55 17.45,10 18,10 C18.55,10 19,9.55 19,9 L19,6 C19,5.45 18.55,5 18,5 L15,5 C14.45,5 14,5.45 14,6 Z" fill="white"></path>
52
52
  </g>`},exit:{viewBox:"-12 -12 38 38",content:`<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" transform="translate(-5.000000, -5.000000)">
53
53
  <path d="M6,16 L8,16 L8,18 C8,18.55 8.45,19 9,19 C9.55,19 10,18.55 10,18 L10,15 C10,14.45 9.55,14 9,14 L6,14 C5.45,14 5,14.45 5,15 C5,15.55 5.45,16 6,16 Z M8,8 L6,8 C5.45,8 5,8.45 5,9 C5,9.55 5.45,10 6,10 L9,10 C9.55,10 10,9.55 10,9 L10,6 C10,5.45 9.55,5 9,5 C8.45,5 8,5.45 8,6 L8,8 Z M15,19 C15.55,19 16,18.55 16,18 L16,16 L18,16 C18.55,16 19,15.55 19,15 C19,14.45 18.55,14 18,14 L15,14 C14.45,14 14,14.45 14,15 L14,18 C14,18.55 14.45,19 15,19 Z M16,8 L16,6 C16,5.45 15.55,5 15,5 C14.45,5 14,5.45 14,6 L14,9 C14,9.55 14.45,10 15,10 L18,10 C18.55,10 19,9.55 19,9 C19,8.45 18.55,8 18,8 L16,8 Z" fill="white"></path>