@vindral/web-sdk 4.1.5-4-g2cb8ae2c → 4.1.5-6-g385d5a4e
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/{CcUOhEtj.js → BG1CcaM8.js} +1 -1
- package/{BK_nbWOA.js → DmG0degs.js} +1 -1
- package/cast-sender.d.ts +8 -0
- package/core.d.ts +8 -0
- package/core.js +1 -1
- package/legacy.d.ts +8 -0
- package/legacy.es.js +22 -17
- package/legacy.umd.js +3 -3
- package/package.json +1 -1
- package/player.d.ts +8 -0
- package/player.js +285 -284
- package/react.d.ts +8 -0
- package/{Dy3uKsWw.js → vDAUeqnu.js} +300 -295
package/legacy.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(u,S){typeof exports=="object"&&typeof module!="undefined"?S(exports):typeof define=="function"&&define.amd?define(["exports"],S):(u=typeof globalThis!="undefined"?globalThis:u||self,S(u.Vindral={}))})(this,(function(u){"use strict";var Fw=Object.create;var gn=Object.defineProperty,Gw=Object.defineProperties,kw=Object.getOwnPropertyDescriptor,Rw=Object.getOwnPropertyDescriptors;var cQ=Object.getOwnPropertySymbols;var KE=Object.prototype.hasOwnProperty,YE=Object.prototype.propertyIsEnumerable;var Pt=(u,S)=>(S=Symbol[u])?S:Symbol.for("Symbol."+u),ae=u=>{throw TypeError(u)};var hQ=(u,S,p)=>S in u?gn(u,S,{enumerable:!0,configurable:!0,writable:!0,value:p}):u[S]=p,D=(u,S)=>{for(var p in S||(S={}))KE.call(S,p)&&hQ(u,p,S[p]);if(cQ)for(var p of cQ(S))YE.call(S,p)&&hQ(u,p,S[p]);return u},V=(u,S)=>Gw(u,Rw(S)),vE=(u,S)=>gn(u,"name",{value:S,configurable:!0});var TE=(u,S)=>{var p={};for(var J in u)KE.call(u,J)&&S.indexOf(J)<0&&(p[J]=u[J]);if(u!=null&&cQ)for(var J of cQ(u))S.indexOf(J)<0&&YE.call(u,J)&&(p[J]=u[J]);return p};var Wi=u=>{var S;return[,,,Fw((S=u==null?void 0:u[Pt("metadata")])!=null?S:null)]},PE=["class","method","getter","setter","accessor","field","value","get","set"],mB=u=>u!==void 0&&typeof u!="function"?ae("Function expected"):u,Uw=(u,S,p,J,N)=>({kind:PE[u],name:S,metadata:J,addInitializer:K=>p._?ae("Already initialized"):N.push(mB(K||null))}),Te=(u,S)=>hQ(S,Pt("metadata"),u[3]),Oi=(u,S,p,J)=>{for(var N=0,K=u[S>>1],j=K&&K.length;N<j;N++)S&1?K[N].call(p):J=K[N].call(p,J);return J},OA=(u,S,p,J,N,K)=>{var j,tA,sA,oA,xt,F=S&7,$=!!(S&8),W=!!(S&16),xe=F>3?u.length+1:F?$?1:2:0,We=PE[F+5],lA=F>3&&(u[xe-1]=[]),v=u[xe]||(u[xe]=[]),VA=F&&(!W&&!$&&(N=N.prototype),F<5&&(F>3||!W)&&kw(F<4?N:{get[p](){return s(this,K)},set[p](SA){return E(this,K,SA)}},p));F?W&&F<4&&vE(K,(F>2?"set ":F>1?"get ":"")+p):vE(N,p);for(var Oe=J.length-1;Oe>=0;Oe--)oA=Uw(F,p,sA={},u[3],v),F&&(oA.static=$,oA.private=W,xt=oA.access={has:W?SA=>Nw(N,SA):SA=>p in SA},F^3&&(xt.get=W?SA=>(F^1?s:d)(SA,N,F^4?K:VA.get):SA=>SA[p]),F>2&&(xt.set=W?(SA,mg)=>E(SA,N,mg,F^4?K:VA.set):(SA,mg)=>SA[p]=mg)),tA=(0,J[Oe])(F?F<4?W?K:VA[We]:F>4?void 0:{get:VA.get,set:VA.set}:N,oA),sA._=1,F^4||tA===void 0?mB(tA)&&(F>4?lA.unshift(tA):F?W?K=tA:VA[We]=tA:N=tA):typeof tA!="object"||tA===null?ae("Object expected"):(mB(j=tA.get)&&(VA.get=j),mB(j=tA.set)&&(VA.set=j),mB(j=tA.init)&&lA.unshift(j));return F||Te(u,N),VA&&gn(N,p,VA),W?F^4?K:VA:N},I=(u,S,p)=>hQ(u,typeof S!="symbol"?S+"":S,p),sn=(u,S,p)=>S.has(u)||ae("Cannot "+p),Nw=(u,S)=>Object(S)!==S?ae('Cannot use the "in" operator on this value'):u.has(S),s=(u,S,p)=>(sn(u,S,"read from private field"),p?p.call(u):S.get(u)),n=(u,S,p)=>S.has(u)?ae("Cannot add the same private member more than once"):S instanceof WeakSet?S.add(u):S.set(u,p),E=(u,S,p,J)=>(sn(u,S,"write to private field"),J?J.call(u,p):S.set(u,p),p),d=(u,S,p)=>(sn(u,S,"access private method"),p);var ft=(u,S,p,J)=>({set _(N){E(u,S,N,p)},get _(){return s(u,S,J)}});var r=(u,S,p)=>new Promise((J,N)=>{var K=sA=>{try{tA(p.next(sA))}catch(oA){N(oA)}},j=sA=>{try{tA(p.throw(sA))}catch(oA){N(oA)}},tA=sA=>sA.done?J(sA.value):Promise.resolve(sA.value).then(K,j);tA((p=p.apply(u,S)).next())}),EA=function(u,S){this[0]=u,this[1]=S},Ee=(u,S,p)=>{var J=(j,tA,sA,oA)=>{try{var xt=p[j](tA),F=(tA=xt.value)instanceof EA,$=xt.done;Promise.resolve(F?tA[0]:tA).then(W=>F?J(j==="return"?j:"next",tA[1]?{done:W.done,value:W.value}:W,sA,oA):sA({value:W,done:$})).catch(W=>J("throw",W,sA,oA))}catch(W){oA(W)}},N=j=>K[j]=tA=>new Promise((sA,oA)=>J(j,tA,sA,oA)),K={};return p=p.apply(u,S),K[Pt("asyncIterator")]=()=>K,N("next"),N("throw"),N("return"),K},Bn=u=>{var S=u[Pt("asyncIterator")],p=!1,J,N={};return S==null?(S=u[Pt("iterator")](),J=K=>N[K]=j=>S[K](j)):(S=S.call(u),J=K=>N[K]=j=>{if(p){if(p=!1,K==="throw")throw j;return j}return p=!0,{done:!1,value:new EA(new Promise(tA=>{var sA=S[K](j);sA instanceof Object||ae("Object expected"),tA(sA)}),1)}}),N[Pt("iterator")]=()=>N,J("next"),"throw"in S?J("throw"):N.throw=K=>{throw K},"return"in S&&J("return"),N},rA=(u,S,p)=>(S=u[Pt("asyncIterator")])?S.call(u):(u=u[Pt("iterator")](),S={},p=(J,N)=>(N=u[J])&&(S[J]=K=>new Promise((j,tA,sA)=>(K=N.call(u,K),sA=K.done,Promise.resolve(K.value).then(oA=>j({value:oA,done:sA}),tA)))),p("next"),p("return"),S);var ot=(u,S,p)=>{if(S!=null){typeof S!="object"&&typeof S!="function"&&ae("Object expected");var J,N;p&&(J=S[Pt("asyncDispose")]),J===void 0&&(J=S[Pt("dispose")],p&&(N=J)),typeof J!="function"&&ae("Object not disposable"),N&&(J=function(){try{N.call(this)}catch(K){return Promise.reject(K)}}),u.push([p,J,S])}else p&&u.push([p]);return S},nt=(u,S,p)=>{var J=typeof SuppressedError=="function"?SuppressedError:function(j,tA,sA,oA){return oA=Error(sA),oA.name="SuppressedError",oA.error=j,oA.suppressed=tA,oA},N=j=>S=p?new J(j,S,"An error was suppressed during disposal"):(p=!0,j),K=j=>{for(;j=u.pop();)try{var tA=j[1]&&j[1].call(j[2]);if(j[0])return Promise.resolve(tA).then(K,sA=>(N(sA),K()))}catch(sA){N(sA)}if(p)throw S};return K()};var Zt,eI,Et,Jg,Mg,Ft,rt,wA,Xt,le,ii,Hg,Ii,iI,II,qg,Cn,gi,si,It,ct,Bi,Ci,vg,IA,Qi,jt,ht,Gt,GA,we,De,mC,gI,Kg,Yg,DA,xE,WE,OE,VE,SC,yC,ZE,SB,fC,XE,jE,ss,Bs,Cs,Qs,YA,XA,CA,QI,me,zt,oi,zE,Qn,kt,oI,nI,os,ns,aI,as,Es,Rt,EI,rs,cs,rI,ni,_E,on,dt,cI,hs,hI,ds,ls,us,dI,FC,ai,$E,nn,ye,ws,Ut,Ei,ri,ci,Nt,Ds,hi,bt,GC,BA,yB,dQ,Vi,lQ,Pe,lI,uI,_t,kC,jA,zA,di,RC,$t,wI,hA,Ar,tr,er,ir,Ir,gr,sr,Br,Cr,Qr,DI,Ss,ys,fA,fs,mI,SI,ps,UC,or,NC,fI,pI,fe,li,bC,ui,lt,MA,Fs,Gs,gt,ks,Rs,GI,Us,LC,nr,wi,Ns,kI,bs,RI,Ls,Di,pe,ug,yE,UI,Js,NI,mi,Fe,Ge,ke,Oo,Si,fE,bI,kA,LI,JI,Vo,MI,fB,pE,FE,GE,kE,Ae,_A,yi,fi,HI,Lt,uQ,wg,RE,UE,NE,bE,ut,Ms,pi,qI,vI,pA,ar,Er,KI,wQ,DQ,mQ,pB,st,Hs,Fi,YI,qs,HA,Zi,Xi,Re,te,TI,Gi,ee,PI,xI,JC,rr,ie,Ie,Ue,vs,Ks,MC,HC,cr,ge,WI,Ys,$A,Jt,ki,Bt,Ts,qC,Ps,an,wt,Ri,se,Mt,xs,En,Ws,Ne,Os,Vs,Zs,vC,hr,Xs,OI,js,VI,zs,rn,_s,Ht,$s,AB,YC,dr,TC,be,Ui,tB,eB,iB,Ni,cn,lr,PC,IB,Le,XI,LE,bi,Li,Ji,Je,_o,jI,SQ,Mi,gB,xC,ur,sB,WC,wr,OC,_I,$I,BB,CB,JE,ME,HE,Ag,tg,Hi,bA,Dt,mt,Me,eg,QB,oB,Be,TA,yQ,FB,Dr,hn,RA,PA,Ct,qi,dA,He,nB,ig,aB,Ig,xA,mr,gg,EB,sg,Sr,yr,fr,pr,dn,Ce,vi,VC,Fr,Bg,qe,Cg,vt,Kt,Qg,Qe,og,ng,ag,ZC,XC,jC,Gr,rB,Yt,LA,Ki,Qt,kr,Dg,Rr,AQ,eA,cB,hB,dB,Ke,cg,Ur,Nr,tQ,Ye,Yi,At,Ti,hg,br,Lr;const J={buffering:"_buffering_1ccif_1","buffering-fullscreen":"_buffering-fullscreen_1ccif_16",hidden:"_hidden_1ccif_25","buffering-indicator":"_buffering-indicator_1ccif_31"};class N{constructor(A){I(this,"attach",A=>{this.detach(),A.appendChild(this.element)});I(this,"attachBefore",(A,t)=>{this.detach(),A.insertBefore(this.element,t)});I(this,"detach",()=>this.element.remove());this.element=A}}const K=J.hidden,j=J.buffering,tA=J["buffering-fullscreen"],sA=J["buffering-indicator"];class oA extends N{constructor(){super(document.createElement("div"));I(this,"indicator",document.createElement("div"));I(this,"isHidden",()=>this.element.classList.contains(K));I(this,"setHidden",t=>t?this.hide():this.show());I(this,"hide",()=>this.element.classList.add(K));I(this,"show",()=>this.element.classList.remove(K));I(this,"fullscreen",t=>{t?this.element.classList.add(tA):this.element.classList.remove(tA)});this.element.className=j,this.indicator.className=sA,this.element.appendChild(this.indicator)}}class xt{constructor(A){I(this,"maxSize",0);I(this,"size",0);I(this,"buffers",[]);I(this,"_borrowedBuffers",0);I(this,"get",A=>{const t=this.buffers.shift();return this._borrowedBuffers++,this.size<A||!t?(this.buffers=[],this.size=A,new ArrayBuffer(A)):t});I(this,"reclaim",A=>{this._borrowedBuffers=Math.max(0,this._borrowedBuffers-1),!(A.byteLength<this.size)&&(this.buffers.length>=this.maxSize||this.buffers.push(A))});this.maxSize=A}get bufferSize(){return this.size}get poolSize(){return this.buffers.length}get borrowedBuffers(){return this._borrowedBuffers}}const F=()=>{};class ${constructor(){I(this,"promise");I(this,"resolved");I(this,"resolve");I(this,"reject");I(this,"pending",!0);this.promise=new Promise((A,t)=>{this.resolve=e=>{this.pending=!1,this.resolved=e,A(e)},this.reject=e=>{this.pending=!1,t(e)}}),this.promise.catch(F)}static resolved(A){const t=new $;return t.resolve(A),t}static fromPromise(A){const t=new $;return t.promise=A,A.then(e=>{t.pending=!1,t.resolved=e},e=>{t.pending=!1,t.reject(e)}),t}}class W{constructor(A=50){I(this,"maxSize");I(this,"values",[]);I(this,"push",A=>{this.isFull()&&this.pop(),this.values.push(A)});I(this,"clear",()=>void(this.values=[]));I(this,"pop",()=>this.values.shift());I(this,"peekFirst",()=>this.values[0]);I(this,"peekLast",()=>this.values[this.values.length-1]);I(this,"isFull",()=>this.values.length>=this.maxSize);I(this,"isEmpty",()=>this.values.length===0);I(this,"items",()=>this.values);I(this,"filterPop",A=>{for(;this.peekFirst()&&!A(this.peekFirst());)this.pop()});this.maxSize=A}}function xe(i){const A=new We(i);return[A,A]}class We{constructor(A){n(this,Zt);n(this,eI,new $);n(this,Et);n(this,Jg,!1);E(this,Zt,new W(A))}isFull(){return s(this,Zt).isFull()}close(){var A;(A=s(this,Et))==null||A.resolve(),E(this,Jg,!0)}abort(A){var t,e;(t=s(this,Et))==null||t.promise.catch(F),(e=s(this,Et))==null||e.reject(A)}push(A){return r(this,null,function*(){var t;s(this,Zt).isFull()&&(yield s(this,eI).promise),s(this,Zt).push(A),(t=s(this,Et))==null||t.resolve(),E(this,Et,new $)})}pop(){return r(this,null,function*(){var A;for(;!(s(this,Jg)&&s(this,Zt).isEmpty());){const t=s(this,Zt).pop();if(t)return s(this,eI).resolve(),E(this,eI,new $),t;s(this,Et)||E(this,Et,new $),yield(A=s(this,Et))==null?void 0:A.promise}})}start(A){}pull(A){return r(this,null,function*(){const t=yield this.pop();t?A.enqueue(t):A.close()})}cancel(A){this.abort(new Error(A))}next(){return r(this,null,function*(){const A=yield this.pop().catch(()=>{});return A?{done:!1,value:A}:{done:!0,value:void 0}})}return(){return this.close(),Promise.resolve({done:!0,value:void 0})}[Symbol.asyncIterator](){return this}}Zt=new WeakMap,eI=new WeakMap,Et=new WeakMap,Jg=new WeakMap;function lA(i,A){if(!i)throw new Error(A)}function v(i){return typeof BigInt=="function"?BigInt(i):i}class VA{constructor(A,t=0){n(this,Mg);n(this,Ft);n(this,rt);I(this,"position",()=>s(this,rt));I(this,"peekBit",()=>this.getBit(s(this,Ft),s(this,rt)));I(this,"readBit",()=>{const A=this.peekBit();return ft(this,rt)._++,A});I(this,"readBits",A=>{let t=0;for(let e=0;e<A;e++)t=t<<1|(this.getBit(s(this,Ft),ft(this,rt)._++)?1:0);return t});I(this,"remainingBits",()=>s(this,Ft).byteLength*8-s(this,rt));I(this,"readSignedExpGolomb",()=>{const A=this.readUnsignedExpGolomb();return A&1?(A+1)/2:-(A/2)});I(this,"readUnsignedExpGolomb",()=>{let A=0;for(;this.getBit(s(this,Ft),ft(this,rt)._++)===0;)A++;let t=1<<A;for(let e=A-1;e>=0;e--)t|=this.getBit(s(this,Ft),ft(this,rt)._++)<<e;return t-1});I(this,"getBit",(A,t)=>{if(A.byteLength*8<=t)throw new Error("BitReader: Out of bounds");return A[t>>3]>>7-(t&7)&1});E(this,Mg,A),E(this,Ft,new Uint8Array(s(this,Mg))),E(this,rt,t)}bytes(){return s(this,Ft)}}Mg=new WeakMap,Ft=new WeakMap,rt=new WeakMap;const Oe=(i,A,t)=>{let e=0;for(let g=A;g<=t;g++)if(g===A){const B=i[g];e+=B&127,B&128&&(e-=128)}else e=e*256+i[g];return e};class SA{constructor(A){n(this,wA);n(this,Xt);n(this,le);E(this,Xt,A),E(this,le,new DataView(A.buffer,A.byteOffset,A.byteLength)),E(this,wA,0)}position(){return s(this,wA)}byteOffset(){return s(this,Xt).byteOffset+s(this,wA)}buffer(){return s(this,Xt)}remaining(){return s(this,Xt).length-s(this,wA)}readUint8(){const A=s(this,le).getUint8(s(this,wA));return E(this,wA,s(this,wA)+1),A}readUint24(){const A=s(this,le).getUint32(s(this,wA))>>8&16777215;return E(this,wA,s(this,wA)+3),A}readUint16(){const A=s(this,le).getUint16(s(this,wA));return E(this,wA,s(this,wA)+2),A}readUint32(){const A=s(this,le).getUint32(s(this,wA));return E(this,wA,s(this,wA)+4),A}readUint64(){const A=Oe(s(this,Xt),s(this,wA),s(this,wA)+7);return E(this,wA,s(this,wA)+8),A}readBytes(A){const t=s(this,Xt).subarray(s(this,wA),s(this,wA)+A);return E(this,wA,s(this,wA)+A),t}readRemaining(){return this.readBytes(this.remaining())}readUtf8String(){const A=[];let t;for(;(t=this.readUint8())!==0&&(A.push(t),this.remaining()!=0););return new TextDecoder().decode(new Uint8Array(A))}}wA=new WeakMap,Xt=new WeakMap,le=new WeakMap;class mg{constructor(A=100,t=100){I(this,"resizeSteps");I(this,"internalBuffer");I(this,"view");I(this,"uint8");I(this,"_position",0);I(this,"_end",0);this.resizeSteps=t,this.internalBuffer=new ArrayBuffer(A),this.view=new DataView(this.internalBuffer),this.uint8=new Uint8Array(this.internalBuffer)}position(){return this._position}seek(A){this._position=Math.max(0,Math.min(this._end,A))}seekToEnd(){this._position=this._end}writeUint8(A){this.writeAndMove(A,1)}writeUint16(A){this.writeAndMove(A,2)}writeUint24(A){this.writeAndMove(A,3)}writeUint32(A){this.writeAndMove(A,4)}writeUint64(A){const t=Math.floor(A/4294967296),e=(A&4294967295)>>>0;this.writeUint32(t),this.writeUint32(e)}writeUint32At(A,t){this.view.setUint32(A,t)}writeBytes(A){this.resizeIfNeeded(this.position()+A.byteLength),this.uint8.set(A,this.position()),this._position+=A.byteLength,this._end=Math.max(this._end,this._position)}buffer(){return this.internalBuffer.slice(0,this._end)}write(A,t){switch(this.resizeIfNeeded(this.position()+t),t){case 1:this.view.setUint8(this.position(),A);break;case 2:this.view.setUint16(this.position(),A);break;case 3:this.view.setUint8(this.position(),A>>16&255),this.view.setUint8(this.position()+1,A>>8&255),this.view.setUint8(this.position()+2,A&255);break;case 4:this.view.setUint32(this.position(),A);break}}writeAndMove(A,t){this.write(A,t),this._position+=t,this._end=Math.max(this._end,this._position)}resizeIfNeeded(A){if(A>this.internalBuffer.byteLength){const t=new ArrayBuffer(A+this.resizeSteps),e=new Uint8Array(t);e.set(this.uint8),this.internalBuffer=t,this.view=new DataView(this.internalBuffer),this.uint8=e}}}function ln(i){const A=atob(i),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t.buffer}function Sg(){const i=self.MediaSource,A=self.ManagedMediaSource;return i!=null?i:A}const Jr=/(android|bbd+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up.(browser|link)|vodafone|wap|windows ce|xda|xiino\/i.test(a)||\/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-\//i,qA=navigator.userAgent.toLowerCase(),Mr=Jr.test(qA),Hr=()=>{const i=document.createElement("video");return i.canPlayType("application/vnd.apple.mpegURL")!==""||i.canPlayType("audio/mpegurl")!==""},qr=()=>{try{if(typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function"){const i=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(i instanceof WebAssembly.Module)return new WebAssembly.Instance(i)instanceof WebAssembly.Instance}}catch(i){return!1}return!1},vr=()=>qA.indexOf("CrKey")!==-1,un=()=>navigator.platform==="MacIntel"&&navigator.maxTouchPoints===0,GB=()=>navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,Kr=()=>qA.indexOf("iphone")>=0&&qA.indexOf("like iphone")<0||qA.indexOf("ipad")>=0&&qA.indexOf("like ipad")<0||qA.indexOf("ipod")>=0&&qA.indexOf("like ipod")<0||GB(),Yr=()=>{var i,A;return GB()?!1:(A=(i=Sg())==null?void 0:i.isTypeSupported('audio/mp4; codecs="opus"'))!=null?A:!1},Tr=()=>/^(?!.*chrome).*safari/i.test(qA);function Pr(){var i,A;if(/(iPhone|iPod|iPad)/i.test(qA))return(A=(i=qA==null?void 0:qA.match(/OS [\d_]+/i))==null?void 0:i[0])==null?void 0:A.substring(3).split("_").map(t=>parseInt(t))[0]}function xr(){var i,A;if(/^((?!chrome|android).)*safari/i.test(qA))return(A=(i=qA.match(/version\/([\d.]+)/))==null?void 0:i[1])==null?void 0:A.split(".").map(t=>parseInt(t))[0]}const fQ=()=>{var t,e;const i=!!Sg();let A=!1;return i&&(A=Yr()),{isMobile:Mr,supportsMp4Opus:A,supportsMediaSource:i,supportsHls:Hr(),supportsWebAssembly:qr(),platform:{iosVersion:(t=Pr())!=null?t:Number.MAX_SAFE_INTEGER,safariVersion:(e=xr())!=null?e:Number.MAX_SAFE_INTEGER,isIpadOS:GB(),isMacOS:un(),isIOS:Kr()}}};class ji{constructor(A,t,e){I(this,"onSuccess");I(this,"onError");I(this,"doExecute");this.doExecute=A,this.onSuccess=t,this.onError=e}execute(A){try{this.doExecute(A),this.onSuccess()}catch(t){this.onError(t)}}}const Wt=i=>i.reduce((A,t)=>A+t,0)/i.length,re=i=>({last:i[i.length-1]||0,average:i.length===0?0:Wt(i),max:i.length===0?0:Math.max(...i),min:i.length===0?0:Math.min(...i)}),Wr=i=>{let A=0,t=0,e=0,g=0,B=0;for(let a=0;a<i.length;a++){const{x:c,y:h}=i[a];A+=c,t+=h,e+=c*h,g+=c*c,B+=h*h}const C=(i.length*e-A*t)/(i.length*g-A*A),Q=(t-C*A)/i.length,o=((i.length*e-A*t)/Math.sqrt((i.length*g-A*A)*(i.length*B-t*t)))**2;return{slope:C,intercept:Q,r2:o,predict:a=>C*(i.length+a)+Q}};class Or{constructor(A=10){I(this,"rates");I(this,"_total",0);I(this,"accumulatedValues",0);I(this,"lastTickTime",Date.now());I(this,"add",A=>{this.accumulatedValues+=A,this._total+=A});I(this,"tick",()=>{const A=this.accumulatedValues/((Date.now()-this.lastTickTime)/1e3);this.rates.push(A),this.accumulatedValues=0,this.lastTickTime=Date.now()});this.rates=new W(A)}get total(){return this._total}get average(){return this.rates.isEmpty()?0:Wt(this.rates.items())}get minMaxAverage(){return re(this.rates.items())}}const Ve=(i,A)=>{if(i===A)return!0;if(i==null||typeof i!="object"||A==null||typeof A!="object")return!1;let t=0,e=0;for(const g in i)t+=1;for(const g in A)if(e+=1,!(g in i)||!Ve(i[g],A[g]))return!1;return t==e};class it{constructor(){I(this,"listeners",{})}emit(A,t){const e=this.listeners[A];e&&(this.listeners[A]=e.filter(B=>!B.once),e.map(B=>B.fn(t)).map(B=>typeof B=="function"&&(B==null?void 0:B())))}off(A,t){const e=this.listeners[A];e&&(this.listeners[A]=e.filter(g=>g.fn!==t))}on(A,t){this.add(A,t,!1)}once(A,t){this.add(A,t,!0)}reset(){this.listeners={}}add(A,t,e){const g=this.listeners[A],B={fn:t,once:e};g?g.push(B):this.listeners[A]=[B]}}const pQ=1e3,FQ=pQ*1e3,wn=FQ*1e3,GQ=(i,A,t)=>i%A===0?i/A:(i/A).toFixed(t),Vr=(i,A=1)=>i>=wn?`${GQ(i,wn,A)} Gbit/s`:i>=FQ?`${GQ(i,FQ,A)} Mbit/s`:i>=pQ?`${GQ(i,pQ,A)} Kbit/s`:`${i} bit/s`,Zr=({width:i,height:A})=>`${i}x${A}`,Xr=i=>i%1e3===0?`${i/1e3} kHz`:i>1e3?`${(i/1e3).toFixed(1)} kHz`:`${i} Hz`,Dn=["off","error","warn","info","debug","trace"],jr={OFF:"off"},ue=class ue{constructor({context:A,logLevel:t,debug:e}){n(this,ii,new Map);n(this,Hg,"");n(this,Ii,!1);n(this,iI,"off");I(this,"trace",(...A)=>{});I(this,"debug",(...A)=>{});I(this,"info",(...A)=>{});I(this,"warn",(...A)=>{});I(this,"error",(...A)=>{});I(this,"table",(...A)=>{});I(this,"count",(...A)=>{});E(this,Hg,A),E(this,iI,t),E(this,Ii,e||!1),this.setLevel(t),this.setDebug(s(this,Ii))}setDebug(A){E(this,Ii,A);for(const[t,e]of s(this,ii))e.setDebug(A);A?(this.table=console.table.bind(console),this.count=console.count.bind(console)):(this.table=()=>{},this.count=()=>{})}setLevel(A){E(this,iI,A);for(const[e,g]of s(this,ii))g.setLevel(A);const t=Dn.indexOf(A);for(const[e,g]of Dn.entries())g!=="off"&&(e<=t?this[g]=console[g].bind(console,"%c%s %c%s","font-weight:bold;",g.toUpperCase(),"font-weight:normal;",s(this,Hg)):this[g]=()=>{})}createContext(A){const t=s(this,ii).get(A);if(!t){const e=new ue({context:`${A}`,logLevel:s(this,iI),debug:s(this,Ii)});return s(this,ii).set(A,e),e}return t}static get(){return s(ue,II)||E(ue,II,new ue({context:"Vindral",logLevel:"off"})),s(ue,II)}};ii=new WeakMap,Hg=new WeakMap,Ii=new WeakMap,iI=new WeakMap,II=new WeakMap,n(ue,II);let UA=ue;function ZA(i){const A=UA.get().createContext(i.context);return function(e,g){const B=String(g.name);function C(...Q){i.enter&&A[i.enter](`Enter '${B}'`,D({},Q));try{const o=e.call(this,...Q);return o instanceof Promise?o.then(a=>{i.return&&A[i.return](`Return '${B}'`,a)}).catch(a=>{i.error&&A[i.error](`Error '${B}'`,a)}):i.return&&A[i.return](`Return '${B}'`,o),o}catch(o){throw i.error&&A[i.error](`Error '${B}'`,o),o}}return C}}function pt(){return typeof Symbol.asyncDispose!="symbol"&&Object.defineProperty(Symbol,"asyncDispose",{value:Symbol.for("asyncDispose")}),Symbol.asyncDispose}function mn(){return typeof Symbol.dispose!="symbol"&&Object.defineProperty(Symbol,"dispose",{value:Symbol.for("dispose")}),Symbol.dispose}class zr{constructor(A,t){n(this,qg);I(this,"value");I(this,"unlocker");this.value=A,this.unlocker=t}unlocked(){var A;return(A=this.unlocker)==null?void 0:A.promise}[mn()](){d(this,qg,Cn).call(this)}[Symbol.dispose](){d(this,qg,Cn).call(this)}}qg=new WeakSet,Cn=function(){this.unlocker.resolve(this.value)};class _r{constructor(A){n(this,gi);n(this,si,new $);E(this,gi,A),s(this,si).resolve(A)}unsafeValue(){return s(this,gi)}isLocked(){return s(this,si).pending}lock(){return r(this,null,function*(){const A=new $;A.promise.then(e=>{E(this,gi,e)}).catch(F);const t=s(this,si).promise.then(()=>A);return E(this,si,A),yield t,new zr(s(this,gi),A)})}}gi=new WeakMap,si=new WeakMap;class vA{constructor(A){n(this,It);n(this,ct);E(this,It,A),E(this,ct,new $)}isClosed(){var A;return!((A=s(this,ct))!=null&&A.pending)}current(){return s(this,It)}value(){var A;return[s(this,It),(A=s(this,ct))==null?void 0:A.promise]}update(A){var t;if(!((t=s(this,ct))!=null&&t.pending))throw new Error("ObservableValue is closed");E(this,It,A instanceof Function?A(s(this,It)):A),s(this,ct).resolve(s(this,It)),E(this,ct,new $)}close(){var A;(A=s(this,ct))==null||A.resolve(s(this,It)),E(this,ct,void 0)}waitFor(A){return r(this,null,function*(){if(A(s(this,It)))return s(this,It);for(;;){const[t,e]=this.value();if(!e)throw new Error("ObservableValue was closed while waiting for condition");const g=yield e;if(A(g))return g}})}[Symbol.asyncIterator](){return Ee(this,null,function*(){for(;;){const[A,t]=this.value();if(yield A,!t)return;yield new EA(t)}})}}It=new WeakMap,ct=new WeakMap;const Sn=(i,A)=>{const t=D({},i);return typeof t!="object"||A.forEach(e=>{delete t[e]}),t},DC=class DC{constructor(){I(this,"pendingTimeouts",new Set);I(this,"pendingIntervals",new Set);I(this,"clearTimeout",A=>{this.pendingTimeouts.delete(A)&&window.clearTimeout(A)});I(this,"clearInterval",A=>{this.pendingIntervals.delete(A)&&window.clearInterval(A)});I(this,"setTimeout",(A,t,...e)=>{const g=window.setTimeout(()=>{A(...e),this.clearTimeout(g)},t);return this.pendingTimeouts.add(g),g});I(this,"setInterval",(A,t,...e)=>{const g=window.setInterval(()=>{A(...e)},t);return this.pendingIntervals.add(g),g});I(this,"unload",()=>{this.pendingIntervals.forEach(this.clearInterval),this.pendingTimeouts.forEach(this.clearTimeout)})}};I(DC,"create",()=>new DC);let NA=DC;const Ze=(i,A=Date.now())=>{const t=i.length;if(t>0){const e=t-1,g=i[e];g.end||(g.end=A)}},zi=(i,A=Date.now())=>{Ze(i),i.push({start:A})},_i=i=>i.reduce((A,t)=>{var e;return A+(((e=t.end)!=null?e:Date.now())-t.start)},0),yn=(i,A,t=Date.now())=>i.reduce((e,g)=>{var Q;const B=Math.max(t-A,g.start),C=(Q=g.end)!=null?Q:t;return Math.max(0,C-B)+e},0);function fn(i){try{return i()}catch(A){return A}}const pn=i=>{try{return JSON.parse(i)}catch(A){return}},Fn=()=>{const i=[...Array(256).keys()].map(t=>t.toString(16).padStart(2,"0")),A=crypto.getRandomValues(new Uint8Array(16));return A[6]=A[6]&15|64,A[8]=A[8]&63|128,[...A.entries()].map(([t,e])=>[4,6,8,10].includes(t)?`-${i[e]}`:i[e]).join("")},ce=i=>r(null,null,function*(){return new Promise(A=>setTimeout(A,i))}),kQ=(t,...e)=>r(null,[t,...e],function*(i,A=new Error("Timeout")){return new Promise((g,B)=>setTimeout(()=>B(A),i))}),$r=(i,A)=>r(null,null,function*(){throw yield i,new Error(A)});class Gn extends it{constructor(t){super();I(this,"config");I(this,"hlsUrl");I(this,"element");I(this,"connectingTimeout");I(this,"castingAvailable",!1);I(this,"updateAuthenticationToken",t=>{this.config.authenticationToken=t,this.hlsUrl=this.getHlsUrl(),this.castingAvailable&&(this.element.src=this.hlsUrl)});I(this,"unload",()=>{this.element&&(this.element.removeEventListener("webkitplaybacktargetavailabilitychanged",this.onAirPlayAvailable),this.element.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",this.onAirPlayPlaybackChanged),this.element.remove())});I(this,"onAirPlayAvailable",t=>{switch(t.availability){case"available":{this.castingAvailable=!0,this.element.src!==this.hlsUrl&&this.checkHlsUrl(this.hlsUrl).then(g=>{g&&(this.element.src=this.hlsUrl,this.emit("available"))});break}case"not-available":this.castingAvailable=!1;break}});I(this,"onAirPlayPlaybackChanged",()=>{window.clearTimeout(this.connectingTimeout),this.element.webkitCurrentPlaybackTargetIsWireless?(this.emit("connected"),this.element.style.display="block",this.element.paused&&this.element.play()):(this.emit("disconnected"),this.element.pause(),this.element.src="",this.element.src=this.hlsUrl,this.element.style.display="none")});this.config=t,this.hlsUrl=this.getHlsUrl(),this.element=document.createElement("video"),this.element.style.position="absolute",this.element.style.top="0",this.element.style.bottom="0",this.element.style.left="0",this.element.style.right="0",this.element.style.width="100%",this.element.style.height="100%",this.element.style.zIndex="1001",this.element.style.display="none",this.element.id="vindral-airplay-element",this.element.slot="overlay",this.element.playsInline=!0,this.element.controls=!0,this.element.preload="metadata",this.element.addEventListener("webkitplaybacktargetavailabilitychanged",this.onAirPlayAvailable),this.element.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",this.onAirPlayPlaybackChanged),this.config.container.appendChild(this.element)}get casting(){return this.element.webkitCurrentPlaybackTargetIsWireless}set channelId(t){}showPlaybackTargetPicker(){this.element.paused&&(this.element.play(),this.connectingTimeout=window.setTimeout(()=>{this.casting||(this.element.pause(),this.element.src="",this.element.src=this.hlsUrl)},3e4)),this.element.webkitShowPlaybackTargetPicker()}static isAirPlaySupported(){return!!window.WebKitPlaybackTargetAvailabilityEvent}getHlsUrl(){const t=new URL(`/api/hls?channelId=${this.config.channelId}`,this.config.url);return this.config.authenticationToken&&t.searchParams.set("authenticationToken",this.config.authenticationToken),t.toString()}checkHlsUrl(t){return r(this,null,function*(){try{return(yield fetch(t,{method:"HEAD"})).ok}catch(e){return!1}})}}class kn extends it{constructor(t){super();I(this,"state","not casting");I(this,"config");I(this,"unloaded",!1);I(this,"updateAuthenticationToken",t=>{this.config&&(this.config.options.authenticationToken=t,this.send({type:"updateAuthToken",token:t}))});I(this,"unload",()=>{var t;this.unloaded=!0,(t=this.getSession())==null||t.removeMessageListener("urn:x-cast:com.vindral.castdata",this.onMessage)});I(this,"init",()=>r(this,null,function*(){return new Promise((t,e)=>{let g=!1;const B=setTimeout(()=>{g=!0,e()},1e4);window.__onGCastApiAvailable=C=>{if(g){g=!1;return}if(clearTimeout(B),!C)return e();setTimeout(()=>{try{this.onGCastApiAvailable(),t()}catch(Q){e()}},1e3)},this.castLibrariesAdded()&&window.cast?window.__onGCastApiAvailable(!0):this.verifyCastLibraries()})}));I(this,"start",()=>r(this,null,function*(){var t;yield(t=this.getInstance())==null?void 0:t.requestSession()}));I(this,"stop",()=>{var t;(t=this.getSession())==null||t.endSession(!0)});I(this,"getReceiverName",()=>{var t,e;return((e=(t=this.getSession())==null?void 0:t.getCastDevice())==null?void 0:e.friendlyName)||void 0});I(this,"onGCastApiAvailable",()=>{var B;const t=this.getInstance();if(!t)throw"cast context should exist";const e=t.getSessionState(),g=((B=this.config)==null?void 0:B.receiverApplicationId)||"A5452297";t.setOptions({receiverApplicationId:g,autoJoinPolicy:chrome.cast.AutoJoinPolicy.TAB_AND_ORIGIN_SCOPED,resumeSavedSession:!0}),t.addEventListener(cast.framework.CastContextEventType.SESSION_STATE_CHANGED,this.onSessionStateChanged),e===cast.framework.SessionState.SESSION_STARTED&&setTimeout(()=>{this.state="casting",this.emit("resumed")})});I(this,"send",t=>{var e;(e=this.getSession())==null||e.sendMessage("urn:x-cast:com.vindral.castdata",t)});I(this,"onMessage",(t,e)=>{if(t==="urn:x-cast:com.vindral.castdata")try{const g=JSON.parse(e);switch(g.type){case"metadata":this.emit("metadata",g.metadata);break;case"serverWallclockTime":this.emit("server wallclock time",g.serverWallclockTime);break;default:break}}catch(g){}});I(this,"onSessionStarted",()=>{var t;(t=this.getSession())==null||t.addMessageListener("urn:x-cast:com.vindral.castdata",this.onMessage),this.send({type:"start",config:this.config})});I(this,"onSessionStateChanged",t=>{if(!this.unloaded)switch(t.sessionState){case cast.framework.SessionState.SESSION_START_FAILED:this.state="not casting",this.emit("failed");break;case cast.framework.SessionState.SESSION_ENDED:this.state="not casting",this.emit("disconnected");break;case cast.framework.SessionState.SESSION_ENDING:break;case cast.framework.SessionState.SESSION_RESUMED:this.onSessionStarted(),this.state="casting",this.emit("resumed");break;case cast.framework.SessionState.SESSION_STARTED:this.onSessionStarted(),this.state="casting",this.emit("connected");break;case cast.framework.SessionState.SESSION_STARTING:break}});I(this,"getInstance",()=>{var t;return(t=window.cast)==null?void 0:t.framework.CastContext.getInstance()});I(this,"getSession",()=>{var t;return(t=this.getInstance())==null?void 0:t.getCurrentSession()});I(this,"castLibrariesAdded",()=>!!(document.querySelector("#vindralCastFrameworkLib")&&document.querySelector("#vindralCastSenderLib")));I(this,"verifyCastLibraries",()=>{if(this.castLibrariesAdded())return;const t=document.createElement("script");t.type="text/javascript",t.id="vindralCastFrameworkLib",t.src="//www.gstatic.com/cast/sdk/libs/sender/1.0/cast_framework.js",document.head.appendChild(t);const e=document.createElement("script");e.type="text/javascript",e.id="vindralCastSenderLib",e.src="//www.gstatic.com/cv/js/sender/v1/cast_sender.js",document.head.appendChild(e)});this.config=t}get casting(){return this.state==="casting"}get volume(){var t,e;return(e=(t=this.getSession())==null?void 0:t.getVolume())!=null?e:0}set volume(t){var e;(e=this.getSession())==null||e.setVolume(t)}get language(){var t,e;return(e=(t=this.config)==null?void 0:t.options)==null?void 0:e.language}set language(t){this.config&&(this.config.options.language=t,this.send({type:"setLanguage",language:t}))}get channelId(){var t;return((t=this.config)==null?void 0:t.options.channelId)||""}set channelId(t){this.config&&(this.config.options.channelId=t,this.send({type:"setChannelId",channelId:t}))}}const RQ=i=>{switch(i){case"h264":case"av1":return"video";case"aac":case"opus":case"mp3":return"audio";case"webvtt":return"text";default:throw new Error("Unknown codec")}};function UQ(i){if(i.startsWith("opus"))return"opus";if(i.startsWith("mp4a"))return"aac";if(i.startsWith("avc1"))return"h264";if(i.startsWith("av01"))return"av1";if(i.startsWith("webvtt"))return"webvtt"}function Rn(i){return!(typeof i.edges[0]=="string"||i.channels[0]&&!("catalog"in i.channels[0]))}function Un(i){return i.tracks.filter(A=>!!A.codec).filter(A=>UQ(A.codec||"")).map((A,t)=>{const e=A.codec,g=A.bitrate;lA(e,"codec is required"),lA(g!=null,"bitrate is required");const B=UQ(e);if(lA(B,"codec is required"),RQ(B)==="audio"){const C=A.samplerate||0,Q=A.channelConfig==="stereo"?2:1;return{track:A,id:t,codec:B,codecString:e,bitRate:g,channels:Q,sampleRate:C,language:A.language}}return RQ(B)==="text"?{track:A,id:t,bitRate:0,codec:B,kind:"subtitles",codecString:e,label:A.label,language:A.language}:(lA(A.width,"width is required"),lA(A.height,"width is required"),lA(A.framerate,"framerate is required"),{track:A,id:t,codec:B,bitRate:g,codecString:e,width:A.width,height:A.height,frameRate:A.framerate})}).sort((A,t)=>A.bitRate-t.bitRate)}const Xe=i=>"width"in i&&typeof i.width=="number",je=i=>"sampleRate"in i&&typeof i.sampleRate=="number",ze=i=>{switch(i.codec){case"opus":return'audio/mp4; codecs="opus"';case"mp3":return"audio/mpeg";case"webvtt":return"text/vtt";case"aac":return i.codecString?`audio/mp4; codecs="${i.codecString}"`:"audio/mp4";case"h264":return i.codecString?`video/mp4; codecs="${i.codecString}"`:"video/mp4";case"av1":return i.codecString?`video/mp4; codecs="${i.codecString}"`:"video/mp4"}},he=()=>Number.MAX_SAFE_INTEGER,kB=()=>({width:Number.MAX_SAFE_INTEGER,height:Number.MAX_SAFE_INTEGER}),Nn=i=>!(typeof i!="object"||i===null||!("type"in i)),Ac={sizeBasedResolutionCapEnabled:!0,pictureInPictureEnabled:!0,abrEnabled:!0,burstEnabled:!1,mseEnabled:!0,mseOpusEnabled:!0,muted:!1,minBufferTime:1500,maxBufferTime:1500,logLevel:jr.OFF,maxSize:kB(),maxVideoBitRate:he(),maxAudioBitRate:he(),maxInitialBitRate:2.5*1e3*1e3,tags:[],media:"audio+video",poster:!0,reconnectHandler:i=>i.reconnectRetries<30,iosWakeLockEnabled:!1,telemetryEnabled:!0,iosMediaElementEnabled:!1,pauseSupportEnabled:!0,advanced:{wasmDecodingConstraint:{bitRate:Number.MAX_SAFE_INTEGER,width:1280,height:1280}},videoCodecs:["av1","h264"],webtransportEnabled:!0},bn="connection_failed",Ln="connection_failed_will_not_attempt_again",Jn="authentication_error",Mn="authentication_expired",Hn="channel_not_found",qn="no_incoming_data_error",vn="connection_inactivity",tc="missing_init_segment",ec="no_track_context",ic="invalid_track_context_state",Kn="disconnected_by_edge",Ic="decoder_error",gc="audio_player_error",sc="media_source_error",Bc="webgl_context_lost_error",Cc="access_forbidden",Qc="channel_switch_failed",oc="drm_error";class x extends Error{constructor(t,e,g={}){super(t);I(this,"props");I(this,"extra",{});I(this,"code",()=>this.props.code);I(this,"isFatal",()=>this.props.isFatal);I(this,"source",()=>this.props.source);I(this,"type",()=>{var t;return(t=this.props.type)!=null?t:"external"});I(this,"toStringifiable",()=>{var g;const t=this.source(),e=t instanceof Error?t.stack:this.stack;return V(D({},this.extra),{code:this.props.code,isFatal:this.props.isFatal,type:this.props.type,message:this.message,sourceMessage:(g=this.source())==null?void 0:g.message,stack:e})});this.props=e,this.extra=g,Object.setPrototypeOf(this,new.target.prototype)}}const nc=(i,A)=>new x("MediaElement Error",{isFatal:i,code:"media_element_error",source:A},{mediaErrorCode:A.code}),Yn=(i,A)=>new x("Decoder Error",{isFatal:i,code:Ic,source:A,type:"internal"}),Tn=(i,A)=>new x("Audio Player Error",{isFatal:i,code:gc,source:A,type:"internal"}),ac=(i,A)=>new x(`No init segment for rendition id ${i} for channel ${A}`,{isFatal:!1,code:tc,type:"internal"}),Pn=(i,A,t,e)=>new x("MediaSource Error",{isFatal:i,code:sc,source:A,type:"internal"},{type:e,consecutiveErrorsCount:t}),RB=(i,A)=>new x(`No track context for ${i}${A?`, rendition id ${A}`:""}`,{isFatal:!1,code:ec,type:"internal"}),Ec=(i,A)=>new x(`Track context is in an invalid state for ${i}${A?`, rendition id ${A}`:""}`,{isFatal:!1,code:ic,type:"internal"}),rc=()=>new x("Web Audio Context resume timeout",{isFatal:!1,code:"web_audio_context_resume_timeout"}),yg=i=>new x("Disconnected From Edge Server",{type:"external",source:i,isFatal:!1,code:Kn}),UB=i=>new x("Authentication Failed",{isFatal:!0,code:Jn,source:i}),cc=i=>new x("Authentication Expired",{isFatal:!0,code:Mn,source:i}),hc=(i,A)=>new x("Connection closed due to inactivity",{isFatal:!1,code:vn,source:A,type:i}),xn=(i,A)=>new x("Channel not found",{isFatal:!1,code:Hn,source:A,type:i}),dc=i=>new x("No Incoming Data",{isFatal:!1,code:qn,source:i}),lc=i=>new x("Connection attempt failed",{isFatal:!1,code:bn,source:i}),Wn=()=>new x("Connection failed - no more reconnect attempts",{isFatal:!0,code:Ln}),uc=i=>new x("WebGL Context Lost",{isFatal:!1,code:Bc,source:i,type:"internal"}),On=i=>new x(i,{isFatal:!0,code:Cc}),Vn=i=>new x(`Channel switch to '${i}' failed`,{isFatal:!1,code:Qc}),Zn=(i,A=!1,t)=>new x(i,{isFatal:A,code:oc,source:t});class NB{constructor(A,t,e,g){I(this,"keySystem");I(this,"licenseServerUrl");I(this,"certificate");I(this,"headers",{});I(this,"queryParams",{});n(this,Bi);n(this,Ci);E(this,Bi,t),this.keySystem=A,this.licenseServerUrl=e,this.certificate=g}get statistics(){return{keySystem:s(this,Bi).keySystem,licenseServerUrl:this.licenseServerUrl,mediaKeySystemConfiguration:s(this,Bi).getConfiguration()}}getMediaKeys(){return r(this,null,function*(){return s(this,Ci)?s(this,Ci):(E(this,Ci,yield s(this,Bi).createMediaKeys()),s(this,Ci))})}requestLicense(A){return r(this,null,function*(){const t=new URL(this.licenseServerUrl);for(const[B,C]of Object.entries(this.queryParams))t.searchParams.append(B,C);const e=yield fetch(t,{method:"POST",body:A,headers:D({"Content-Type":"application/octet-stream"},this.headers)});if(!e.ok)throw new Error(`Failed to fetch license: ${e.statusText}`);return yield e.arrayBuffer()})}}Bi=new WeakMap,Ci=new WeakMap;function Xn(i){const A=window.atob(i.replace(/-/g,"+").replace(/_/g,"/"));let t="";for(let e=0;e<A.length;e++)t+=("0"+A.charCodeAt(e).toString(16)).substr(-2);return t}function wc(i){let A="";for(let t=0;t<i.length;t+=2)A+=String.fromCharCode(parseInt(i.substr(t,2),16));return window.btoa(A).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Dc(i,A){if(i.byteLength!==A.byteLength)return!1;const t=new Uint8Array(i),e=new Uint8Array(A);for(let g=0;g<t.length;g++)if(t[g]!==e[g])return!1;return!0}class mc extends NB{constructor(t,e){super("clearkey",t,"");n(this,vg);E(this,vg,e)}handleLicenseRequest(t){const e=new Uint8Array(t),g=String.fromCharCode(...e),B=JSON.parse(g),C=[];for(let a=0;a<B.kids.length;a++){const c=B.kids[a];if(c){const h=Xn(c).toLowerCase(),l=s(this,vg)[h];l&&C.push({kty:"oct",alg:"A128KW",kid:c,k:wc(l)})}}const Q=JSON.stringify({keys:C,type:B.type});return new TextEncoder().encode(Q)}}vg=new WeakMap;const jn={playready:["150","2000","3000"],widevine:["SW_SECURE_CRYPTO","SW_SECURE_DECODE","HW_SECURE_CRYPTO","HW_SECURE_DECODE","HW_SECURE_ALL"],fairplay:[""],clearkey:[""]},NQ={initDataTypes:["cenc"],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42c01f"'}]},Sc={fairplay:{keySystem:"com.apple.fps",supportedConfig:{initDataTypes:["sinf"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42c01f"'}]}},playready:{keySystem:"com.microsoft.playready",supportedConfig:NQ},widevine:{keySystem:"com.widevine.alpha",supportedConfig:NQ},clearkey:{keySystem:"org.w3.clearkey",supportedConfig:NQ}},zn=(i,A)=>r(null,null,function*(){return navigator.requestMediaKeySystemAccess(i,[A]).catch(()=>{})}),_n=(i,A,t,e,g,B)=>r(null,null,function*(){let C;for(const Q of e){const o=t==null?void 0:t.map(c=>V(D({},c),{robustness:Q,contentType:B?`${g==="audioCapabilities"?"audio/mp4":"video/mp4"}; codecs="${B}"`:c.contentType}));if(!(yield zn(i,{initDataTypes:A,[g]:o})))break;C=o}return C}),yc=(i,A,t,e)=>r(null,null,function*(){const{keySystem:g,supportedConfig:B}=Sc[i],{initDataTypes:C,videoCapabilities:Q,audioCapabilities:o}=B,a=e==null?void 0:e[i],c=(a==null?void 0:a.videoRobustness)||jn[i],h=(a==null?void 0:a.audioRobustness)||jn[i],[l,m]=yield Promise.all([_n(g,C,Q,c,"videoCapabilities",A),_n(g,C,o,h,"audioCapabilities",t)]);return!l&&!m?void 0:yield zn(g,{initDataTypes:C,videoCapabilities:l,audioCapabilities:m})}),fc=(i,A,t,e)=>r(null,null,function*(){let g;for(const B of i)if(g=yield yc(B,A,t,e),g)return{keySystem:B,mediaKeySystemAccess:g}});class pc extends NB{constructor(A,t,e){super("fairplay",A,t,e)}}const Fc=i=>{var Q,o,a,c;const A=String.fromCharCode(...new Uint16Array(i)),t=new window.DOMParser().parseFromString(A,"application/xml"),e=t.getElementsByTagName("HttpHeaders")[0];let g={};if(e){const h=e.getElementsByTagName("name"),l=e.getElementsByTagName("value");for(let m=0;m<h.length;m++){const y=(Q=h[m])==null?void 0:Q.childNodes[0],f=(o=l[m])==null?void 0:o.childNodes[0];y!=null&&y.nodeValue&&f&&f.nodeValue&&(g[y.nodeValue]=f.nodeValue)}}const B=t.getElementsByTagName("Challenge")[0];let C;return B&&((a=B.childNodes[0])!=null&&a.nodeValue)&&(C=window.atob((c=B.childNodes[0])==null?void 0:c.nodeValue)),t.querySelector("parsererror")&&(g={"Content-Type":"text/xml; charset=utf-8",SOAPAction:'"http://schemas.microsoft.com/DRM/2007/03/protocols/AcquireLicense"'},C=i),{headers:g,message:C}};class Gc extends NB{constructor(A,t){super("playready",A,t)}requestLicense(A){return r(this,null,function*(){lA(this.licenseServerUrl,"No license server URL set");const t=new URL(this.licenseServerUrl);for(const[B,C]of Object.entries(this.queryParams))t.searchParams.append(B,C);const e=Fc(A),g=yield fetch(t,{method:"POST",headers:D(D({},e.headers),this.headers),body:e.message});if(!g.ok)throw new Error(`Failed to fetch license: ${g.statusText}`);return yield g.arrayBuffer()})}}class kc extends NB{constructor(A,t){super("widevine",A,t)}}const Rc=5e3;class $n{constructor(A,t,e={}){n(this,DA);n(this,IA);n(this,Qi);n(this,jt);n(this,ht,new $);n(this,Gt);n(this,GA);n(this,we,new Map);n(this,De);n(this,mC,fQ());n(this,gI);n(this,Kg,A=>{if(s(this,IA).info("Received DRM data",{drmData:A}),window.clearTimeout(s(this,gI)),s(this,GA)){const t=d(this,DA,jE).call(this,A)[s(this,GA).keySystem];t&&(s(this,GA).licenseServerUrl=t)}s(this,ht).resolve(A)});n(this,Yg,A=>{s(this,IA).info("Encrypted event received",{event:A}),d(this,DA,xE).call(this,A)});n(this,SC,A=>{var B,C;s(this,IA).debug("Session message received",{event:A});const t=A.target,e=A.message;if(!s(this,we).get(t)){s(this,IA).error("No active session found for event",{event:A});return}s(this,IA).debug("Requesting license for session",{sessionId:t.sessionId,licenseServerUrl:(B=s(this,GA))==null?void 0:B.licenseServerUrl}),(C=s(this,GA))==null||C.requestLicense(e).then(Q=>{s(this,IA).debug("License received for session",{sessionId:t.sessionId}),t.update(Q).catch(o=>{d(this,DA,SB).call(this,{message:"Failed to update session with license",isFatal:!1,error:o})})}).catch(Q=>{d(this,DA,SB).call(this,{message:"Failed to request license",isFatal:!1,error:Q})})});n(this,yC,A=>{const t=A.target;s(this,IA).debug("Key status changed for session",{sessionId:t.sessionId}),t.keyStatuses.forEach((e,g)=>{const B=Xn(window.btoa(String.fromCharCode(...new Uint8Array(g))));s(this,IA).debug("Key status",{base64kid:B,status:e})})});n(this,fC,A=>r(this,null,function*(){const t=d(this,DA,XE).call(this,A);s(this,IA).debug("Prioritized key system list",{keySystemList:t});const e=yield fc(t,A.videoCodec,A.audioCodec,{widevine:s(this,Gt).widevine,playready:s(this,Gt).playready});if(!e)return s(this,IA).warn("No supported key system found"),null;s(this,IA).debug("Supported key system found",e.mediaKeySystemAccess.getConfiguration());const{keySystem:g,mediaKeySystemAccess:B}=e;let C=null;return g==="clearkey"?(lA(A.clearkeys,"No clearkeys found"),C=new mc(B,A.clearkeys)):g==="playready"?(lA(A.playreadyLicenseUrl,"No playreadyLicenseUrl found"),C=new Gc(B,A.playreadyLicenseUrl)):g==="widevine"?(lA(A.widevineLicenseUrl,"No widevineLicenseUrl found"),C=new kc(B,A.widevineLicenseUrl)):g==="fairplay"&&(lA(A.fairplayLicenseUrl,"No fairplayLicenseUrl found"),lA(A.fairplayCertificate,"No fairplayCertificate found"),C=new pc(B,A.fairplayLicenseUrl,A.fairplayCertificate)),C&&(C.headers=s(this,Gt).headers||{},C.queryParams=s(this,Gt).queryParams||{}),C}));E(this,Qi,A),E(this,IA,t),E(this,Gt,e),s(this,Qi).on("received drm data",s(this,Kg))}static isSupported(){return!!navigator.requestMediaKeySystemAccess}attach(A){E(this,jt,A),s(this,IA).info("Media element attached"),s(this,jt).addEventListener("encrypted",s(this,Yg))}getStatistics(){var A,t;return!s(this,ht).resolved&&!((A=s(this,GA))!=null&&A.statistics)?null:D(D({},s(this,ht).resolved),(t=s(this,GA))==null?void 0:t.statistics)}unload(){var A;s(this,IA).info("Unloading EncryptedMediaExtensions"),s(this,Qi).off("received drm data",s(this,Kg)),(A=s(this,jt))==null||A.removeEventListener("encrypted",s(this,Yg)),s(this,we).forEach((t,e)=>{e.close()}),s(this,we).clear(),E(this,De,void 0),E(this,GA,void 0)}set headers(A){s(this,Gt).headers=A,s(this,GA)&&(s(this,GA).headers=A)}set queryParams(A){s(this,Gt).queryParams=A,s(this,GA)&&(s(this,GA).queryParams=A)}onChannelSwitch(){if(!s(this,ht).resolved){s(this,IA).debug("DRM is not used, skipping channel switch handling");return}Tr()&&s(this,mC).platform.safariVersion<18&&d(this,DA,SB).call(this,{message:"DRM channel switch not supported on Safari < 18",isFatal:!0}),window.clearTimeout(s(this,gI));const A=s(this,ht).resolved;E(this,ht,new $),E(this,gI,window.setTimeout(()=>{s(this,ht).resolve(A)},Rc))}}IA=new WeakMap,Qi=new WeakMap,jt=new WeakMap,ht=new WeakMap,Gt=new WeakMap,GA=new WeakMap,we=new WeakMap,De=new WeakMap,mC=new WeakMap,gI=new WeakMap,Kg=new WeakMap,Yg=new WeakMap,DA=new WeakSet,xE=function(A){return r(this,null,function*(){try{yield d(this,DA,WE).call(this),s(this,IA).debug("Media keys initialization completed"),yield d(this,DA,OE).call(this,A.initData,A.initDataType)}catch(t){d(this,DA,SB).call(this,{message:"Failed to handle encrypted event",isFatal:!0,error:t})}})},WE=function(){return r(this,null,function*(){var t;s(this,IA).debug("Initializing media keys");const A=yield s(this,ht).promise;if((t=s(this,jt))!=null&&t.mediaKeys){s(this,IA).debug("Media keys already set on media element");return}if(s(this,De)){s(this,IA).debug("Media keys initialization already in progress, waiting for completion"),yield s(this,De);return}E(this,De,r(this,null,function*(){const e=yield s(this,fC).call(this,A);s(this,IA).debug("CDM obtained",{cdm:e}),lA(s(this,jt),"No media element found"),lA(e,"No CDM found");const g=yield e.getMediaKeys();e.certificate&&(yield d(this,DA,ZE).call(this,g,e.certificate)),s(this,IA).debug("Setting media keys on media element"),yield s(this,jt).setMediaKeys(g),E(this,GA,e)})),yield s(this,De)})},OE=function(A,t){return r(this,null,function*(){lA(s(this,GA),"No CDM manager found");const e=yield s(this,GA).getMediaKeys();if(!A||!d(this,DA,VE).call(this,A)){s(this,IA).debug("Duplicate initData, no need to create new session",{initData:A});return}const g=e.createSession();s(this,IA).debug("Creating new session",{session:g}),g.addEventListener("keystatuseschange",s(this,yC)),g.closed.then(B=>{s(this,IA).info("Session is closed",{reason:B})}),g.addEventListener("message",s(this,SC)),s(this,we).set(g,A),s(this,IA).debug("Generating request for session",{session:g,initDataType:t,initData:A}),yield g.generateRequest(t,A)})},VE=function(A){for(const[t,e]of s(this,we))if(Dc(A,e))return!1;return!0},SC=new WeakMap,yC=new WeakMap,ZE=function(A,t){return r(this,null,function*(){try{s(this,IA).debug("Setting server certificate",{certificate:t}),(yield A.setServerCertificate(t))||s(this,IA).warn("Server certificates are not supported by the CDM.")}catch(e){s(this,IA).error("Failed to set server certificate",{error:e})}})},SB=function(A){const{message:t,isFatal:e,error:g}=A;s(this,IA).error(t,{error:g}),s(this,Qi).emit("error",Zn(t,e,g))},fC=new WeakMap,XE=function(A){const t=[];return A.clearkeys&&t.push("clearkey"),A.playreadyLicenseUrl&&t.push("playready"),A.widevineLicenseUrl&&t.push("widevine"),A.fairplayLicenseUrl&&A.fairplayCertificate&&t.push("fairplay"),t},jE=function(A){return{fairplay:A.fairplayLicenseUrl,playready:A.playreadyLicenseUrl,widevine:A.widevineLicenseUrl,clearkey:void 0}};const Uc=7,Nc=8,bc=i=>{const A=i.getUint32(0,!1),t=i.getUint8(0)<<16|i.getUint16(1,!1);let e=0;return t===1?e+=3:A===1&&(e+=4),e},Lc=i=>bc(new DataView(i,0))!==0,Aa=(i,A=0)=>{for(let t=A;t<i.byteLength-4;t++){const e=i.getUint32(t)===1,g=(i.getUint8(t)<<16|i.getUint16(t+1))===1;if(e||g)return{position:t,nalPrefixSize:e?4:3}}},Jc=i=>i&31,Mc=(i,A)=>{const t=new DataView(i,0);let e=Aa(t);for(;e;){const{position:g,nalPrefixSize:B}=e,C=Aa(t,g+4),Q=C?C.position-g-B:void 0;if(!A(new DataView(i,g+B,Q),B))return;e=C}},ta=i=>{const A=[],t=[];if(!Lc(i)){const e=new DataView(i,0),g=e.getUint8(5)&31;let B=6;for(let Q=0;Q<g;Q++){const o=e.getUint16(B);A.push(i.slice(B+2,B+2+o)),B+=o+2}const C=e.getUint8(B);B+=1;for(let Q=0;Q<C;Q++){const o=e.getUint16(B);t.push(i.slice(B+2,B+2+o)),B+=o+2}return{sequenceParameterSets:A,pictureParameterSets:t}}return Mc(i,e=>{const g=e.byteOffset+e.byteLength;switch(Jc(e.getUint8(0))){case Nc:t.push(e.buffer.slice(e.byteOffset,g));break;case Uc:A.push(e.buffer.slice(e.byteOffset,g));break}return!0}),{sequenceParameterSets:A,pictureParameterSets:t}},Hc=i=>{var y;const A=new DataView(i),t=A.getUint8(1),e=A.getUint8(2),g=A.getUint8(3),B=new VA(i,32);B.readUnsignedExpGolomb();let C=1;switch(t){case 100:case 110:case 122:case 244:case 44:case 83:case 86:case 118:case 128:case 138:case 144:{if(C=B.readUnsignedExpGolomb(),C===3&&B.readBits(1),B.readUnsignedExpGolomb()+8,B.readUnsignedExpGolomb()+8,B.readBit(),B.readBit()){for(let k=0;k<(C!=3?8:12);k++)if(B.readBit()){const U=k<6?16:64;let H=0,T=8,z=8;for(let Y=0;Y<U;Y++)z!=0&&(H=B.readSignedExpGolomb(),z=(T+H+256)%256),T=z==0?T:z}}break}}B.readUnsignedExpGolomb();const Q=B.readUnsignedExpGolomb();if(Q==0)B.readUnsignedExpGolomb();else if(Q==1)throw new Error("Unhandled case");B.readUnsignedExpGolomb(),B.readBit();const o=B.readUnsignedExpGolomb(),a=B.readUnsignedExpGolomb(),c=B.readBit();c===0&&B.readBit(),B.readBit();let h=o+1,l=a+1;if(l*=2-c,l*=16,h*=16,B.readBit()){const f=C==1?1:0,q=1<<(C==1||C==2?1:0),U=2-c<<f,H=B.readUnsignedExpGolomb()*q,T=B.readUnsignedExpGolomb()*q,z=B.readUnsignedExpGolomb()*U,Y=B.readUnsignedExpGolomb()*U;h-=H+T,l-=z+Y}let m={numerator:1,denumerator:1};return B.readBit()&&B.readBit()&&(m=(y=qc[B.readBits(8)])!=null?y:{numerator:0,denumerator:0}),{width:h,height:l,pixelAspectRatio:m,profileIdc:t,constraintFlags:e,levelIdc:g}},qc=[{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}],vc=184549376;function Kc(i){const A=new SA(i),t=Yc(A);(t.flags&vc)!==0&&Tc(A);const e=Pc(A);if(String.fromCharCode(...e.frameId)==="TXXX"){const B=new SA(A.readBytes(e.size));return{header:t,txx:xc(B)}}}function Yc(i){const A=i.readBytes(3),t=i.readUint8(),e=i.readUint8(),g=i.readUint8(),B=i.readUint32();return{id:A,majorVersion:t,minorVersion:e,flags:g,size:B}}function Tc(i){const A=i.readUint32();return i.readBytes(A-4),{}}function Pc(i){const A=i.readBytes(4),t=i.readUint32(),e=i.readUint16();return{frameId:A,size:t,flags:e}}function xc(i){const A=i.readUint8(),t=i.readUtf8String(),e=i.readUtf8String();return{encoding:A,description:t,value:e}}function ea(i){let A=i.readUint32();const t=[i.readUint8(),i.readUint8(),i.readUint8(),i.readUint8()],e=String.fromCharCode.apply(null,t);return A===1&&(A=i.readUint64()-8),{size:A-8,type:e}}function Wc(i,A){const t=ea(A),e=new SA(A.readBytes(t.size));if(t.type!==i.type)throw new Error(`invalid error type: ${t.type}, expected ${i.type}`);const g=i.decodeData(e);return e.readRemaining(),g}function Ot(i){const A=i.readUint8(),t=i.readUint24();return{version:A,flags:t}}const sI=class sI{constructor({timescale:A,presentationTime:t,presentationTimeDelta:e,schemeIdUri:g,value:B,eventDuration:C,id:Q,data:o}){I(this,"type",sI.type);I(this,"timescale");I(this,"presentationTime");I(this,"presentationTimeDelta");I(this,"schemeIdUri");I(this,"value");I(this,"eventDuration");I(this,"id");I(this,"data");this.timescale=A,this.presentationTime=t,this.presentationTimeDelta=e,this.schemeIdUri=g,this.value=B,this.eventDuration=C,this.id=Q,this.data=o}static decodeData(A){const{version:t}=Ot(A);switch(t){case 1:{const e=A.readUint32(),g=A.readUint64(),B=A.readUint32(),C=A.readUint32(),Q=A.readUtf8String(),o=A.readUtf8String(),a=A.remaining(),c=A.readBytes(a);return new sI({timescale:e,presentationTime:g,eventDuration:B,id:C,schemeIdUri:Q,value:o,data:c})}case 0:{const e=A.readUtf8String(),g=A.readUtf8String(),B=A.readUint32(),C=A.readUint32(),Q=A.readUint32(),o=A.readUint32(),a=A.remaining(),c=A.readBytes(a);return new sI({timescale:B,presentationTimeDelta:C,schemeIdUri:e,value:g,eventDuration:Q,id:o,data:c})}default:throw new Error(`unsupported version ${t}`)}}};I(sI,"type","emsg");let bB=sI;const Tg=class Tg{constructor(A){I(this,"type",Tg.type);I(this,"data");this.data=A}static decodeData(A){const t=A.readRemaining();return new Tg(t)}};I(Tg,"type","mdat");let LB=Tg;const Pg=class Pg{constructor(A,t,e){I(this,"type",Pg.type);I(this,"extra");I(this,"byteOffset");I(this,"baseMediaDecodeTime");this.extra=A,this.byteOffset=t,this.baseMediaDecodeTime=e}static decodeData(A){const t=Ot(A),e=A.byteOffset();let g=0;return t.version===1?g=A.readUint64():g=A.readUint32(),new Pg(t,e,g)}};I(Pg,"type","tfdt");let JB=Pg;const Oc=1,Vc=2,Zc=8,Xc=16,jc=32,xg=class xg{constructor(A,t,e,g){I(this,"type",xg.type);I(this,"extra");I(this,"defaultSampleDuration");I(this,"defaultSampleSize");I(this,"defaultSampleFlags");this.extra=A,this.defaultSampleDuration=t,this.defaultSampleSize=e,this.defaultSampleFlags=g}static decodeData(A){const t=Ot(A);let e,g,B;return A.readUint32(),(t.flags&Oc)>0&&A.readUint64(),(t.flags&Vc)>0&&A.readUint32(),(t.flags&Zc)>0&&(e=A.readUint32()),(t.flags&Xc)>0&&(g=A.readUint32()),(t.flags&jc)>0&&(B=A.readUint32()),new xg(t,e,g,B)}};I(xg,"type","tfhd");let MB=xg;const cA=class cA{constructor(A,t,e){I(this,"type",cA.type);I(this,"dataOffset");I(this,"firstSampleFlags");I(this,"samplesCount");I(this,"sampleDurations",[]);I(this,"sampleSizes",[]);I(this,"sampleFlags",[]);I(this,"sampleCts",[]);this.dataOffset=t,this.firstSampleFlags=e,this.samplesCount=A}is_sync_sample(A){const t=cA.FLAG_SAMPLE_FLAG_IS_NON_SYNC|cA.FLAG_SAMPLE_DEPENDS_YES,e=this.sampleFlags[A];if(typeof e!="undefined")return(e&t)===0;if(A===0&&this.firstSampleFlags)return(this.firstSampleFlags&t)===0}static decodeData(A){const{flags:t}=Ot(A),e=A.readUint32();let g,B;t&cA.TRUN_DATA_OFFSET&&(g=A.readUint32()),t&cA.TRUN_FIRST_SAMPLE_FLAGS&&(B=A.readUint32());const C=new cA(e,g,B);for(let Q=0;Q<e;Q++)t&cA.SAMPLE_DURATION&&C.sampleDurations.push(A.readUint32()),t&cA.SAMPLE_SIZE&&C.sampleSizes.push(A.readUint32()),t&cA.SAMPLE_FLAGS&&C.sampleFlags.push(A.readUint32()),t&cA.SAMPLE_CTS&&C.sampleCts.push(A.readUint32());return C}};I(cA,"TRUN_DATA_OFFSET",1),I(cA,"TRUN_FIRST_SAMPLE_FLAGS",4),I(cA,"SAMPLE_DURATION",256),I(cA,"SAMPLE_SIZE",512),I(cA,"SAMPLE_FLAGS",1024),I(cA,"SAMPLE_CTS",2048),I(cA,"FLAG_SAMPLE_FLAG_IS_NON_SYNC",65536),I(cA,"FLAG_SAMPLE_DEPENDS_NO",33554432),I(cA,"FLAG_SAMPLE_DEPENDS_YES",16777216),I(cA,"type","trun");let fg=cA;const Wg=class Wg{constructor(A,t,e){I(this,"type",Wg.type);I(this,"tfhd");I(this,"tfdt");I(this,"trun");this.tfhd=A,this.tfdt=t,this.trun=e}static decodeData(A){let t,e,g;for(;A.remaining()>0;){const B=at(A);B instanceof MB&&(t=B),B instanceof JB&&(e=B),B instanceof fg&&(g=B)}return new Wg(t,e,g)}};I(Wg,"type","traf");let HB=Wg;const Og=class Og{constructor(A){I(this,"type",Og.type);I(this,"traf");this.traf=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=at(A);e instanceof HB&&(t=e)}if(!t)throw new Error("No traf found");return new Og(t)}};I(Og,"type","moof");let qB=Og;const Vg=class Vg{constructor(){I(this,"type",Vg.type)}static decodeData(A){return new Vg}};I(Vg,"type","mvhd");let vB=Vg;const Zg=class Zg{constructor(A){I(this,"type",Zg.type);I(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){Ot(A),A.readUint32();const t=String.fromCharCode(...A.readBytes(4));return new Zg(t)}};I(Zg,"type","hdlr");let KB=Zg;const BI=class BI{constructor(A,t,e,g){I(this,"type",BI.type);I(this,"creationTime");I(this,"modificationTime");I(this,"timescale");I(this,"duration");this.creationTime=A,this.modificationTime=t,this.timescale=e,this.duration=g}static decodeData(A){const{version:t}=Ot(A);if(t===1){const Q=A.readUint64(),o=A.readUint64(),a=A.readUint32(),c=A.readUint64();return new BI(Q,o,a,c)}const e=A.readUint32(),g=A.readUint32(),B=A.readUint32(),C=A.readUint32();return new BI(e,g,B,C)}};I(BI,"type","mdhd");let YB=BI;const Xg=class Xg{constructor(A,t,e,g){I(this,"type",Xg.type);I(this,"av01");I(this,"avc1");I(this,"opus");I(this,"codec");this.avc1=A,this.av01=t,this.opus=e,this.codec=g}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){Ot(A);const t=A.readUint32();let e,g,B,C;for(let Q=0;Q<t;Q++)for(;A.remaining()>0;){const o=at(A);switch(o.type){case"avc1":e="h264",g=o;break;case"av01":e="av1",C=o;break;case"mp4a":e="aac";break;case"Opus":e="opus",B=o;break}}return new Xg(g,C,B,e)}};I(Xg,"type","stsd");let TB=Xg;const jg=class jg{constructor(A){I(this,"type",jg.type);I(this,"stsd");this.stsd=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=at(A);e instanceof TB&&(t=e)}if(!t)throw new Error("No stsd found");return new jg(t)}};I(jg,"type","stbl");let PB=jg;const zg=class zg{constructor(A){I(this,"type",zg.type);I(this,"stbl");this.stbl=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=at(A);e instanceof PB&&(t=e)}if(!t)throw new Error("No stbl found");return new zg(t)}};I(zg,"type","minf");let xB=zg;const _g=class _g{constructor(A,t,e){I(this,"type",_g.type);I(this,"hdlr");I(this,"minf");I(this,"mdhd");this.hdlr=A,this.minf=t,this.mdhd=e}static decodeData(A){let t,e,g;for(;A.remaining()>0;){const B=at(A);B instanceof KB&&(t=B),B instanceof xB&&(e=B),B instanceof YB&&(g=B)}if(!t)throw new Error("No hdlr found");if(!e)throw new Error("No minf found");if(!g)throw new Error("No mdhd found");return new _g(t,e,g)}};I(_g,"type","mdia");let WB=_g;const $g=class $g{constructor(A,t,e,g,B,C,Q,o){I(this,"type",$g.type);I(this,"modificationTime");I(this,"creationTime");I(this,"trackId");I(this,"duration");I(this,"alternateGroup");I(this,"volume");I(this,"width");I(this,"height");this.modificationTime=A,this.creationTime=t,this.trackId=e,this.duration=g,this.alternateGroup=B,this.volume=C,this.width=Q,this.height=o}static decodeData(A){const t=Ot(A);let e=0,g=0;t.version===1?(e=A.readUint64(),g=A.readUint64()):(e=A.readUint32(),g=A.readUint32());const B=A.readUint32();A.readUint32();const C=A.readUint32();A.readUint32(),A.readUint32(),A.readUint16();const Q=A.readUint16(),o=A.readUint16();A.readUint16(),new Array(9).fill(0).map(()=>A.readUint32());const a=A.readUint16();A.readUint16();const c=A.readUint16();return A.readUint16(),new $g(e,g,B,C,Q,o,a,c)}};I($g,"type","tkhd");let OB=$g;const As=class As{constructor(A,t){I(this,"type",As.type);I(this,"tkhd");I(this,"mdia");this.tkhd=A,this.mdia=t}static decodeData(A){let t,e;for(;A.remaining()>0;){const g=at(A);g instanceof OB&&(t=g),g instanceof WB&&(e=g)}if(!t)throw new Error("No tkhd found");if(!e)throw new Error("No mdia found");return new As(t,e)}};I(As,"type","trak");let VB=As;const ts=class ts{constructor(A,t){I(this,"type",ts.type);I(this,"mvhd");I(this,"traks");this.mvhd=A,this.traks=t}static decodeData(A){let t;const e=[];for(;A.remaining()>0;){const g=at(A);g instanceof VB&&e.push(g),g instanceof vB&&(t=g)}if(!t)throw new Error("No mvhd found");return new ts(t,e)}};I(ts,"type","moov");let ZB=ts;const es=class es{constructor(A,t,e,g,B,C,Q,o){I(this,"type",es.type);I(this,"configurationVersion");I(this,"avcProfileIndication");I(this,"profileCompatibility");I(this,"avcLevelIndication");I(this,"lengthSizeMinusOne");I(this,"sequenceParameterSets");I(this,"pictureParameterSets");I(this,"bytes");this.configurationVersion=A,this.avcProfileIndication=t,this.profileCompatibility=e,this.avcLevelIndication=g,this.lengthSizeMinusOne=B,this.sequenceParameterSets=C,this.pictureParameterSets=Q,this.bytes=o}static decodeData(A){const t=A.buffer(),e=A.readUint8(),g=A.readUint8(),B=A.readUint8(),C=A.readUint8(),Q=A.readUint8()&3,o=A.readUint8()&31,a=[];for(let l=0;l<o;l++){const m=A.readBytes(A.readUint16());a.push(m)}const c=A.readUint8(),h=[];for(let l=0;l<c;l++){const m=A.readBytes(A.readUint16());h.push(m)}return new es(e,g,B,C,Q,a,h,t)}};I(es,"type","avcC");let bQ=es;const is=class is{constructor(A,t,e,g,B){I(this,"type",is.type);I(this,"avcC");I(this,"width");I(this,"height");I(this,"horizontalResolution");I(this,"verticalResolution");this.avcC=A,this.width=t,this.height=e,this.horizontalResolution=g,this.verticalResolution=B}static decodeData(A){A.readUint32(),A.readUint16(),A.readUint16(),A.readUint32(),A.readUint64(),A.readUint32();const t=A.readUint16(),e=A.readUint16(),g=A.readUint32(),B=A.readUint32();A.readUint32(),A.readUint16(),A.readBytes(32),A.readUint16(),A.readUint16();let C;for(;A.remaining()>0;){const Q=at(A);switch(Q.type){case"avcC":C=Q;break}}if(!C)throw new Error("no avcC");return new is(C,t,e,g,B)}};I(is,"type","avc1");let LQ=is;const Is=class Is{constructor(){I(this,"type",Is.type)}static decodeData(A){return new Is}};I(Is,"type","dOps");let JQ=Is;const gs=class gs{constructor(A,t,e){I(this,"type",gs.type);I(this,"dops");I(this,"channelCount");I(this,"sampleRate");this.dops=A,this.channelCount=t,this.sampleRate=e}static decodeData(A){A.readUint32(),A.readUint16(),A.readUint16();const t=A.readUint16();A.readUint16(),A.readUint32();const e=A.readUint16();A.readUint16(),A.readUint32();const g=A.readUint16();A.readUint16(),t===1&&(A.readUint64(),A.readUint64());const B=Wc(JQ,A);return new gs(B,e,g)}};I(gs,"type","Opus");let MQ=gs;const CI=class CI{constructor(A,t){I(this,"type",CI.type);I(this,"ntpTimestamp");I(this,"mediaTime");this.ntpTimestamp=A,this.mediaTime=t}date(){const[A,t]=this.ntpTimestamp,e=A*1e3+t/2**32*1e3,g=new Date(Date.UTC(1900,0,1,0,0,0));return new Date(g.getTime()+e)}static decodeData(A){const{version:t}=Ot(A);A.readUint32();const e=A.readUint32(),g=A.readUint32();if(t===1){const C=A.readUint64();return new CI([e,g],C)}const B=A.readUint32();return new CI([e,g],B)}};I(CI,"type","prft");let XB=CI;class zc{constructor(A,t){n(this,ss);n(this,Bs);E(this,ss,A),E(this,Bs,t.readBytes(A.size))}data(){return s(this,Bs)}get type(){return s(this,ss).type}}ss=new WeakMap,Bs=new WeakMap;const _c={moov:ZB,trak:VB,tkhd:OB,mvhd:vB,moof:qB,traf:HB,tfhd:MB,tfdt:JB,trun:fg,mdat:LB,mdia:WB,hdlr:KB,minf:xB,stbl:PB,mdhd:YB,stsd:TB,prft:XB,avc1:LQ,avcC:bQ,Opus:MQ,emsg:bB};function at(i){const A=ea(i),t=_c[A.type],e=new SA(i.readBytes(A.size));if(!t){const B=new zc(A,e);return e.readRemaining(),B}const g=t.decodeData(e);return e.readRemaining(),g}function $c(i){if(i.byteLength<8)throw new Error("Buffer too small");const A=new SA(i),t=new Map;for(;A.remaining()>0;){const B=at(A);t.set(B.type,B)}const e=t.get("ftyp"),g=t.get("moov");if(!e)throw new Error("ftyp atom not found");if(!g||!(g instanceof ZB))throw new Error("moov atom not found");return{ftyp:e,moov:g}}function Ah(i){if(i.byteLength<8)throw new Error("Buffer too small");const A=new SA(i),t=new Map,e=[];for(;A.remaining()>0;){const Q=at(A);Q instanceof bB&&e.push(Q),t.set(Q.type,Q)}const g=t.get("moof"),B=t.get("mdat"),C=t.get("prft");if(!g||!(g instanceof qB))throw new Error("moof atom not found");if(!B||!(B instanceof LB))throw new Error("mdat atom not found");if(C&&!(C instanceof XB))throw new Error("invalid prft found");return{moof:g,mdat:B,prft:C,emsgs:e}}class th{constructor(A){n(this,Cs);n(this,Qs);E(this,Cs,A),E(this,Qs,$c(A))}rawBytes(){return s(this,Cs)}init(){return s(this,Qs)}}Cs=new WeakMap,Qs=new WeakMap;const Wo=class Wo{constructor(A,t){n(this,YA);n(this,XA);n(this,CA);E(this,YA,t),E(this,XA,A),E(this,CA,Ah(t))}clone(){return new Wo(s(this,XA),new Uint8Array(s(this,YA).buffer.slice(s(this,YA).byteOffset,s(this,YA).byteOffset+s(this,YA).byteLength)))}updateBaseMediaDecodeTime(A){const t=new DataView(s(this,YA).buffer,s(this,YA).byteOffset,s(this,YA).byteLength);if(s(this,CA).moof.traf.tfdt)if(s(this,CA).moof.traf.tfdt.baseMediaDecodeTime=A,s(this,CA).moof.traf.tfdt.extra.version===1){const e=Math.floor(A/4294967296),g=(A&4294967295)>>>0;t.setUint32(s(this,CA).moof.traf.tfdt.byteOffset-s(this,YA).byteOffset,e),t.setUint32(s(this,CA).moof.traf.tfdt.byteOffset-s(this,YA).byteOffset+4,g)}else t.setUint32(s(this,CA).moof.traf.tfdt.byteOffset-s(this,YA).byteOffset,A)}producerReferenceTime(){if(s(this,CA).prft)return s(this,CA).prft.date()}duration(){const A=s(this,CA).moof.traf.trun,t=s(this,CA).moof.traf.tfhd;if((A==null?void 0:A.sampleDurations.length)===0){const e=(A==null?void 0:A.samplesCount)||1;if(t!=null&&t.defaultSampleDuration)return(t==null?void 0:t.defaultSampleDuration)*e}return(A==null?void 0:A.sampleDurations.reduce((e,g)=>e+g,0))||0}baseMediaDecodeTime(){var t;const A=(t=s(this,CA).moof.traf.tfdt)==null?void 0:t.baseMediaDecodeTime;if(!A)throw new Error("no baseMediaDecodeTime");return A}startsWithKeyframe(){var e;const A=s(this,CA).moof.traf.trun,t=(A==null?void 0:A.firstSampleFlags)||(A==null?void 0:A.sampleFlags[0])||((e=s(this,CA).moof.traf.tfhd)==null?void 0:e.defaultSampleFlags);return t?(t&fg.FLAG_SAMPLE_DEPENDS_NO)!==0:!1}compositionTimeOffset(A){var t;return(t=s(this,CA).moof.traf.trun)==null?void 0:t.sampleCts[A]}timescale(){const A=s(this,XA).init().moov.traks[0];if(!A)throw new Error("no tracks");return A.mdia.mdhd.timescale}mediaType(){var t;const A=(t=s(this,XA).init().moov.traks[0])==null?void 0:t.mdia.hdlr.mediaType();if(!A)throw new Error("no media type");return A}header(){return s(this,XA)}fragment(){return s(this,CA)}samplesCount(){var A;return((A=s(this,CA).moof.traf.trun)==null?void 0:A.samplesCount)||0}sample(A){var y,f,k,q,U,H,T,z,Y,FA,nA,mA,tt,JA,w;const t=(y=s(this,XA).init().moov.traks[0])==null?void 0:y.mdia.minf.stbl.stsd.codec,e=((f=s(this,CA).moof.traf.trun)==null?void 0:f.samplesCount)||0,g=(k=s(this,CA).moof.traf.tfdt)==null?void 0:k.baseMediaDecodeTime;if(A>=e||typeof g=="undefined"||!t)return;const B=this.compositionTimeOffset(A),C=((q=s(this,CA).moof.traf.trun)==null?void 0:q.sampleDurations[A])||0,Q=((U=s(this,CA).moof.traf.trun)==null?void 0:U.sampleDurations.slice(0,A).reduce((G,AA)=>G+AA,0))||0,o=g+Q,a=((H=s(this,XA).init().moov.traks[0])==null?void 0:H.mdia.mdhd.timescale)||1e3,c=((T=s(this,CA).moof.traf.trun)==null?void 0:T.sampleSizes[A])||s(this,CA).mdat.data.byteLength,h=((z=s(this,CA).moof.traf.trun)==null?void 0:z.sampleSizes.slice(0,A).reduce((G,AA)=>G+AA,0))||0,l=s(this,CA).mdat.data.subarray(h,h+c),m=((Y=s(this,CA).moof.traf.trun)==null?void 0:Y.is_sync_sample(A))||!1;if(this.mediaType()==="video"){const G=((FA=s(this,XA).init().moov.traks[0])==null?void 0:FA.tkhd.width)||0,AA=((nA=s(this,XA).init().moov.traks[0])==null?void 0:nA.tkhd.height)||0;return{type:"video",codec:t,width:G,height:AA,duration:C,isSync:m,timescale:a,timestamp:o,compositionTimeOffset:B,data:l}}return{type:"audio",codec:t,channels:((tt=(mA=s(this,XA).init().moov.traks[0])==null?void 0:mA.mdia.minf.stbl.stsd.opus)==null?void 0:tt.channelCount)||0,sampleRate:((w=(JA=s(this,XA).init().moov.traks[0])==null?void 0:JA.mdia.minf.stbl.stsd.opus)==null?void 0:w.sampleRate)||0,duration:C,isSync:m,timestamp:o,compositionTimeOffset:B,data:l,timescale:a}}rawBytes(){return s(this,YA)}};YA=new WeakMap,XA=new WeakMap,CA=new WeakMap;let HQ=Wo;class ia{constructor(A){n(this,QI);E(this,QI,new th(A))}header(){return s(this,QI)}createFragment(A){return new HQ(s(this,QI),A)}}QI=new WeakMap;function M(i){const A=new ArrayBuffer(i.length),t=new Uint8Array(A);for(let e=0,g=i.length;e<g;e++)t[e]=i.charCodeAt(e);return new Uint8Array(A)}const gA={ftyp:M("ftyp"),mvhd:M("mvhd"),moov:M("moov"),trak:M("trak"),tkhd:M("tkhd"),mdia:M("mdia"),mdhd:M("mdhd"),hdlr:M("hdlr"),minf:M("minf"),vmhd:M("vmhd"),smhd:M("smhd"),dinf:M("dinf"),dref:M("dref"),stbl:M("stbl"),stsd:M("stsd"),avc1:M("avc1"),av01:M("av01"),av1C:M("av1C"),avcC:M("avcC"),esds:M("esds"),colr:M("colr"),nclx:M("nclx"),mvex:M("mvex"),trex:M("trex"),udta:M("udta"),meta:M("meta"),ilst:M("ilst"),moof:M("moof"),mfhd:M("mfhd"),traf:M("traf"),tfhd:M("tfhd"),tfdt:M("tfdt"),trun:M("trun"),mdat:M("mdat"),mp4a:M("mp4a"),Opus:M("Opus"),prft:M("prft"),dOps:M("dOps"),emsg:M("emsg")},eh=1e3,pg=M("iso6"),Ia=new Uint8Array([0,0,2,0]),ih=[pg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([97,118,99,49]),new Uint8Array([109,112,52,49])],Ih=[pg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([97,118,48,49]),new Uint8Array([109,112,52,49])],gh=[pg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([109,112,52,49])];class ga{constructor(){I(this,"writer",new mg);I(this,"moofOffset",0)}}const uA=(i,A,t)=>{i.writer.writeUint32(t+8),i.writer.writeBytes(A)},yA=(i,A,t,e,g)=>{uA(i,A,t+4),i.writer.writeUint8(e),i.writer.writeUint24(g)},qQ=(i,A)=>{uA(i,gA.ftyp,pg.byteLength+Ia.byteLength+A.reduce((t,e)=>t+e.byteLength,0)),i.writer.writeBytes(pg),i.writer.writeBytes(Ia),A.forEach(t=>i.writer.writeBytes(t))},sh=2**32,Bh=2208988800,Ch=(i,A,t,e)=>{yA(i,gA.prft,20,1,0);const B=t/1e3,C=Math.floor(B),o=(B-C)*1e3*1e3*sh/1e6;i.writer.writeUint32(A),i.writer.writeUint32(C+Bh),i.writer.writeUint32(o),i.writer.writeUint64(e)},Qh=(i,A,t)=>{yA(i,gA.mvhd,96,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(t),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)},sa=i=>"sequenceParameterSets"in i,vQ=i=>"sequenceHeader"in i,_e=i=>i.type=="video",Fg=i=>i.type=="audio",oh=(i,A,t)=>{const e=i.writer.position();yA(i,gA.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*t/A.timescale),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint16(0),i.writer.writeUint16(Fg(A)?1:0),i.writer.writeUint16(Fg(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])),_e(A)?(i.writer.writeUint32(A.width*65536),i.writer.writeUint32(A.height*65536)):Fg(A)&&(i.writer.writeUint32(0),i.writer.writeUint32(0)),i.writer.writeUint32At(e,i.writer.position()-e)},nh=(i,A)=>{yA(i,gA.mdhd,20,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(A.timescale),i.writer.writeUint32(A.duration);const t=A.lang||"und",e=(t.charCodeAt(0)&31)<<10|(t.charCodeAt(1)&31)<<5|t.charCodeAt(2)&31;i.writer.writeUint16(e),i.writer.writeUint16(0)},ah=(i,A)=>{const t=i.writer.position();yA(i,gA.hdlr,0,0,0),i.writer.writeUint32(0),i.writer.writeBytes(M(_e(A)?"vide":"soun")),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeBytes(M(_e(A)?"VideoHandler\0":"SoundHandler\0")),i.writer.writeUint32At(t,i.writer.position()-t)},Eh=i=>{const A=i.writer.position();uA(i,gA.dinf,0),yA(i,gA.dref,16,0,0),i.writer.writeUint32(1),yA(i,M("url "),0,0,1),i.writer.writeUint32At(A,i.writer.position()-A)},rh=(i,A)=>{const t=i.writer.position();uA(i,gA.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(e=>{i.writer.writeUint16(e.byteLength),i.writer.writeBytes(e)}),i.writer.writeUint8(A.pictureParameterSets.length),A.pictureParameterSets.forEach(e=>{i.writer.writeUint16(e.byteLength),i.writer.writeBytes(e)}),i.writer.writeUint32At(t,i.writer.position()-t)},ch=(i,A)=>{var Q,o;const t=i.writer.position();uA(i,gA.av1C,0);const{seqProfile:e,operatingPoints:g,colorConfig:B}=A.parsedSequenceHeader,C=g[0];i.writer.writeUint8(129),i.writer.writeUint8(e<<5|((Q=C==null?void 0:C.seqLevelIdx)!=null?Q:0)),i.writer.writeUint8(((o=C==null?void 0:C.tier)!=null?o:0)|(B.highBitDepth?1:0)|(B.bitDepth===12?1:0)<<5|(B.monoChrome?1:0)<<4|B.subsamplingX<<3|B.subsamplingY<<2|B.chromaSamplePosition&65535),i.writer.writeUint8(0),i.writer.writeBytes(A.sequenceHeader),i.writer.writeUint32At(t,i.writer.position()-t)},hh=(i,A)=>{const t=i.writer.position(),e=vQ(A)?gA.av01:gA.avc1;uA(i,e,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),sa(A)?rh(i,A):vQ(A)&&(ch(i,A),A.parsedSequenceHeader.colorConfig&&(uA(i,M("colr"),11),i.writer.writeBytes(gA.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,M("pasp"),8),i.writer.writeUint32(A.pixelAspectRatio.numerator),i.writer.writeUint32(A.pixelAspectRatio.denumerator)),A.bitrate&&(uA(i,M("btrt"),12),i.writer.writeUint32(0),i.writer.writeUint32(A.bitrate),i.writer.writeUint32(A.bitrate)),i.writer.writeUint32At(t,i.writer.position()-t)},jB=(i,A,t)=>{let e=3;for(i.writer.writeUint8(A);e>0;e--)i.writer.writeUint8(t>>7*e|128);i.writer.writeUint8(t&127)},dh=(i,A)=>{const t=A.decoderConfig.byteLength>0?A.decoderConfig.byteLength+5:0,e=i.writer.position();yA(i,gA.esds,0,0,0),jB(i,3,21+t+5+1),i.writer.writeUint16(A.trackId),i.writer.writeUint8(0),jB(i,4,13+t);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&&(jB(i,5,A.decoderConfig.byteLength),i.writer.writeBytes(A.decoderConfig)),jB(i,6,1),i.writer.writeUint8(2),i.writer.writeUint32At(e,i.writer.position()-e)},lh=i=>{switch(i){case"aac":case"mp3":return"mp4a";case"opus":return"Opus"}},uh=(i,A)=>{const t=i.writer.position();uA(i,M("dOps"),0),i.writer.writeUint8(0);const e=A.decoderConfig,g=new DataView(e.buffer,e.byteOffset,e.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(t,i.writer.position()-t)},wh=(i,A)=>{const t=i.writer.position();switch(uA(i,M(lh(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":dh(i,A);break;case"opus":uh(i,A);break}A.bitrate&&(uA(i,M("btrt"),12),i.writer.writeUint32(0),i.writer.writeUint32(A.bitrate),i.writer.writeUint32(A.bitrate)),i.writer.writeUint32At(t,i.writer.position()-t)},Dh=(i,A)=>{const t=i.writer.position();uA(i,gA.stbl,0);const e=i.writer.position();yA(i,gA.stsd,0,0,0),i.writer.writeUint32(1),_e(A)?hh(i,A):Fg(A)&&wh(i,A),i.writer.writeUint32At(e,i.writer.position()-e),yA(i,M("stts"),4,0,0),i.writer.writeUint32(0),yA(i,M("stsc"),4,0,0),i.writer.writeUint32(0),yA(i,M("stsz"),8,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),yA(i,M("stco"),4,0,0),i.writer.writeUint32(0),i.writer.writeUint32At(t,i.writer.position()-t)},mh=(i,A)=>{const t=i.writer.position();uA(i,gA.minf,0),_e(A)?(yA(i,gA.vmhd,8,0,1),i.writer.writeUint32(0),i.writer.writeUint32(0)):Fg(A)&&(yA(i,gA.smhd,4,0,0),i.writer.writeUint16(0),i.writer.writeUint16(0)),Eh(i),Dh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Sh=(i,A)=>{const t=i.writer.position();uA(i,gA.mdia,0),nh(i,A),ah(i,A),mh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},yh=(i,A,t)=>{const e=i.writer.position();uA(i,gA.trak,0),oh(i,A,t),Sh(i,A),i.writer.writeUint32At(e,i.writer.position()-e)},fh=(i,A)=>{yA(i,gA.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)},ph=(i,A)=>{const t=i.writer.position();uA(i,gA.mvex,0),A.forEach(e=>fh(i,e)),i.writer.writeUint32At(t,i.writer.position()-t)},Fh=(i,A,t,e)=>{const g=i.writer.position();uA(i,gA.moov,0),Qh(i,0,t),A.forEach(B=>yh(i,B,t)),ph(i,A),i.writer.writeUint32At(g,i.writer.position()-g)},Gh=(i,A)=>{const t=i.writer.position();yA(i,gA.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(t,i.writer.position()-t)},kh=(i,A)=>{const t=i.writer.position();yA(i,gA.tfdt,8,1,0);const e=Math.floor(A.timestamp/4294967296),g=(A.timestamp&4294967295)>>>0;i.writer.writeUint32(e),i.writer.writeUint32(g),i.writer.writeUint32At(t,i.writer.position()-t)},Rh=(i,A)=>{if(!A.samples[0])throw new Error("At least one sample must be provided");const t=A.samples.some(o=>!!o.compositionTimeOffset),e=KQ(A.samples[0])!==A.defaultFlags,g=A.samples.length>1;let B=1;e&&(B|=4),t&&(B|=2048),g&&(B|=512,B|=256,B|=1024);const C=i.writer.position();yA(i,gA.trun,16,1,B),i.writer.writeUint32(A.samples.length);const Q=i.writer.position();i.writer.writeUint32(0),e&&i.writer.writeUint32(KQ(A.samples[0]));for(const o of A.samples)g&&(i.writer.writeUint32(o.duration),i.writer.writeUint32(o.data.byteLength),i.writer.writeUint32(KQ(o))),t&&i.writer.writeUint32(o.compositionTimeOffset||0);i.writer.writeUint32At(Q,i.writer.position()-i.moofOffset+8),i.writer.writeUint32At(C,i.writer.position()-C)},KQ=i=>i.isSync?33554432:16842752,Uh=(i,A)=>{const t=i.writer.position();uA(i,gA.traf,0),Gh(i,A),kh(i,A),Rh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Nh=(i,A)=>{yA(i,gA.mfhd,4,0,0),i.writer.writeUint32(A)},bh=(i,A)=>{const t=i.writer.position();uA(i,gA.moof,0),Nh(i,A.sequenceNumber),Uh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Lh=(i,A)=>{const t=A.samples.reduce((e,g)=>e+g.data.byteLength,0);uA(i,gA.mdat,t),A.samples.forEach(e=>i.writer.writeBytes(e.data))},zB=(i,A)=>{const t=new ga,e=i.filter(B=>_e(B)&&sa(B)).length>0;return i.filter(B=>_e(B)&&vQ(B)).length>0?qQ(t,Ih):e?qQ(t,ih):qQ(t,gh),Fh(t,i,eh),t.writer.buffer()},_B=i=>{var t;const A=new ga;return((t=i.samples[0])==null?void 0:t.producerReferenceTime)!==void 0&&Ch(A,i.trackId,i.samples[0].producerReferenceTime,i.timestamp),A.moofOffset=A.writer.position(),bh(A,i),Lh(A,i),A.writer.buffer()},Jh=(i,A)=>{const t=i.map(C=>V(D({},C),{data:new Uint8Array(C.data)}));if(!t[0])throw new Error("At least one sample must be provided");const{timestamp:e,data:g,duration:B}=t[0];return _B({trackId:1,timestamp:e,sequenceNumber:A,defaultSize:g.byteLength,defaultFlags:33554432,defaultDuration:B,samples:t})},Mh=(i,A,t,e)=>zB([{type:"audio",codec:"aac",decoderConfig:i,channelCount:A,sampleRate:t,timescale:e,duration:0,trackId:1}]),Ba=i=>{const{sequenceParameterSets:A,pictureParameterSets:t}=ta(i),e=A[0],g=t[0];if(!e||!g)throw new Error("No sps or pps provided");return Hc(e)},Hh=(i,A)=>{const t=i.map(Q=>V(D({},Q),{data:new Uint8Array(Q.data)}));if(!t[0])throw new Error("At least one sample must be provided");const{isSync:e,timestamp:g,data:B,duration:C}=t[0];return _B({trackId:1,timestamp:g,sequenceNumber:A,defaultSize:B.byteLength,defaultFlags:e?33554432:16842752,defaultDuration:C,samples:t})},qh=(i,A)=>{const{sequenceParameterSets:t,pictureParameterSets:e}=ta(i),g=Ba(i);return zB([{type:"video",sequenceParameterSets:t.map(B=>new Uint8Array(B)),pictureParameterSets:e.map(B=>new Uint8Array(B)),width:g.width,height:g.height,timescale:A,duration:0,trackId:1}])},vh=(i,A,t)=>zB([{type:"audio",trackId:1,channelCount:A,timescale:t,codec:"opus",decoderConfig:i,duration:0,sampleRate:48e3}]),Kh=(i,A)=>{const t=i.map(C=>V(D({},C),{data:new Uint8Array(C.data)}));if(!t[0])throw new Error("At least one sample must be provided");const{timestamp:e,data:g,duration:B}=t[0];return _B({trackId:1,timestamp:e,sequenceNumber:A,defaultSize:g.byteLength,defaultFlags:33554432,defaultDuration:B,samples:t})},Ca=i=>{const A=new VA(i);return A.peekBit()===1&&A.readBits(32),Ph(A),zh(A)},Yh=i=>{let A=0,t=0;for(let e=0;e<8;e++){const g=i.readBits(8);if(A|=(g&127)<<e*7,t+=1,(g&128)!==128)break}return[t,A]},Th=i=>{let A=0;for(;A<100&&i.readBit()===0;)A++;return A>=32?0:i.readBits(A)+(1<<A)-1},Ph=i=>{const A=i.remainingBits()/8,t=i.readBits(8);if((t>>7&1)!==0)return;const g=t>>3&15,B=t>>2&1,C=t>>1&1;B==1&&i.readBits(8);const[Q,o]=C?Yh(i):[0,A];return{headerLength:1+B+Q,type:g,obuSize:o}},xh=i=>{const A=i.readBits(32),t=i.readBits(32),e=i.readBit()!==0;let g=0;return e&&(g=Th(i)+1),{timescale:t,equalPictureInterval:e,numUnitsInDisplayTick:A,numTicksPerPicture:g}},Qa=2,YQ=2,Wh=1,Oh=2,Vh=2,Zh=13,Xh=0,jh=2,oa=0,zh=i=>{const A=i.readBits(3),e=i.readBit()!==0,g=i.readBit()!==0;let B,C=!1,Q=!1,o=!1,a=0,c=0;const h=[];if(g)i.readBits(5);else{if(Q=i.readBit()!==0,Q&&(B=xh(i),C=i.readBit()!==0,C))throw new Error("Not implemented");o=i.readBit()!==0;const QA=i.readBits(5)+1;for(let R=0;R<QA;R++){const L=i.readBits(12),Z=i.readBits(5);let aA=0;if(Z>7&&(aA=i.readBit()),C)throw new Error("decoderModelInfoPresentFlag==1");o&&i.readBit()!==0&&i.readBits(4),h.push({tier:aA,operatingPointIdc:L,seqLevelIdx:Z})}}const l=i.readBits(4)+1,m=i.readBits(4)+1,y=i.readBits(l)+1,f=i.readBits(m)+1;let k=!1;g?k=!1:k=i.readBit()!==0,k&&(a=i.readBits(4)+2,c=i.readBits(3)+1);const q=i.readBit()!==0,U=i.readBit()!==0,H=i.readBit()!==0;let T=!1,z=!1,Y=!1,FA=!1,nA=!1,mA=!1,tt=!1,JA=Qa,w=YQ,G=0;g||(T=i.readBit()!==0,z=i.readBit()!==0,Y=i.readBit()!==0,FA=i.readBit()!==0,nA=i.readBit()!==0,nA&&(mA=i.readBit()!==0,tt=i.readBit()!==0),i.readBit()!==0?JA=Qa:JA=i.readBit(),JA>0?i.readBit()>0?w=YQ:w=i.readBit():w=YQ,nA?G=i.readBits(3):G=0);const AA=i.readBit()!==0,iA=i.readBit()!==0,O=i.readBit()!==0;return{seqProfile:A,stillPicture:e,reducedStillPictureHeader:g,timingInfoPresentFlag:Q,timingInfo:B!=null?B:{equalPictureInterval:!1,numUnitsInDisplayTick:0,timescale:0,numTicksPerPicture:0},decoderModelInfoPresentFlag:C,initialDisplayDelayPresentFlag:o,operatingPoints:h,frameWidthBits:l,frameHeightBits:m,maxFrameWidth:y,maxFrameHeight:f,frameIdNumbersPresentFlag:k,deltaFrameIdLength:a,additionalFrameIdLength:c,use_128x128Superblock:q,enableFilterIntra:U,enableIntraEdgeFilter:H,enableInterintraCompound:T,enableMaskedCompound:z,enableWarpedMotion:Y,enableDualFilter:FA,enableOrderHint:nA,enableJntComp:mA,enableRefFrameMvs:tt,seqForceScreenContentTools:JA,seqForceIntegerMv:w,orderHintBits:G,enableSuperres:AA,enableCdef:iA,enableRestoration:O,colorConfig:_h(i,A),filmGrainParamsPresent:i.readBit()!==0}},_h=(i,A)=>{const t=i.readBit()!==0;let e=8,g=!1;A===2&&t?e=i.readBit()!==0?12:10:A<=2&&(e=t?10:8),A===1?g=!1:g=i.readBit()!==0;const B=g?1:3,C=i.readBit()!==0;let Q=Oh,o=Vh,a=jh,c=!1,h=0,l=0,m=oa,y=!1;return C&&(Q=i.readBits(8),o=i.readBits(8),a=i.readBits(8)),g?(c=i.readBit()!==0,h=1,l=1,m=oa,y=!1,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:a,numPlanes:B,separateUvDeltaQ:y,subsamplingX:h,subsamplingY:l,transferCharacteristics:o}):Q===Wh&&o==Zh&&a==Xh?(c=!0,h=0,l=0,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:a,numPlanes:B,separateUvDeltaQ:y,subsamplingX:h,subsamplingY:l,transferCharacteristics:o}):(c=i.readBit()!==0,A===0?(h=1,l=1):A===1?(h=0,l=0):e===12?(h=i.readBit(),h!==0?l=i.readBit():l=0):(h=1,l=0),h!==0&&l!==0&&(m=i.readBits(2)),y=i.readBit()!==0,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:a,numPlanes:B,separateUvDeltaQ:y,subsamplingX:h,subsamplingY:l,transferCharacteristics:o})},$h=i=>{const A=Ca(i);if(A)return{width:A.maxFrameWidth,height:A.maxFrameHeight}},Ad=(i,A)=>{const t=i.map(Q=>V(D({},Q),{data:new Uint8Array(Q.data)}));if(!t[0])throw new Error("At least one sample must be provided");const{isSync:e,timestamp:g,data:B,duration:C}=t[0];return _B({trackId:1,timestamp:g,sequenceNumber:A,defaultSize:B.byteLength,defaultFlags:e?33554432:16842752,defaultDuration:C,samples:t})},td=(i,A)=>{const t=Ca(i);if(!t)throw new Error("Failed to parse sequence header");return zB([{type:"video",parsedSequenceHeader:t,sequenceHeader:new Uint8Array(i),width:t.maxFrameWidth,height:t.maxFrameHeight,timescale:A,duration:0,trackId:1}])},ed=i=>{const{codec:A,initData:t,timescale:e}=i;switch(A){case"h264":return Id(t,e);case"av1":return gd(t,e);case"opus":return sd(t,e,i.channelCount||2);case"aac":return Bd(t,e,i.channelCount||2);default:throw new Error(`Failed to initialize ${A} segment`)}},id=(i,A)=>{switch(i){case"h264":return Ba(A);case"av1":return $h(A)}},Id=(i,A)=>qh(i,A),gd=(i,A)=>td(i,A),sd=(i,A,t)=>vh(new Uint8Array(i),t,A),Bd=(i,A,t)=>Mh(new Uint8Array(i),t,A,A),Cd=(i,A)=>{if(!i[0])throw new Error("At least one sample must be provided");switch(i[0].codec){case"h264":return Hh(i,A);case"opus":return Kh(i,A);case"aac":return Jh(i,A);case"av1":return Ad(i,A);default:throw new Error(`Unsupported codec ${i[0].codec}`)}},Gg=i=>!!(i&1),Qd=i=>!!(i&2),od=i=>!!(i&4),nd=i=>!!(i&8),ad=i=>!!(i&16),Ed=i=>{const A=new DataView(i,0),t=A.getUint8(0),e=A.getUint16(1),g=A.getUint8(3),B=A.getUint8(4),C=Oe(new Uint8Array(i),5,12),Q=A.getUint32(13),o=ad(g)?A.getInt16(17):void 0,a=i.slice(e);return{version:t,renditionId:B,flags:g,timestamp:C,timescale:Q,payload:a,compositionTimeOffset:o}},rd="data:video/mp4;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAGF21kYXTeBAAAbGliZmFhYyAxLjI4AABCAJMgBDIARwAAArEGBf//rdxF6b3m2Ui3lizYINkj7u94MjY0IC0gY29yZSAxNDIgcjIgOTU2YzhkOCAtIEguMjY0L01QRUctNCBBVkMgY29kZWMgLSBDb3B5bGVmdCAyMDAzLTIwMTQgLSBodHRwOi8vd3d3LnZpZGVvbGFuLm9yZy94MjY0Lmh0bWwgLSBvcHRpb25zOiBjYWJhYz0wIHJlZj0zIGRlYmxvY2s9MTowOjAgYW5hbHlzZT0weDE6MHgxMTEgbWU9aGV4IHN1Ym1lPTcgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0xNiBjaHJvbWFfbWU9MSB0cmVsbGlzPTEgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz02IGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTI1MCBrZXlpbnRfbWluPTI1IHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NDAgcmM9Y3JmIG1idHJlZT0xIGNyZj0yMy4wIHFjb21wPTAuNjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCB2YnZfbWF4cmF0ZT03NjggdmJ2X2J1ZnNpemU9MzAwMCBjcmZfbWF4PTAuMCBuYWxfaHJkPW5vbmUgZmlsbGVyPTAgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAAAFZliIQL8mKAAKvMnJycnJycnJycnXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXiEASZACGQAjgCEASZACGQAjgAAAAAdBmjgX4GSAIQBJkAIZACOAAAAAB0GaVAX4GSAhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGagC/AySEASZACGQAjgAAAAAZBmqAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZrAL8DJIQBJkAIZACOAAAAABkGa4C/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmwAvwMkhAEmQAhkAI4AAAAAGQZsgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGbQC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm2AvwMkhAEmQAhkAI4AAAAAGQZuAL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGboC/AySEASZACGQAjgAAAAAZBm8AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZvgL8DJIQBJkAIZACOAAAAABkGaAC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmiAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpAL8DJIQBJkAIZACOAAAAABkGaYC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmoAvwMkhAEmQAhkAI4AAAAAGQZqgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGawC/AySEASZACGQAjgAAAAAZBmuAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZsAL8DJIQBJkAIZACOAAAAABkGbIC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm0AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZtgL8DJIQBJkAIZACOAAAAABkGbgCvAySEASZACGQAjgCEASZACGQAjgAAAAAZBm6AnwMkhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AAAAhubW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAABDcAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAzB0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAA+kAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAALAAAACQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAPpAAAAAAABAAAAAAKobWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAB1MAAAdU5VxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACU21pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAhNzdGJsAAAAr3N0c2QAAAAAAAAAAQAAAJ9hdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAALAAkABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAALWF2Y0MBQsAN/+EAFWdCwA3ZAsTsBEAAAPpAADqYA8UKkgEABWjLg8sgAAAAHHV1aWRraEDyXyRPxbo5pRvPAyPzAAAAAAAAABhzdHRzAAAAAAAAAAEAAAAeAAAD6QAAABRzdHNzAAAAAAAAAAEAAAABAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAAIxzdHN6AAAAAAAAAAAAAAAeAAADDwAAAAsAAAALAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAAiHN0Y28AAAAAAAAAHgAAAEYAAANnAAADewAAA5gAAAO0AAADxwAAA+MAAAP2AAAEEgAABCUAAARBAAAEXQAABHAAAASMAAAEnwAABLsAAATOAAAE6gAABQYAAAUZAAAFNQAABUgAAAVkAAAFdwAABZMAAAWmAAAFwgAABd4AAAXxAAAGDQAABGh0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAACAAAAAAAABDcAAAAAAAAAAAAAAAEBAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAQkAAADcAABAAAAAAPgbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAC7gAAAykBVxAAAAAAALWhkbHIAAAAAAAAAAHNvdW4AAAAAAAAAAAAAAABTb3VuZEhhbmRsZXIAAAADi21pbmYAAAAQc21oZAAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAADT3N0YmwAAABnc3RzZAAAAAAAAAABAAAAV21wNGEAAAAAAAAAAQAAAAAAAAAAAAIAEAAAAAC7gAAAAAAAM2VzZHMAAAAAA4CAgCIAAgAEgICAFEAVBbjYAAu4AAAADcoFgICAAhGQBoCAgAECAAAAIHN0dHMAAAAAAAAAAgAAADIAAAQAAAAAAQAAAkAAAAFUc3RzYwAAAAAAAAAbAAAAAQAAAAEAAAABAAAAAgAAAAIAAAABAAAAAwAAAAEAAAABAAAABAAAAAIAAAABAAAABgAAAAEAAAABAAAABwAAAAIAAAABAAAACAAAAAEAAAABAAAACQAAAAIAAAABAAAACgAAAAEAAAABAAAACwAAAAIAAAABAAAADQAAAAEAAAABAAAADgAAAAIAAAABAAAADwAAAAEAAAABAAAAEAAAAAIAAAABAAAAEQAAAAEAAAABAAAAEgAAAAIAAAABAAAAFAAAAAEAAAABAAAAFQAAAAIAAAABAAAAFgAAAAEAAAABAAAAFwAAAAIAAAABAAAAGAAAAAEAAAABAAAAGQAAAAIAAAABAAAAGgAAAAEAAAABAAAAGwAAAAIAAAABAAAAHQAAAAEAAAABAAAAHgAAAAIAAAABAAAAHwAAAAQAAAABAAAA4HN0c3oAAAAAAAAAAAAAADMAAAAaAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAACMc3RjbwAAAAAAAAAfAAAALAAAA1UAAANyAAADhgAAA6IAAAO+AAAD0QAAA+0AAAQAAAAEHAAABC8AAARLAAAEZwAABHoAAASWAAAEqQAABMUAAATYAAAE9AAABRAAAAUjAAAFPwAABVIAAAVuAAAFgQAABZ0AAAWwAAAFzAAABegAAAX7AAAGFwAAAGJ1ZHRhAAAAWm1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALWlsc3QAAAAlqXRvbwAAAB1kYXRhAAAAAQAAAABMYXZmNTUuMzMuMTAw",$B=()=>"wakeLock"in navigator&&window.navigator.userAgent.indexOf("Samsung")===-1;class cd{constructor(){I(this,"enabled",!1);I(this,"wakeLockVideo");I(this,"_wakeLock",null);I(this,"handleVisibilityChange",()=>{this._wakeLock!==null&&document.visibilityState==="visible"&&this.enable()});$B()&&(this._wakeLock=null,document.addEventListener("visibilitychange",this.handleVisibilityChange),document.addEventListener("fullscreenchange",this.handleVisibilityChange))}_addSourceToVideo(A,t,e){const g=document.createElement("source");g.src=e,g.type=`video/${t}`,A.appendChild(g)}get isEnabled(){return this.enabled}attach(A){if(!$B()){if(!this.wakeLockVideo){const t=document.createElement("video");this.wakeLockVideo=t,this.wakeLockVideo.setAttribute("title","Live Stream"),this.wakeLockVideo.setAttribute("playsinline",""),this._addSourceToVideo(this.wakeLockVideo,"mp4",rd),Object.assign(this.wakeLockVideo.style,{position:"absolute",left:"-100%",top:"-100%"}),this.wakeLockVideo.addEventListener("loadedmetadata",()=>{t.addEventListener("timeupdate",()=>{t.currentTime>.5&&(t.currentTime=Math.random())})})}A&&A.appendChild(this.wakeLockVideo)}}enable(){return r(this,null,function*(){var A,t;return $B()?navigator.wakeLock.request("screen").then(e=>{this._wakeLock=e,this.enabled=!0,this._wakeLock.addEventListener("release",()=>{})}).catch(()=>{this.enabled=!1}):((t=(A=this.wakeLockVideo)==null?void 0:A.play())!=null?t:Promise.resolve()).then(g=>(this.enabled=!0,g)).catch(()=>{this.enabled=!1})})}disable(){var A,t;$B()?(this._wakeLock&&this._wakeLock.release(),this._wakeLock=null):((A=this.wakeLockVideo)==null||A.pause(),(t=this.wakeLockVideo)==null||t.remove()),this.enabled=!1}unload(){document.removeEventListener("visibilitychange",this.handleVisibilityChange),document.removeEventListener("fullscreenchange",this.handleVisibilityChange),this.disable()}}const hd=/\r\n|\r|\n/;class na{constructor(A){n(this,me);n(this,zt);E(this,me,A),E(this,zt,0)}skipEmptyLines(){let A=0;for(;s(this,me)[s(this,zt)]==="";)ft(this,zt)._++,A++;return A}readLine(){return s(this,me)[ft(this,zt)._++]}takeUntilEmptyLine(){const A=[];for(;s(this,me)[s(this,zt)]!=="";){const t=this.readLine();if(t===void 0)break;A.push(t)}return A}linesLeft(){return s(this,me).length-s(this,zt)}}me=new WeakMap,zt=new WeakMap;class aa{constructor(){n(this,oi)}parse(A){const t=[],e=A.split(hd),g=new na(e),B=g.readLine();if(!B||!B.startsWith("WEBVTT"))throw new Error("missing 'WEBVTT' signature");for(;g.readLine()!=="";);for(;g.linesLeft()>0;){const C=d(this,oi,zE).call(this,g);C&&t.push(C),g.skipEmptyLines()}return t}}oi=new WeakSet,zE=function(A){A.skipEmptyLines();const t=A.takeUntilEmptyLine(),e=new na(t);let g=e.readLine(),B;if(g!=null&&g.startsWith("NOTE"))return;if(g!=null&&g.includes("-->")||(B=g,g=e.readLine()),g===void 0)throw new Error("expected cue line");const[C,Q]=g.split("-->").map(m=>m.trim());if(!C||!Q)throw new Error(`a cue needs both start and end time start: ${C} end: ${Q}`);const[o,a]=Q.split(" ",1).map(m=>m.trim());if(!o)throw new Error(`missing end time: ${o}`);const c=e.readLine();if(!c)throw new Error("missing text");const h=d(this,oi,Qn).call(this,C),l=d(this,oi,Qn).call(this,o);return{id:B,startTime:h,endTime:l,text:c}},Qn=function(A){const t=A.split(":");if(t.length==2){const[Q=0,o=0]=t.map(c=>parseFloat(c));return Q*60+o}const[e=0,g=0,B=0]=t.map(Q=>parseFloat(Q));return e*60*60+g*60+B};const dd=i=>{const A=window;A.vindralInstances=A.vindralInstances||{},A.vindralInstances[i.getStatistics().clientId.substring(0,8)]=i};class TQ extends it{constructor({type:t,autoplay:e,muted:g,logger:B,poster:C}){super();I(this,"element");I(this,"logger");I(this,"seekTimes",new W(10));I(this,"seekStartTime");I(this,"_userProvidedMuted");I(this,"timers",new NA);I(this,"_userHasProvidedInput",!1);I(this,"_isPaused",!0);I(this,"isActivated",!1);I(this,"dummy");I(this,"_iosHackEnterPiPMode",()=>{const t=this.element.parentElement,e=this.element.clientWidth/this.element.clientHeight;this.element.style.position="fixed",this.element.style.opacity="0",this.element.style.pointerEvents="none",t&&(this.dummy=document.createElement("video"),this.dummy.style.paddingBottom="calc(100% / "+e+")",this.dummy.style.width="100%",this.dummy.style.height="0px",t.appendChild(this.dummy))});I(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)});I(this,"attach",t=>{this.element.remove(),t.appendChild(this.element)});I(this,"load",()=>{this.timers.setInterval(this.onPlayPause,500),this.timers.setTimeout(()=>{this.timers.setInterval(this.onBufferStateChange,500)},1e4)});I(this,"unload",()=>{this.timers.unload()});I(this,"getPlaybackRate",()=>this.element.playbackRate);I(this,"getPlaybackState",()=>this.element.readyState>=this.element.HAVE_FUTURE_DATA?"playing":"buffering");I(this,"setPlaybackRate",t=>void(this.element.playbackRate=t));I(this,"getBuffer",()=>{const t=[],e=this.element.buffered;if(!e)return[];for(let g=0;g<e.length;g++)t.push({start:e.start(g)*1e3,end:e.end(g)*1e3});return t});I(this,"pause",()=>{this._isPaused=!1,this.element.pause()});I(this,"tryPlay",()=>{this.element.muted=this._userProvidedMuted,this._play().catch(F)});I(this,"play",()=>{this.element.muted=this._userProvidedMuted,this._play().catch(t=>{if(t instanceof Error){const e=new x("Media Play Error",{source:t,isFatal:!1,code:"media_play_error"});this.emit("error",e)}})});I(this,"_play",()=>r(this,null,function*(){try{yield this.element.play(),this._userHasProvidedInput=!this.muted||this._userProvidedMuted}catch(t){if(t instanceof Error&&t.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 t}}));I(this,"onEvent",t=>{this.logger.trace(t.type,{state:this.element.readyState,event:t,playbackState:this.getPlaybackState()})});I(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})});I(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"))});I(this,"onBufferStateChange",()=>{this.emit("buffer state",{isPaused:this.element.paused,buffered:this.getBuffer(),currentTime:this.currentTime,playbackState:this.getPlaybackState()})});I(this,"onSeekStart",()=>{this.seekStartTime=Date.now()});I(this,"onSeekEnd",()=>{this.seekStartTime&&(this.seekTimes.push(Date.now()-this.seekStartTime),this.seekStartTime=void 0)});this.logger=B,this._userProvidedMuted=g,this.element=document.createElement(t),this.element instanceof HTMLVideoElement&&(this.element.playsInline=!0),this.element.controls=!1,this.element.autoplay=e,this.element.muted=g,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||!C||this.element.setAttribute("poster",C)},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:Wt(this.seekTimes.items())}get isSeeking(){return this.element.seeking}get currentTime(){return isNaN(this.element.currentTime)?0:this.element.currentTime*1e3}set currentTime(t){Number.isFinite(t)&&(this.element.currentTime=t/1e3)}get playbackRate(){return this.element.playbackRate}set playbackRate(t){this.element.playbackRate=t}get volume(){return this.element.volume}set volume(t){this.element.volume=t}get muted(){return this.element.muted}set muted(t){this._userProvidedMuted=t,this.element.muted=t}get userHasProvidedInput(){return this._userHasProvidedInput}get isPaused(){return this._isPaused}}const ld=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 je(i)?A={type:"media-source",audio:{contentType:ze(i),bitrate:i.bitRate,channels:i.channels.toString(),samplerate:i.sampleRate}}:A={type:"media-source",video:{contentType:ze(i),bitrate:i.bitRate,width:i.width,height:i.height,framerate:i.frameRate[0]/i.frameRate[1]}},navigator.mediaCapabilities.decodingInfo(A)},ud=.15,wd=.2,Ea=.4,Dd=.5,md=.6,PQ=15,Sd={cooldownTime:3e3,maxBufferingEvents:{last10Seconds:0},maxBufferingRatio:{last10Seconds:0},maxRecentDowngradesCount:3,maxDowngradeLookbackMs:60*1e3,minTimeSpentPlaying:{factor:.5,ratio:.1},maxCooldownRatio:2},xQ=i=>A=>A>i,pC=class pC{constructor(A,t,e,g){I(this,"qualityOfServiceSource");I(this,"config");I(this,"emitter");I(this,"logger");I(this,"isSuspended",!1);I(this,"lastAdaptTime",Date.now());I(this,"isEnabled",!0);I(this,"load",()=>{this.emitter.on("buffer state",this.onBufferState),this.emitter.on("adapted level",this.onAdaptedLevel)});I(this,"unload",()=>{this.emitter.off("buffer state",this.onBufferState),this.emitter.off("adapted level",this.onAdaptedLevel)});I(this,"suspend",()=>{this.isSuspended=!0});I(this,"unsuspend",()=>{this.reset(),this.isSuspended=!1});I(this,"reset",(A=0)=>{this.lastAdaptTime=Date.now()+A});I(this,"getStatistics",()=>({isAbrEnabled:this.isEnabled}));I(this,"isQoSOk",A=>{const t=this.qualityOfServiceSource.getLevelStats(A),{upgradesFromLevel:e,downgradesFromLevel:g}=t!=null?t:{upgradesFromLevel:[],downgradesFromLevel:[]},B=Date.now()-this.config.maxDowngradeLookbackMs,C=g.filter(xQ(B)).length,Q=e.filter(xQ(B)).length;if(C-Q>this.config.maxRecentDowngradesCount)return this.logger.debug("Recent downgrades count is over maximum",{downgrades:C-Q,maxRecentDowngradesCount:this.config.maxRecentDowngradesCount}),!1;const o=this.qualityOfServiceSource.timeSpentPlayingInAtLeastLevelRatio(A),a=this.qualityOfServiceSource.timeActive()-this.qualityOfServiceSource.timeSpentBuffering(),c=o*a/this.config.maxDowngradeLookbackMs;if(C>1&&c<this.config.minTimeSpentPlaying.factor)return this.logger.debug("Time spent playing is too low",{recentDowngrades:C,timeSpentPlayingInAtLeastLevelRatio:o}),!1;if(C>1&&o<this.config.minTimeSpentPlaying.ratio)return this.logger.debug("Time spent playing in at least this level is too low",{recentDowngrades:C,timeSpentPlayingInAtLeastLevelRatio:o}),!1;const h=Math.max(0,g.length-e.length-c),l=Date.now()-this.config.maxDowngradeLookbackMs*h,m=g.filter(xQ(l)).length;return m&&h>this.config.maxCooldownRatio?(this.logger.debug("Too many downgrades compared to time spent playing",{downgradesWithinCooldownTime:m,cooldownRatio:h}),!1):!0});I(this,"onBufferState",A=>{if(!this.isEnabled||this.isSuspended||this.lastAdaptTime+this.config.cooldownTime>Date.now())return;const{bufferFullness:t,general:e}=this.qualityOfServiceSource.getMetrics(),g=this.qualityOfServiceSource.getBufferFullnessRegression();if(!g)return;const B=10*1e3,C=30*1e3,{slope:Q}=g,o=g.predict(PQ),a=Q<0,c=g.predict(PQ)<Ea&&g.slope<0,h=g.predict(PQ)>md,l=this.qualityOfServiceSource.timeSpentBufferingLast(C),m=this.qualityOfServiceSource.timeSpentActiveLast(C),y=this.qualityOfServiceSource.bufferingEventsLast(C),f=m>0?l/m:0,k=this.qualityOfServiceSource.getTargetBufferTime();if(t<.15&&f>.8){this.adaptLevel("reconnect");return}if(e.decodeRate<=1){this.adaptLevel("downgrade");return}if(t>Dd&&h&&!this.tooMuchTimeBuffering(B)&&!this.tooManyBufferingEvents(B)){this.adaptLevel("upgrade");return}if(k<1e3){A.playbackState==="buffering"&&(y>5||f>.3)&&this.adaptLevel("downgrade");return}(c||t<ud)&&a&&t<Ea&&o<wd&&this.adaptLevel(A.playbackState==="buffering"?"double downgrade":"downgrade")});I(this,"onAdaptedLevel",()=>{this.reset()});I(this,"adaptLevel",A=>this.emitter.emit("adapt level",A));this.qualityOfServiceSource=e,this.config=D(D({},Sd),g),this.emitter=A,this.logger=t}tooMuchTimeBuffering(A){const t=this.qualityOfServiceSource.timeSpentActiveLast(A);return(t?this.qualityOfServiceSource.timeSpentBufferingLast(A)/t:0)>this.config.maxBufferingRatio.last10Seconds}tooManyBufferingEvents(A){return this.qualityOfServiceSource.timeSpentBufferingLast(A)>this.config.maxBufferingEvents.last10Seconds}};I(pC,"create",(A,t,e,g={})=>new pC(A,t,e,g));let WQ=pC;const yd={minBufferTime:1500,maxBufferTime:1500,cooldownTime:3e4,maxBufferingEvents:{last30Seconds:3},maxBufferingRatio:{last30Seconds:.15}},Se=class Se{constructor(A,t,e,g,B){I(this,"qualityOfServiceSource");I(this,"targetBufferTimeTarget");I(this,"config");I(this,"emitter");I(this,"logger");I(this,"isSuspended",!1);I(this,"lastIncreaseTime",Date.now());I(this,"bufferTimeAdjustmentCount",0);I(this,"load",()=>{this.emitter.on("buffer state",this.onBufferState)});I(this,"unload",()=>{this.emitter.off("buffer state",this.onBufferState)});I(this,"suspend",()=>{this.isSuspended=!0});I(this,"unsuspend",()=>{this.reset(),this.isSuspended=!1});I(this,"reset",()=>{this.lastIncreaseTime=Date.now()});I(this,"getStatistics",()=>({bufferTimeAdjustmentCount:this.bufferTimeAdjustmentCount}));I(this,"onBufferState",A=>{const{minBufferTime:t,maxBufferTime:e,cooldownTime:g}=this.config;if(this.isSuspended||this.lastIncreaseTime+g>Date.now()||this.targetBufferTimeTarget.targetBufferTime>=e)return;const B=this.qualityOfServiceSource.timeSpentBufferingLast(30*1e3),C=this.qualityOfServiceSource.bufferingEventsLast(30*1e3),Q=this.qualityOfServiceSource.timeSpentActiveLast(30*1e3),o=B/Q,a=Math.ceil(Math.max((e-t)/(Se.BUFFER_TIME_MAX_STEPS-1),Se.BUFFER_TIME_STEP_SIZE));(o>this.config.maxBufferingRatio.last30Seconds||C>this.config.maxBufferingEvents.last30Seconds)&&(this.targetBufferTimeTarget.targetBufferTime=Math.min(e,this.targetBufferTimeTarget.targetBufferTime+a),this.bufferTimeAdjustmentCount++,this.reset())});this.qualityOfServiceSource=e,this.targetBufferTimeTarget=g,this.config=D(D({},yd),B),this.emitter=A,this.logger=t}updateConfig(A){this.config=D(D({},this.config),A)}};I(Se,"BUFFER_TIME_STEP_SIZE",500),I(Se,"BUFFER_TIME_MAX_STEPS",3),I(Se,"create",(A,t,e,g,B={})=>new Se(A,t,e,g,B));let OQ=Se;const fd=i=>i?{Authorization:`Bearer ${i}`}:void 0,pd=(i,A)=>{try{const t=i.ancestorOrigins;if(t&&t.length>0)return Array.from(t).join(",")||void 0}catch(t){}try{if(A.referrer)return new URL(A.referrer).origin||void 0}catch(t){}},Fd=i=>typeof i=="object"&&i!==null&&"message"in i;class Gd extends Error{constructor({status:t,url:e,body:g}){const B=pn(g),C=Fd(B)?B.message:`Url ${e.toString()}, Status code: ${t}, Body: ${g}`;super(C);I(this,"status");I(this,"body");I(this,"url");this.status=t,this.body=g,this.url=e,Object.setPrototypeOf(this,new.target.prototype)}}const kd=i=>typeof i.status=="number",Rd=()=>{if(!(typeof window=="undefined"||typeof document=="undefined"))return pd(window.location,document)},Ud=i=>{const A=Rd();if(!A||i.searchParams.has("parentOrigin"))return i;const t=new URL(i.toString());return t.searchParams.append("parentOrigin",A),t},ra=(i,A)=>r(null,null,function*(){const t=Ud(i),e=yield fetch(t.toString(),D({mode:"cors"},A));if(!e.ok)throw new Gd({status:e.status,url:t,body:yield e.text()});return e}),VQ=(i,A)=>r(null,null,function*(){return yield(yield ra(i,D({},A))).json()}),ca=(i,A)=>r(null,null,function*(){return ra(i,D({method:"POST"},A))});function Nd(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 ha={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 da{constructor(A){I(this,"baseUrl");I(this,"tokenFactory");this.baseUrl=new URL("/api/v4/",A.publicEndpoint).toString(),this.tokenFactory=A.tokenFactory}connect(A){return r(this,null,function*(){const{channelId:t,channelGroupId:e}=A,g={channelId:t,channelGroupId:e},B=new URL(ha.lbConnect(A),this.baseUrl),C=this.getAuthToken(g),Q=yield VQ(B,{headers:this.getHeaders(C)});if(Nd(Q)){const o=Q.channels.map(a=>{const c=this.toChannel(a,g),h=Un(a.catalog);return V(D(D({},a),c),{renditions:h})});return V(D({},Q),{channels:o})}else{const o=Q.channels.map(a=>{const c=this.toChannel(a,g);return D(D({},a),c)});return V(D({},Q),{channels:o})}})}getChannel(A){return r(this,null,function*(){const t={channelId:A},e=new URL(`channel/${A}`,this.baseUrl),g=this.getAuthToken(t),B=yield VQ(e,{headers:this.getHeaders(g)});return this.toChannel(B,t,g)})}getChannels(A){return r(this,null,function*(){const t={channelGroupId:A},e=new URL(`channels/${A}`,this.baseUrl),g=this.getAuthToken(t),B=yield VQ(e,{headers:this.getHeaders(g)}),C=Array.isArray(B)?B:B.channels;return this.toChannels(C,t,g)})}getHeaders(A){var e;return(e=fd(A))!=null?e:{}}getAuthToken(A){return this.tokenFactory?this.tokenFactory(A):void 0}toChannels(A,t,e){return A.map(g=>this.toChannel(g,t,e))}toChannel(A,t,e){const{baseUrl:g,sizes:B}=A.thumbnail,C=g||new URL(ha.thumbnails(t,e),this.baseUrl),Q=B.map(o=>new URL(`?channelId=${A.channelId}&width=${o.width}&height=${o.height}${bd(t,e)}`,C).toString());return{channelId:A.channelId,name:A.name,isLive:A.isLive,thumbnailUrls:Q}}}const bd=(i,A)=>A?i.channelGroupId?`&channelGroupId=${i.channelGroupId}&auth.token=${A}&auth.type=jwt`:`&auth.token=${A}&auth.type=jwt`:"";var AC=(i=>(i[i.StreamHeaderGroup=4]="StreamHeaderGroup",i[i.FetchHeader=5]="FetchHeader",i[i.StreamHeaderTrack=60]="StreamHeaderTrack",i))(AC||{});const KA={Normal:0,ObjectDoesNotExist:1,GroupDoesNotExist:2,EndOfGroup:3,EndOfTrackAndGroup:4};function la(i){switch(i){case KA.Normal:case KA.ObjectDoesNotExist:case KA.GroupDoesNotExist:case KA.EndOfGroup:case KA.EndOfTrackAndGroup:return}throw new Error("Unknown object status "+i)}class Ld{constructor(A,t,e,g,B,C){n(this,kt);n(this,oI);n(this,nI);n(this,os);n(this,ns);n(this,aI,new $);n(this,as,0);n(this,Es);E(this,kt,A),E(this,oI,t),E(this,nI,e),E(this,os,g),E(this,ns,B),E(this,Es,C)}endStatus(){return s(this,aI).promise}groupId(){return s(this,oI)}subscribeId(){return s(this,nI)}next(){return r(this,null,function*(){if(!s(this,aI).pending)return{done:!0,value:void 0};if(yield s(this,kt).isDone())return{done:!0,value:void 0};const A=s(this,as)===0?s(this,oI):yield s(this,kt).readBigVarInt(),t=yield s(this,kt).readBigVarInt(),e=yield s(this,kt).readVarInt();let g=0,B=new Uint8Array;return e>0?B=yield s(this,kt).read(e):g=yield s(this,kt).readVarInt(),la(g),(g===KA.EndOfTrackAndGroup||g===KA.EndOfGroup)&&s(this,aI).resolve(g),ft(this,as)._++,{done:!1,value:{subscribeId:s(this,nI),trackAlias:s(this,os),groupId:A,subGroupId:v(0),objectId:t,subscriberPriority:s(this,ns),streamId:s(this,Es),objectStatus:g,payload:B}}})}return(){return r(this,null,function*(){for(;!(yield this.next()).done;);return{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[pt()](){return Promise.resolve()}[Symbol.asyncDispose](){return Promise.resolve()}}kt=new WeakMap,oI=new WeakMap,nI=new WeakMap,os=new WeakMap,ns=new WeakMap,aI=new WeakMap,as=new WeakMap,Es=new WeakMap;class Jd{constructor(A,t,e,g,B){n(this,ni);n(this,Rt);n(this,EI);n(this,rs);n(this,cs);n(this,rI);E(this,Rt,A),E(this,EI,t),E(this,rs,e),E(this,cs,g),E(this,rI,B)}streamId(){return s(this,rI)}groups(){return d(this,ni,_E).call(this)}subscribeId(){return s(this,EI)}return(){return r(this,null,function*(){return yield s(this,Rt).close(),{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[pt()](){return d(this,ni,on).call(this)}[Symbol.asyncDispose](){return d(this,ni,on).call(this)}}Rt=new WeakMap,EI=new WeakMap,rs=new WeakMap,cs=new WeakMap,rI=new WeakMap,ni=new WeakSet,_E=function(){return Ee(this,null,function*(){for(;!(yield new EA(s(this,Rt).isDone()));){const A=yield new EA(s(this,Rt).readBigVarInt()),t=new Ld(s(this,Rt),A,s(this,EI),s(this,rs),s(this,cs),s(this,rI));if(yield t,(yield new EA(Promise.race([t.endStatus(),s(this,Rt).closed()])))===KA.EndOfTrackAndGroup)return}})},on=function(){return s(this,Rt).close().catch(()=>{})};class Md{constructor(A,t,e,g,B,C,Q){n(this,ai);n(this,dt);n(this,cI);n(this,hs);n(this,hI);n(this,ds);n(this,ls);n(this,us,!1);n(this,dI);n(this,FC,UA.get().createContext("GroupReader"));E(this,dt,A),E(this,cI,t),E(this,hs,e),E(this,hI,g),E(this,ds,B),E(this,ls,C),E(this,dI,Q)}streamId(){return s(this,dI)}groupId(){return s(this,hI)}subscribeId(){return s(this,cI)}next(){return r(this,null,function*(){try{if((yield s(this,dt).isDone())||s(this,us))return{done:!0,value:void 0};const A=yield s(this,dt).readBigVarInt(),t=yield s(this,dt).readVarInt();let e=0,g=new Uint8Array;return t>0?g=yield s(this,dt).read(t):e=yield s(this,dt).readVarInt(),la(e),e===KA.EndOfGroup&&E(this,us,!0),{done:!1,value:{subscribeId:s(this,cI),trackAlias:s(this,hs),groupId:s(this,hI),subGroupId:s(this,ds),subscriberPriority:s(this,ls),streamId:s(this,dI),objectId:A,objectStatus:e,payload:g}}}catch(A){return s(this,FC).info("Error reading object",{error:A}),{done:!0,value:void 0}}})}return(){return r(this,null,function*(){return yield s(this,dt).close().catch(()=>{}),{done:!0,value:void 0}})}groups(){return d(this,ai,$E).call(this)}[Symbol.asyncIterator](){return this}[pt()](){return d(this,ai,nn).call(this)}[Symbol.asyncDispose](){return d(this,ai,nn).call(this)}}dt=new WeakMap,cI=new WeakMap,hs=new WeakMap,hI=new WeakMap,ds=new WeakMap,ls=new WeakMap,us=new WeakMap,dI=new WeakMap,FC=new WeakMap,ai=new WeakSet,$E=function(){return Ee(this,null,function*(){yield this})},nn=function(){return s(this,dt).close().catch(()=>{})};function ua(i,A){return r(this,null,function*(){const t=yield i.readVarInt();switch(t){case AC.StreamHeaderGroup:{const e=yield i.readBigVarInt(),g=yield i.readBigVarInt(),B=yield i.readBigVarInt(),C=yield i.readBigVarInt(),Q=yield i.readUnsigned8();return new Md(i,e,g,B,C,Q,A)}case AC.StreamHeaderTrack:{const e=yield i.readBigVarInt(),g=yield i.readBigVarInt(),B=yield i.readUnsigned8();return new Jd(i,e,g,B,A)}default:throw new Error("Unexpected message type "+t)}})}class Hd{constructor(A,t){n(this,ye);n(this,ws);E(this,ye,A),E(this,ws,t)}start(A){s(this,ye).addEventListener("message",t=>{if(typeof t.data=="object"&&t.data instanceof ArrayBuffer){const e=new Uint8Array(t.data);e[0]==s(this,ws)&&A.enqueue(e.subarray(1))}}),s(this,ye).addEventListener("error",()=>A.error(new Error("WebSocket error"))),s(this,ye).addEventListener("close",()=>fn(()=>A.close()))}cancel(A){s(this,ye).close(void 0,A)}}ye=new WeakMap,ws=new WeakMap;class qd{constructor(A){n(this,Ut);n(this,Ei,null);n(this,ri,null);n(this,ci,null);E(this,Ut,A)}start(A){E(this,Ei,t=>{if(typeof t.data=="object"&&t.data instanceof ArrayBuffer){const e=new Uint8Array(t.data),g=e[0]||0,B=g&127,C=(g>>7&1)>0;if(B&&B!==0){const Q=e.subarray(1);A.enqueue([C,B,Q])}}}),E(this,ri,()=>fn(()=>A.close())),E(this,ci,()=>A.error(new Error("WebSocket error"))),s(this,Ut).addEventListener("message",s(this,Ei)),s(this,Ut).addEventListener("error",s(this,ci)),s(this,Ut).addEventListener("close",s(this,ri))}cancel(A){s(this,Ei)&&s(this,Ut).removeEventListener("message",s(this,Ei)),s(this,ci)&&s(this,Ut).removeEventListener("error",s(this,ci)),s(this,ri)&&s(this,Ut).removeEventListener("close",s(this,ri))}}Ut=new WeakMap,Ei=new WeakMap,ri=new WeakMap,ci=new WeakMap;class tC{constructor(A,t){n(this,BA);n(this,Nt);n(this,Ds);n(this,hi);n(this,bt,0);n(this,GC,new TextDecoder);E(this,Nt,A),E(this,Ds,t),E(this,hi,t.getReader())}readUnsigned8(){return r(this,null,function*(){return yield d(this,BA,Vi).call(this,1),d(this,BA,Pe).call(this,1)[0]})}readString(){return r(this,null,function*(){const A=yield this.readVarInt(),t=yield this.read(A);return s(this,GC).decode(t)})}readVarInt(){return r(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 r(this,null,function*(){yield d(this,BA,Vi).call(this,1);const A=(d(this,BA,lQ).call(this,1)[0]&192)>>6;switch(s(this,Nt)[s(this,bt)]=d(this,BA,lQ).call(this,1)[0]&63,A){case 0:return v(d(this,BA,Pe).call(this,1)[0]);case 1:{yield d(this,BA,Vi).call(this,2);const t=d(this,BA,Pe).call(this,2),e=new DataView(t.buffer,t.byteOffset,t.byteLength);return v(e.getUint16(0))}case 2:{yield d(this,BA,Vi).call(this,4);const t=d(this,BA,Pe).call(this,4),e=new DataView(t.buffer,t.byteOffset,t.byteLength);return v(e.getUint32(0))}case 3:{yield d(this,BA,Vi).call(this,8);const t=d(this,BA,Pe).call(this,8),e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(typeof e.getBigUint64!="undefined")return v(e.getBigUint64(0));const g=Oe(t,0,7);return v(g)}default:throw new Error("Invalid VarInt size")}})}read(A){return r(this,null,function*(){return yield d(this,BA,Vi).call(this,A),d(this,BA,Pe).call(this,A)})}readAll(){return r(this,null,function*(){for(;yield d(this,BA,dQ).call(this););return d(this,BA,Pe).call(this,d(this,BA,yB).call(this))})}isDone(){return r(this,null,function*(){return d(this,BA,yB).call(this)>0?!1:(yield d(this,BA,dQ).call(this))==0})}closed(){return r(this,null,function*(){return s(this,hi).closed})}close(){return r(this,null,function*(){return s(this,hi).releaseLock(),s(this,Ds).cancel()})}}Nt=new WeakMap,Ds=new WeakMap,hi=new WeakMap,bt=new WeakMap,GC=new WeakMap,BA=new WeakSet,yB=function(){return s(this,Nt).length-s(this,bt)},dQ=function(){return r(this,null,function*(){const{value:A,done:t}=yield s(this,hi).read();if(t)return Promise.resolve(0);if(d(this,BA,yB).call(this)===0)E(this,Nt,A);else{const g=s(this,Nt).subarray(s(this,bt)),B=new Uint8Array(g.length+A.length);B.set(g),B.set(A,g.byteLength),E(this,Nt,B)}return E(this,bt,0),Promise.resolve(A.length)})},Vi=function(A){return r(this,null,function*(){for(;d(this,BA,yB).call(this)<A;)if((yield d(this,BA,dQ).call(this))===0)throw new Error("Read failed")})},lQ=function(A){return s(this,Nt).subarray(s(this,bt),s(this,bt)+A)},Pe=function(A){const t=d(this,BA,lQ).call(this,A);return E(this,bt,s(this,bt)+t.length),t};class wa{constructor(A){n(this,lI,new Uint8Array(8));n(this,uI);n(this,_t);n(this,kC,new TextEncoder);E(this,uI,A),E(this,_t,s(this,uI).getWriter())}writeString(A){return r(this,null,function*(){const t=s(this,kC).encode(A);return yield this.writeVarInt(t.length),this.write(t)})}write(A){return s(this,_t).write(A)}writeUnsigned8(A){return s(this,_t).write(eC(A,s(this,lI)))}writeVarInt(A){return s(this,_t).write(ka(A,s(this,lI)))}writeBigVarInt(A){return s(this,_t).write(Ra(A,s(this,lI)))}flush(){return r(this,null,function*(){})}close(){return r(this,null,function*(){s(this,_t).releaseLock(),yield s(this,uI).close()})}}lI=new WeakMap,uI=new WeakMap,_t=new WeakMap,kC=new WeakMap;const Da={OPEN:1},ms=class ms{constructor(A){n(this,jA,0);n(this,zA,new Uint8Array(ms.DEFAULT_BUFFER_SIZE));n(this,di);n(this,RC,new TextEncoder);E(this,di,A)}writeString(A){return r(this,null,function*(){const t=s(this,RC).encode(A);return yield this.writeVarInt(t.length),this.write(t)})}ensureBufferSpace(A){if(s(this,zA).length-s(this,jA)>=A)return;const t=new Uint8Array(s(this,zA).length+A);t.set(s(this,zA)),E(this,zA,t)}write(A){return this.ensureBufferSpace(A.length),s(this,zA).set(A,s(this,jA)),E(this,jA,s(this,jA)+A.byteLength),Promise.resolve()}writeUnsigned8(A){return this.ensureBufferSpace(1),eC(A,s(this,zA).subarray(s(this,jA))),E(this,jA,s(this,jA)+1),Promise.resolve()}writeVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return this.ensureBufferSpace(8),E(this,jA,s(this,jA)+ka(A,s(this,zA).subarray(s(this,jA))).byteLength),Promise.resolve()}writeBigVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return this.ensureBufferSpace(8),E(this,jA,s(this,jA)+Ra(A,s(this,zA).subarray(s(this,jA))).byteLength),Promise.resolve()}flush(){if(s(this,di).readyState!==Da.OPEN)throw new Error("Writer is not open");return s(this,di).send(s(this,zA).subarray(0,s(this,jA))),E(this,jA,0),E(this,zA,new Uint8Array(ms.DEFAULT_BUFFER_SIZE)),Promise.resolve()}close(){return s(this,di).close(),Promise.resolve()}};jA=new WeakMap,zA=new WeakMap,di=new WeakMap,RC=new WeakMap,I(ms,"DEFAULT_BUFFER_SIZE",1024);let kg=ms;const ma=2**6-1,Sa=2**14-1,ya=2**30-1,vd=Number.MAX_SAFE_INTEGER,Kd=typeof BigInt=="function"?v(2)**v(62)-v(1):v(Number.MAX_SAFE_INTEGER);function eC(i,A){return A[0]=i,A.subarray(0,1)}function fa(i,A){const t=new DataView(A.buffer,A.byteOffset,2);return t.setUint16(0,i),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function pa(i,A){const t=new DataView(A.buffer,A.byteOffset,4);return t.setUint32(0,i),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function Fa(i,A){const t=new DataView(A.buffer,A.byteOffset,8);return t.setBigUint64(0,i),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function Ga(i,A){const t=new DataView(A.buffer,A.byteOffset,8);return t.setUint32(0,i/4294967296),t.setUint32(4,i&4294967295),A.set([192],0),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function ka(i,A){if(i<=ma)return eC(i,A);if(i<=Sa)return fa(i|16384,A);if(i<=ya)return pa(i|2147483648,A);if(i<=vd)return typeof BigInt=="function"?Fa(BigInt(i)|BigInt(3221225472)<<BigInt(32),A):Ga(Number(i),A);throw new Error(`overflow, value larger than 53-bits: ${i}`)}function Ra(i,A){if(i<ma)return eC(Number(i),A);if(i<Sa)return fa(Number(i)|16384,A);if(i<=ya)return pa(Number(i)|2147483648,A);if(i<=Kd)return typeof BigInt=="function"?Fa(BigInt(i)|BigInt(3221225472)<<BigInt(32),A):Ga(Number(i),A);throw new Error(`overflow, value larger than 62-bits: ${i}`)}var b=(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))(b||{});function iC(i){return r(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 t=[];for(let e=0;e<A;e++)t.push(yield i.readString());return t})}function ZQ(i,A){return r(this,null,function*(){yield i.writeVarInt(A.length);for(const t of A)yield i.writeString(t)})}const IC=v(2);function $i(i){return r(this,null,function*(){const A=yield i.readVarInt(),t=new Map;for(let e=0;e<A;e++){const g=yield i.readBigVarInt(),B=yield i.read(yield i.readVarInt());t.set(g,{type:g,payload:B})}return t})}function AI(i,A){return r(this,null,function*(){yield i.writeVarInt(A.size);for(const[t,e]of A)yield i.writeBigVarInt(t),yield i.writeVarInt(e.payload.length),yield i.write(e.payload)})}function Yd(i){return r(this,null,function*(){return{type:b.Announce,namespace:yield iC(i),params:yield $i(i)}})}function Td(i,A){return r(this,null,function*(){yield ZQ(i,A.namespace),yield AI(i,A.params)})}function Pd(i){return r(this,null,function*(){return{type:b.AnnounceOk,namespace:yield iC(i)}})}function xd(i,A){return r(this,null,function*(){yield ZQ(i,A.namespace)})}const Wd={"latest-group":1,"latest-object":2,"absolute-start":3,"absolute-range":4};function Od(i){return r(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 Vd(i,A){return r(this,null,function*(){const t=Wd[A.type];switch(yield i.writeVarInt(t),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 ${t}`)}})}function Ua(i){return r(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 Na(i,A){return r(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 Zd(i){return r(this,null,function*(){const A=yield i.readBigVarInt(),t=yield i.readBigVarInt(),e=yield iC(i),g=yield i.readString(),B=yield i.readUnsigned8(),C=yield Ua(i),Q=yield Od(i),o=yield $i(i);if(Q.type==="absolute-range"){const a=Q.start.group>Q.end.group,c=Q.start.group===Q.end.group&&Q.start.object>Q.end.object;if(a||c)throw new Error("Invalid filter range")}return{type:b.Subscribe,id:A,trackAlias:t,namespace:e,name:g,subscriberPriority:B,groupOrder:C,filterType:Q,params:o}})}function Xd(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.trackAlias),yield ZQ(i,A.namespace),yield i.writeString(A.name),yield i.writeUnsigned8(A.subscriberPriority),yield Na(i,A.groupOrder),yield Vd(i,A.filterType),yield AI(i,A.params)})}const XQ={TrackEnded:3,Expired:6};function jd(i){return r(this,null,function*(){const A=yield i.readBigVarInt(),t=yield i.readVarInt(),e=yield i.readString(),g=(yield i.readUnsigned8())==1;let B;return g&&(B={group:yield i.readBigVarInt(),object:yield i.readBigVarInt()}),{type:b.SubscribeDone,id:A,errorCode:t,reason:e,finalInfo:B}})}function zd(i,A){return r(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 _d(i){return r(this,null,function*(){return{type:b.SubscribeError,id:yield i.readBigVarInt(),errorCode:yield i.readBigVarInt(),reason:yield i.readString(),trackAlias:yield i.readBigVarInt()}})}function $d(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.errorCode),yield i.writeString(A.reason),yield i.writeBigVarInt(A.trackAlias)})}function Al(i){return r(this,null,function*(){const A=yield i.readBigVarInt(),t=yield i.readBigVarInt(),e=yield Ua(i),g=(yield i.readUnsigned8())==1;let B;if(e=="inherit-publisher")throw new Error("SusbcribeOk cannot have inherit publisher group order");g&&(B={group:yield i.readBigVarInt(),object:yield i.readBigVarInt()});const C=yield $i(i);return{type:b.SubscribeOk,id:A,groupOrder:e,expires:t,largestInfo:B,params:C}})}function tl(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.expires),yield Na(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 AI(i,A.params)})}function el(i){return r(this,null,function*(){const A=yield i.readBigVarInt(),t=yield i.readBigVarInt(),e=yield i.readBigVarInt(),g=yield i.readBigVarInt(),B=yield i.readBigVarInt(),C=yield i.readUnsigned8(),Q=yield $i(i),o=t>g,a=t===g&&e>B;if(o||a)throw new Error("Invalid filter range");return{type:b.SubscribeUpdate,id:A,start:{group:t,object:e},end:{group:g,object:B},subscriberPriority:C,params:Q}})}function il(i,A){return r(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 AI(i,A.params)})}const Il={Subscriber:2},gC={Role:v(0)},ba={Draft07:4278190087};function La(i){return r(this,null,function*(){const A=yield i.readVarInt();switch(A){case ba.Draft07:return{type:"known",value:A};default:return{type:"unknown",value:A}}})}function gl(i,A){return r(this,null,function*(){yield i.writeVarInt(A.supportedVersions.length);for(const t of A.supportedVersions)yield i.writeVarInt(t.value);yield AI(i,A.parameters)})}function sl(i){return r(this,null,function*(){const A=[],t=yield i.readVarInt();for(let g=0;g<t;g++)A.push(yield La(i));const e=yield $i(i);if(!e.has(gC.Role))throw new Error("Role parameter is required");return{type:b.ClientSetup,supportedVersions:A,parameters:e}})}function Bl(i,A){return r(this,null,function*(){yield i.writeVarInt(A.selectedVersion.value),yield AI(i,A.parameters)})}function Cl(i){return r(this,null,function*(){const A=yield La(i);if(A.type!=="known")throw new Error("Expected known version");const t=yield $i(i);if(!t.has(gC.Role))throw new Error("Role parameter is required");return{type:b.ServerSetup,selectedVersion:A,parameters:t}})}function Ql(i){return r(this,null,function*(){return{type:b.Unsubscribe,id:yield i.readBigVarInt()}})}function ol(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id)})}class Ja{constructor(A){n(this,hA);n(this,$t);n(this,wI,new Uint8Array);E(this,$t,A)}write(A){return r(this,null,function*(){yield s(this,$t).writeVarInt(A.type);const t=new kg({close:()=>{},readyState:Da.OPEN,send:e=>{E(this,wI,new Uint8Array(e))}});switch(A.type){case b.Subscribe:yield d(this,hA,er).call(this,t,A);break;case b.Announce:yield d(this,hA,Cr).call(this,t,A);break;case b.SubscribeOk:yield d(this,hA,ir).call(this,t,A);break;case b.SubscribeUpdate:yield d(this,hA,gr).call(this,t,A);break;case b.SubscribeError:yield d(this,hA,Ir).call(this,t,A);break;case b.SubscribeDone:yield d(this,hA,sr).call(this,t,A);break;case b.Unsubscribe:yield d(this,hA,Br).call(this,t,A);break;case b.ClientSetup:yield d(this,hA,Ar).call(this,t,A);break;case b.ServerSetup:yield d(this,hA,tr).call(this,t,A);break;case b.AnnounceOk:yield d(this,hA,Qr).call(this,t,A);break;default:throw new Error(`Unknown message type: ${A.type}`)}yield t.flush(),yield s(this,$t).writeVarInt(s(this,wI).byteLength),yield s(this,$t).write(s(this,wI)),yield s(this,$t).flush()})}close(){return r(this,null,function*(){return s(this,$t).close()})}}$t=new WeakMap,wI=new WeakMap,hA=new WeakSet,Ar=function(A,t){return r(this,null,function*(){yield gl(A,t)})},tr=function(A,t){return r(this,null,function*(){yield Bl(A,t)})},er=function(A,t){return r(this,null,function*(){yield Xd(A,t)})},ir=function(A,t){return r(this,null,function*(){yield tl(A,t)})},Ir=function(A,t){return r(this,null,function*(){yield $d(A,t)})},gr=function(A,t){return r(this,null,function*(){yield il(A,t)})},sr=function(A,t){return r(this,null,function*(){yield zd(A,t)})},Br=function(A,t){return r(this,null,function*(){yield ol(A,t)})},Cr=function(A,t){return r(this,null,function*(){yield Td(A,t)})},Qr=function(A,t){return r(this,null,function*(){yield xd(A,t)})};class nl{constructor(A,t){n(this,DI);n(this,Ss);n(this,ys);E(this,DI,A),E(this,Ss,new Ja(A)),E(this,ys,t)}write(A){return r(this,null,function*(){yield s(this,DI).write(s(this,ys)),yield s(this,Ss).write(A)})}close(){return s(this,DI).close()}}DI=new WeakMap,Ss=new WeakMap,ys=new WeakMap;function al(i){return r(this,null,function*(){return{type:b.AnnounceError,namespace:yield iC(i),errorCode:yield i.readBigVarInt(),reason:yield i.readString()}})}function El(i,A,t){return r(this,null,function*(){return{type:b.Unknown,messageType:A,payload:yield i.read(t)}})}class Ma{constructor(A){n(this,fA);E(this,fA,A)}cancel(){return s(this,fA).close()}read(){return r(this,null,function*(){const A=yield s(this,fA).readVarInt(),t=yield s(this,fA).readVarInt();switch(A){case b.ServerSetup:return Cl(s(this,fA));case b.ClientSetup:return sl(s(this,fA));case b.Subscribe:return Zd(s(this,fA));case b.SubscribeOk:return Al(s(this,fA));case b.SubscribeDone:return jd(s(this,fA));case b.SubscribeError:return _d(s(this,fA));case b.SubscribeUpdate:return el(s(this,fA));case b.Unsubscribe:return Ql(s(this,fA));case b.Announce:return Yd(s(this,fA));case b.AnnounceOk:return Pd(s(this,fA));case b.AnnounceError:return al(s(this,fA))}return El(s(this,fA),v(A),t)})}}fA=new WeakMap;const yI=class yI{constructor(A,t){n(this,UC);n(this,fs);n(this,mI);n(this,SI,new $);n(this,ps,new $);E(this,fs,A),E(this,mI,t),s(this,SI).resolve()}write(A){return r(this,null,function*(){const t=yield d(this,UC,or).call(this);try{yield s(this,fs).write(A)}finally{t.resolve()}})}markPostHandshake(){s(this,ps).resolve()}postHandshake(){return s(this,ps).promise}read(){return r(this,null,function*(){return s(this,mI).read()})}cancel(){return s(this,mI).cancel()}static wrapWebsocket(A){const t=new ReadableStream(new Hd(A,s(yI,NC))),e=new Ma(new tC(new Uint8Array([]),t)),g=new nl(new kg(A),new Uint8Array([0]));return new yI(g,e)}static wrapWebTransport(A){const t=A.writable,e=A.readable;return new yI(new Ja(new wa(t)),new Ma(new tC(new Uint8Array,e)))}};fs=new WeakMap,mI=new WeakMap,SI=new WeakMap,ps=new WeakMap,UC=new WeakSet,or=function(){const A=new $,t=s(this,SI).promise.then(()=>A);return E(this,SI,A),t},NC=new WeakMap,n(yI,NC,0);let sC=yI;function Ha(i,A){return r(this,null,function*(){yield i.write({type:b.ClientSetup,supportedVersions:[{type:"known",value:ba.Draft07}],parameters:new Map([[gC.Role,{type:gC.Role,payload:new Uint8Array([A])}]])});const t=yield i.read();if(i.markPostHandshake(),t.type!==b.ServerSetup)throw new Error("Expected server setup message");if(t.selectedVersion.type!=="known")throw new Error("Expected known version")})}class rl{constructor(A){I(this,"announce");n(this,fI,new $);this.announce=A}onOk(A){s(this,fI).resolve(A)}onError(A){const t=new Error(A.reason);return s(this,fI).reject(t),t}ok(){return s(this,fI).promise}}fI=new WeakMap;function cl(i){const A=new rl(i);return new hl(A)}class hl{constructor(A){I(this,"state");this.state=A}}const FI=class FI{constructor(A){I(this,"subscribe");n(this,pI,new $);n(this,fe,new $);n(this,li,new $);n(this,bC,Date.now());n(this,ui,new $);n(this,lt);switch(this.subscribe=A,A.filterType.type){case"absolute-start":E(this,lt,{startGroup:A.filterType.start.group});break;case"absolute-range":E(this,lt,{startGroup:A.filterType.start.group,endGroup:A.filterType.end.group});break}}onUpdate(A){E(this,lt,{startGroup:A.start.group}),A.end.group>v(0)&&(s(this,lt).endGroup=A.end.group-v(1))}onError(A){const t=new Error(A.reason);return s(this,pI).reject(t),s(this,fe).reject(t),t}onDone(A){A.finalInfo&&(s(this,lt)||E(this,lt,{startGroup:v(0)}),s(this,lt).endGroup=A.finalInfo.group),s(this,fe).resolve(A)}onUnsubscribe(A){s(this,li).resolve(A)}onOk(A){const t=Math.max(0,Date.now()-s(this,bC)),e=Number(A.expires);if(e>0){const g=Math.max(FI.minGraceTime,Math.min(e/10,FI.maxGraceTime));Promise.race([ce(e-g-t),this.done().catch(F)]).then(()=>s(this,ui).resolve(this.expiryState())).catch(F)}s(this,pI).resolve(A)}done(){return s(this,fe).promise}ok(){return s(this,pI).promise}range(){return s(this,lt)}close(){s(this,ui).promise.catch(F),s(this,ui).reject(new Error("Subscription closed"))}expiryState(){return s(this,fe).resolved&&s(this,fe).resolved.errorCode!==XQ.Expired?"done":s(this,li).pending?"active":"unsubscribed"}unsubscribed(){return s(this,li).promise}isUnsubscribed(){return s(this,li).resolved}expiryNotification(){return s(this,ui).promise}};pI=new WeakMap,fe=new WeakMap,li=new WeakMap,bC=new WeakMap,ui=new WeakMap,lt=new WeakMap,I(FI,"maxGraceTime",15e3),I(FI,"minGraceTime",3e3);let BC=FI;class dl{constructor(A){n(this,MA);n(this,Fs,!1);E(this,MA,A)}write(A){return r(this,null,function*(){s(this,Fs)||(yield s(this,MA).writeVarInt(AC.StreamHeaderGroup),yield s(this,MA).writeBigVarInt(A.subscribeId),yield s(this,MA).writeBigVarInt(A.trackAlias),yield s(this,MA).writeBigVarInt(A.groupId),yield s(this,MA).writeBigVarInt(A.subGroupId),yield s(this,MA).writeUnsigned8(A.subscriberPriority),E(this,Fs,!0)),yield s(this,MA).writeBigVarInt(A.objectId),yield s(this,MA).writeVarInt(A.payload.length),A.payload.length>0?yield s(this,MA).write(A.payload):yield s(this,MA).writeVarInt(A.objectStatus),yield s(this,MA).flush()})}close(){return r(this,null,function*(){yield s(this,MA).close()})}}MA=new WeakMap,Fs=new WeakMap;class ll{constructor(A,t,e,g){n(this,LC);n(this,Gs);n(this,gt);n(this,ks);n(this,Rs);n(this,GI);n(this,Us);E(this,Gs,t),E(this,gt,A),E(this,ks,e),E(this,Rs,g),E(this,Us,UA.get().createContext(`SubscriptionWriter:${A.subscribe.name}`))}finalInfo(){return s(this,GI)}run(){return r(this,null,function*(){yield Promise.race([d(this,LC,nr).call(this).catch(A=>s(this,Us).error("error writing subscription",A)),s(this,gt).unsubscribed(),s(this,gt).done(),s(this,gt).expiryNotification().catch(F)])})}done(A,t){return r(this,null,function*(){if(s(this,gt).isUnsubscribed())return;const e={type:b.SubscribeDone,id:s(this,gt).subscribe.id,errorCode:A,reason:t,finalInfo:s(this,GI)};s(this,gt).onDone(e),yield s(this,Rs).push(e)})}[pt()](){return this.done(XQ.TrackEnded,"Track ended")}[Symbol.asyncDispose](){return this.done(XQ.TrackEnded,"Track ended")}}Gs=new WeakMap,gt=new WeakMap,ks=new WeakMap,Rs=new WeakMap,GI=new WeakMap,Us=new WeakMap,LC=new WeakSet,nr=function(){return r(this,null,function*(){try{for(var C=rA(s(this,Gs)),Q,o,a;Q=!(o=yield C.next()).done;Q=!1){const c=o.value;var A=[];try{const h=s(this,gt).range();if(h&&(h.startGroup>c.id||h.endGroup&&h.endGroup<c.id))break;const l=yield s(this,ks).openSendStream();const m=new dl(l);const y=ot(A,new ul(m,c.consume(),s(this,gt)),!0);yield y.run();E(this,GI,y.finalGroup())}catch(t){var e=t,g=!0}finally{var B=nt(A,e,g);B&&(yield B)}}}catch(o){a=[o]}finally{try{Q&&(o=C.return)&&(yield o.call(C))}finally{if(a)throw a[0]}}})};class ul{constructor(A,t,e){n(this,wi);n(this,Ns);n(this,kI);n(this,bs);n(this,RI);E(this,wi,A),E(this,Ns,t),E(this,kI,e),E(this,RI,UA.get().createContext(`GroupSubscriptionWriter:${e.subscribe.name}`))}finalGroup(){return s(this,bs)}run(){return r(this,null,function*(){s(this,RI).debug("write group");try{for(var A=rA(s(this,Ns)),t,e,g;t=!(e=yield A.next()).done;t=!1){const B=e.value;yield s(this,wi).write({subscribeId:s(this,kI).subscribe.id,trackAlias:s(this,kI).subscribe.trackAlias,subGroupId:v(0),subscriberPriority:0,groupId:B.groupId,objectId:B.objectId,objectStatus:B.objectStatus,payload:B.payload}),E(this,bs,{group:B.groupId,object:B.objectId})}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}s(this,RI).debug("write group done")})}[pt()](){return s(this,wi).close().catch(F)}[Symbol.asyncDispose](){return s(this,wi).close().catch(F)}}wi=new WeakMap,Ns=new WeakMap,kI=new WeakMap,bs=new WeakMap,RI=new WeakMap;class wl{constructor(A,t,e){n(this,pe);I(this,"state");n(this,Ls);n(this,Di);this.state=A,E(this,Ls,t),E(this,Di,e)}ok(A){return r(this,null,function*(){var o,a,c;const t=(o=this.state.range())==null?void 0:o.startGroup,e=A.latest(),g=e==null?void 0:e.id,B=(c=(a=e==null?void 0:e.latest())==null?void 0:a.objectId)!=null?c:v(0),C=A.consume(t!=null?t:g),Q={type:b.SubscribeOk,id:this.state.subscribe.id,expires:v(0),groupOrder:"ascending",params:new Map,largestInfo:g?{group:g,object:B}:void 0};return yield s(this,Di).push(Q),new ll(this.state,C,s(this,Ls),s(this,Di))})}invalidRange(){return d(this,pe,ug).call(this,v(1),"Invalid range")}retryTrackAlias(){return d(this,pe,ug).call(this,v(2),"Retry track alias")}trackDoesNotExist(){return d(this,pe,ug).call(this,v(3),"Track does not exist")}unauthorized(){return d(this,pe,ug).call(this,v(4),"Unauthorized")}timeout(){return d(this,pe,ug).call(this,v(5),"Timeout")}[pt()](){return this.trackDoesNotExist()}[Symbol.asyncDispose](){return this.trackDoesNotExist()}}Ls=new WeakMap,Di=new WeakMap,pe=new WeakSet,ug=function(A,t){const e={type:b.SubscribeError,id:this.state.subscribe.id,errorCode:A,reason:t,trackAlias:this.state.subscribe.trackAlias};return s(this,Di).push(e)},yE=[ZA({context:"Session",enter:"info",error:"error"})];class jQ{constructor(A,t,e){Oi(Oo,5,this);n(this,UI);n(this,Js);n(this,NI);n(this,mi,UA.get().createContext("Publisher"));n(this,Fe,new vA(new Map));n(this,Ge,new vA(new Map));n(this,ke,new We(10));E(this,UI,A),E(this,Js,t),E(this,NI,e)}announce(A){return r(this,null,function*(){if(s(this,Fe).current().has(A.join("/")))throw new Error("Duplicate announcement");const t=new Map,e=s(this,UI).authToken();e&&t.set(IC,{type:IC,payload:new TextEncoder().encode(e)});const g={type:b.Announce,namespace:A,params:t},B=cl(g);if(s(this,Fe).update(Q=>Q.set(g.namespace.join("/"),B)),yield s(this,NI).push(g),!(yield Promise.race([B.state.ok(),s(this,UI).closed()])))throw new Error("Session closed")})}close(){s(this,Ge).current().forEach(A=>A.close()),s(this,Ge).close(),s(this,Fe).close(),s(this,ke).close()}incomingSubscriptions(){return s(this,ke)}onMessage(A){return r(this,null,function*(){switch(A.type){case b.Subscribe:{const t=new BC(A);if(s(this,Ge).update(e=>(e.set(A.id,t),e)),s(this,ke).isFull()){const e=yield s(this,ke).pop();yield e==null?void 0:e.timeout()}yield s(this,ke).push(new wl(t,s(this,Js),s(this,NI)))}break;case b.SubscribeUpdate:{const t=s(this,Ge).current().get(A.id);t||s(this,mi).debug("No subscription found",A),t==null||t.onUpdate(A)}break;case b.Unsubscribe:{const t=s(this,Ge).current().get(A.id);t||s(this,mi).debug("No subscription found",A),t==null||t.onUnsubscribe(A)}break;case b.AnnounceOk:{const t=s(this,Fe).current().get(A.namespace.join("/"));t||s(this,mi).debug("No announcement found",A),t==null||t.state.onOk(A)}break;case b.AnnounceError:{const t=s(this,Fe).current().get(A.namespace.join("/"));t||s(this,mi).debug("No announcement found",A),t==null||t.state.onError(A)}break}})}}Oo=Wi(null),UI=new WeakMap,Js=new WeakMap,NI=new WeakMap,mi=new WeakMap,Fe=new WeakMap,Ge=new WeakMap,ke=new WeakMap,OA(Oo,1,"announce",yE,jQ),Te(Oo,jQ);function Dl(i,A){const t=new BC(A),[e,g]=xe(100),B=new ml(t,e),C=new qa(i,t,g);return[B,C]}class ml{constructor(A,t){I(this,"state");n(this,Si);this.state=A,E(this,Si,t)}onDone(A){this.state.onDone(A)}onData(A){return s(this,Si).push(A)}onError(A){const t=this.state.onError(A);s(this,Si).abort(t)}close(){this.state.close(),s(this,Si).close()}}Si=new WeakMap;class qa{constructor(A,t,e){Oi(Vo,5,this);n(this,MI);n(this,bI);n(this,kA);n(this,LI);n(this,JI,new $);E(this,bI,A),E(this,kA,t),E(this,LI,e)}get id(){return s(this,kA).subscribe.id}get trackAlias(){return s(this,kA).subscribe.trackAlias}get name(){return s(this,kA).subscribe.name}range(){return s(this,kA).range()}expiryNotification(){return s(this,kA).expiryNotification()}update(A,t){return r(this,null,function*(){const e={type:b.SubscribeUpdate,id:s(this,kA).subscribe.id,start:{group:A,object:v(0)},end:{group:t+v(1),object:v(0)},params:new Map,subscriberPriority:0};s(this,kA).onUpdate(e),yield s(this,bI).push(e)})}unsubscribe(){return r(this,null,function*(){const A={type:b.Unsubscribe,id:s(this,kA).subscribe.id};s(this,kA).onUnsubscribe(A),yield s(this,bI).push(A)})}close(){var A,t;return s(this,JI).resolve(),(t=(A=s(this,LI)).return)==null?void 0:t.call(A)}closed(){return s(this,JI).promise}done(){return s(this,kA).done()}expiryState(){return s(this,kA).expiryState()}unsubscribed(){return s(this,kA).isUnsubscribed()}return(){return r(this,null,function*(){return s(this,JI).resolve(),yield this.unsubscribe(),{done:!0,value:void 0}})}groups(){return Ee(this,null,function*(){var A,t;try{for(var m=rA(s(this,LI)),y,f,k;y=!(f=yield new EA(m.next())).done;y=!1){var Q=f.value;var o=[];try{const q=ot(o,Q,!0);try{for(var e=rA(q.groups()),g,B,C;g=!(B=yield new EA(e.next())).done;g=!1){const U=B.value;const H=(A=s(this,kA).range())==null?void 0:A.startGroup,T=(t=s(this,kA).range())==null?void 0:t.endGroup;if(H&&U.groupId()<H)return{done:!0,value:void 0};if(T&&U.groupId()>T)return{done:!0,value:void 0};yield U}}catch(B){C=[B]}finally{try{g&&(B=e.return)&&(yield new EA(B.call(e)))}finally{if(C)throw C[0]}}}catch(a){var c=a,h=!0}finally{var l=nt(o,c,h);l&&(yield new EA(l))}}}catch(f){k=[f]}finally{try{y&&(f=m.return)&&(yield new EA(f.call(m)))}finally{if(k)throw k[0]}}})}[Symbol.asyncIterator](){return this.groups()}objects(){return Ee(this,null,function*(){try{for(var B=rA(this.groups()),C,Q,o;C=!(Q=yield new EA(B.next())).done;C=!1){const a=Q.value;try{for(var A=rA(a),t,e,g;t=!(e=yield new EA(A.next())).done;t=!1){const c=e.value;yield c}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield new EA(e.call(A)))}finally{if(g)throw g[0]}}}}catch(Q){o=[Q]}finally{try{C&&(Q=B.return)&&(yield new EA(Q.call(B)))}finally{if(o)throw o[0]}}})}[(fE=[ZA({context:"SubscriptionConsumer",enter:"info"})],pt())](){return d(this,MI,fB).call(this)}[Symbol.asyncDispose](){return d(this,MI,fB).call(this)}}Vo=Wi(null),bI=new WeakMap,kA=new WeakMap,LI=new WeakMap,JI=new WeakMap,MI=new WeakSet,fB=function(){return r(this,null,function*(){return yield this.close(),this.unsubscribe()})},fB=OA(Vo,17,"#dispose",fE,MI,fB),Te(Vo,qa);const Sl=2e3;kE=[ZA({context:"Session",return:"debug"})],GE=[ZA({context:"Session",enter:"info",error:"error"})],FE=[ZA({context:"Session",enter:"debug"})],pE=[ZA({context:"Session",enter:"debug"})];class CC{constructor(A,t){Oi(HI,5,this);n(this,Lt);n(this,Ae);I(this,"nextSubscribeId",v(0));n(this,_A,new vA(new Map));n(this,yi);n(this,fi,UA.get().createContext("Subscriber"));E(this,Ae,A),E(this,yi,t),d(this,Lt,uQ).call(this).catch(F)}subscribe(g,B){return r(this,arguments,function*(A,t,e=new Map){const C=this.nextSubscribeId++,Q=s(this,Ae).authToken();Q&&e.set(IC,{type:IC,payload:new TextEncoder().encode(Q)});const o={type:b.Subscribe,namespace:A,name:t.name,id:C,trackAlias:C,groupOrder:t.groupOrder,subscriberPriority:t.priority,filterType:t.filterType,params:e},[a,c]=Dl(s(this,yi),o);if(s(this,_A).update(l=>l.set(C,a)),yield s(this,yi).push(o),!(yield Promise.race([a.state.ok(),s(this,Ae).closed()])))throw new Error("Session closed");return c.closed().then(()=>Promise.race([ce(Sl),this.closed()])).then(()=>d(this,Lt,wg).call(this,c.id)).catch(()=>d(this,Lt,wg).call(this,c.id)),c})}closed(){return s(this,Ae).closed()}transportType(){return s(this,Ae).transportType()}url(){return s(this,Ae).url()}onMessage(A){return r(this,null,function*(){switch(A.type){case b.Announce:yield s(this,yi).push({type:b.AnnounceOk,namespace:A.namespace});break;case b.SubscribeOk:{const t=s(this,_A).current().get(A.id);t&&t.state.onOk(A)}break;case b.SubscribeError:{const t=s(this,_A).current().get(A.id);t||s(this,fi).debug("No subscription found",A),t==null||t.onError(A),d(this,Lt,wg).call(this,A.id)}break;case b.SubscribeDone:{const t=s(this,_A).current().get(A.id);t||s(this,fi).debug("No subscription found",A),t==null||t.onDone(A)}break}})}onObjectReader(A){return r(this,null,function*(){const t=s(this,_A).current().get(A.subscribeId());if(!t){s(this,fi).warn("No subscription found",A.subscribeId());return}yield t.onData(A)})}close(){s(this,_A).current().forEach(A=>A.close()),s(this,_A).close()}}HI=Wi(null),Ae=new WeakMap,_A=new WeakMap,yi=new WeakMap,fi=new WeakMap,Lt=new WeakSet,uQ=function(){return r(this,null,function*(){try{for(var A=rA(s(this,_A)),t,e,g;t=!(e=yield A.next()).done;t=!1){const B=e.value;const C=[...B.values()].map(Q=>Q.state.subscribe);s(this,fi).debug("current subscriptions",C)}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}})},wg=function(A){s(this,_A).isClosed()||s(this,_A).update(t=>(t.delete(A),t))},uQ=OA(HI,17,"#observeChanges",kE,Lt,uQ),OA(HI,1,"subscribe",GE,CC),OA(HI,1,"close",FE,CC),wg=OA(HI,17,"#deleteSubscription",pE,Lt,wg),Te(HI,CC);class zQ{constructor(A,t){Oi(KI,5,this);n(this,pA);n(this,ut);n(this,Ms);n(this,pi);n(this,qI,UA.get().createContext("Session"));I(this,"subscriber");I(this,"publisher");n(this,vI);const[e,g]=xe(100);E(this,ut,A),E(this,pi,g),this.subscriber=new CC(this,e),this.publisher=new jQ(this,A,e),E(this,Ms,d(this,pA,Er).call(this)),E(this,vI,new vA(t)),this.closed().then(()=>this.close()).catch(F)}updateAuthToken(A){s(this,vI).update(A)}authToken(){return s(this,vI).current()}transportType(){return s(this,ut).transportType()}url(){return s(this,ut).url()}closed(){return s(this,Ms)}close(){try{this.subscriber.close(),this.publisher.close(),s(this,pi).cancel("closing"),s(this,ut).close()}catch(A){s(this,qI).warn("Error closing session",A)}}[(bE=[ZA({context:"Session",return:"info",error:"error"})],NE=[ZA({context:"Session",return:"info",error:"error"})],UE=[ZA({context:"Session",return:"info",error:"error"})],RE=[ZA({context:"Session",enter:"debug"})],mn())](){d(this,pA,pB).call(this)}[Symbol.dispose](){d(this,pA,pB).call(this)}}KI=Wi(null),ut=new WeakMap,Ms=new WeakMap,pi=new WeakMap,qI=new WeakMap,vI=new WeakMap,pA=new WeakSet,ar=function(A){return r(this,null,function*(){var t,e;switch(s(this,qI).debug("received message",A),yield(t=this.subscriber)==null?void 0:t.onMessage(A),yield(e=this.publisher)==null?void 0:e.onMessage(A),A.type){case b.Goaway:break}})},Er=function(){return r(this,null,function*(){return(yield Promise.all([d(this,pA,DQ).call(this),d(this,pA,mQ).call(this),d(this,pA,wQ).call(this)])).find(t=>t instanceof Error)})},wQ=function(){return r(this,null,function*(){try{try{for(var A=rA(s(this,pi)),t,e,g;t=!(e=yield A.next()).done;t=!1){const B=e.value;s(this,qI).debug("sending message",B),yield s(this,ut).writeMessage(B)}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}}catch(B){return B}})},DQ=function(){return r(this,null,function*(){try{for(yield s(this,ut).afterHandshake();;){const A=yield s(this,ut).readMessage().catch(()=>{});if(!A)break;yield d(this,pA,ar).call(this,A)}}catch(A){return A}finally{s(this,pi).cancel("closing")}})},mQ=function(){return r(this,null,function*(){var A;try{for(;;){const t=yield s(this,ut).objectStream();if(!t)break;yield(A=this.subscriber)==null?void 0:A.onObjectReader(t)}}catch(t){return t}})},pB=function(){this.close()},wQ=OA(KI,17,"#runOutgoingMessages",bE,pA,wQ),DQ=OA(KI,17,"#runControl",NE,pA,DQ),mQ=OA(KI,17,"#runObjects",UE,pA,mQ),pB=OA(KI,17,"#dispose",RE,pA,pB),Te(KI,zQ);const yl=128;class fl{constructor(A,t,e){n(this,HA);n(this,st);n(this,Hs);n(this,Fi,!0);n(this,YI,!1);n(this,qs);E(this,st,A),E(this,Hs,t),E(this,qs,e)}writeUnsigned8(A){return r(this,null,function*(){return d(this,HA,Zi).call(this),yield d(this,HA,Xi).call(this),s(this,st).writeUnsigned8(A)})}writeVarInt(A){return r(this,null,function*(){return d(this,HA,Zi).call(this),yield d(this,HA,Xi).call(this),s(this,st).writeVarInt(A)})}writeBigVarInt(A){return r(this,null,function*(){return d(this,HA,Zi).call(this),yield d(this,HA,Xi).call(this),s(this,st).writeBigVarInt(A)})}write(A){return r(this,null,function*(){return d(this,HA,Zi).call(this),yield d(this,HA,Xi).call(this),s(this,st).write(A)})}writeString(A){return r(this,null,function*(){return d(this,HA,Zi).call(this),yield d(this,HA,Xi).call(this),s(this,st).writeString(A)})}flush(){return r(this,null,function*(){d(this,HA,Zi).call(this),E(this,Fi,!0),yield s(this,st).flush()})}close(){return r(this,null,function*(){s(this,YI)||(E(this,Fi,!0),yield d(this,HA,Xi).call(this,!1),yield s(this,st).flush(),E(this,YI,!0),s(this,qs).call(this))})}}st=new WeakMap,Hs=new WeakMap,Fi=new WeakMap,YI=new WeakMap,qs=new WeakMap,HA=new WeakSet,Zi=function(){if(s(this,YI))throw new Error("Stream is closed")},Xi=function(A=!0){if(s(this,Fi))return E(this,Fi,!1),s(this,st).writeUnsigned8(s(this,Hs)|(A?yl:0))};class pl{constructor(A,t){n(this,JC);n(this,Re);n(this,te);n(this,TI);n(this,Gi);n(this,ee,new Map);n(this,PI,UA.get().createContext("WebSocketConnection"));n(this,xI,new Set(new Array(128).fill(0).map((A,t)=>t+1)));E(this,Re,A),E(this,te,t),E(this,TI,new ReadableStream(new qd(A))),s(this,Re).addEventListener("close",()=>{s(this,te).markPostHandshake(),s(this,ee).forEach(e=>e.close())})}openSendStream(){const A=s(this,xI).values().next().value;if(!A)throw new Error("No stream IDs available");return s(this,xI).delete(A),Promise.resolve(new fl(new kg(s(this,Re)),A,()=>d(this,JC,rr).call(this,A)))}transportType(){return"websocket"}url(){return s(this,Re).url}afterHandshake(){return s(this,te).postHandshake()}objectStream(){return r(this,null,function*(){var A;for(;;){E(this,Gi,s(this,TI).getReader());try{const{value:t,done:e}=yield s(this,Gi).read();if(e)return;const[g,B,C]=t;if(s(this,ee).has(v(B))){const Q=s(this,ee).get(v(B));if(!Q)throw new Error("Stream not found");C.length>0&&(yield Q.push(C)),g||(s(this,PI).debug("Closing stream",{streamId:B}),Q.close(),s(this,ee).delete(v(B)))}else{let c;s(this,PI).debug("Creating new stream",{streamId:B});const[Q,o]=xe(1e3),a=new ReadableStream({pull(h){return r(this,null,function*(){const l=yield o.pop();l?h.enqueue(l):h.close()})}});if(s(this,ee).set(v(B),Q),g||(s(this,PI).debug("Closing new stream",{streamId:B}),yield a.cancel(),s(this,ee).delete(v(B))),C.length>0)return yield ua(new tC(C,a),B)}}finally{(A=s(this,Gi))==null||A.releaseLock()}}})}close(){var A;return s(this,te).cancel().catch(F),s(this,TI).cancel("closing").catch(F),(A=s(this,Gi))==null||A.cancel("closing").catch(F),s(this,Re).close()}closed(){return Promise.resolve()}writeMessage(A){return r(this,null,function*(){yield s(this,te).write(A)})}readMessage(){return r(this,null,function*(){return s(this,te).read()})}}Re=new WeakMap,te=new WeakMap,TI=new WeakMap,Gi=new WeakMap,ee=new WeakMap,PI=new WeakMap,xI=new WeakMap,JC=new WeakSet,rr=function(A){s(this,xI).add(A)};class Fl{constructor(A,t,e){n(this,HC);n(this,ie);n(this,Ie);n(this,Ue,new We(100));n(this,vs);n(this,Ks,0);n(this,MC,UA.get().createContext("WebTransportConnection"));E(this,vs,e),E(this,ie,A),E(this,Ie,t),d(this,HC,cr).call(this).catch(g=>{s(this,MC).debug("Incoming streams handling ended with error",g),s(this,Ie).markPostHandshake(),s(this,Ue).close()}),s(this,ie).closed.then(()=>{s(this,Ie).markPostHandshake(),s(this,Ue).close()})}openSendStream(){return r(this,null,function*(){const A=yield s(this,ie).createUnidirectionalStream();return new wa(A)})}transportType(){return"webtransport"}url(){return s(this,vs)}afterHandshake(){return s(this,Ie).postHandshake()}closed(){return r(this,null,function*(){yield s(this,ie).closed})}close(){s(this,ie).close()}writeMessage(A){return r(this,null,function*(){yield s(this,Ie).write(A)})}readMessage(){return r(this,null,function*(){return s(this,Ie).read()})}objectStream(){return r(this,null,function*(){return s(this,Ue).pop()})}}ie=new WeakMap,Ie=new WeakMap,Ue=new WeakMap,vs=new WeakMap,Ks=new WeakMap,MC=new WeakMap,HC=new WeakSet,cr=function(){return r(this,null,function*(){const A=s(this,ie).incomingUnidirectionalStreams.getReader();for(;;){const{value:t,done:e}=yield A.read();if(e){s(this,Ue).close();return}const g=new tC(new Uint8Array,t);yield s(this,Ue).push(ua(g,s(this,Ks))),ft(this,Ks)._++}})};function _Q(i){return r(this,null,function*(){const A=new WebSocket(i.wsUrl||i.url);A.binaryType="arraybuffer",yield new Promise((B,C)=>{A.addEventListener("error",()=>C(new Error("WebSocket error")),{once:!0}),A.addEventListener("open",B,{once:!0})});const t=sC.wrapWebsocket(A);Ha(t,i.role).catch(()=>{A.close()});const e=new pl(A,t);return new zQ(e,i.authToken)})}function Gl(i){return r(this,null,function*(){const A="60b82e8021689e163c1041b4475ef9c86e7565bc45d1a0aa43f5148769f461c7",t=new Uint8Array(A.length/2);for(let o=0;o<t.length;o+=1)t[o]=parseInt(A.slice(2*o,2*o+2),16);const e=new WebTransport(i.url,{congestionControl:"low-latency"});yield Promise.race([e.ready,e.closed.then(()=>Promise.reject(new Error("WebTransport closed")))]);const g=yield e.createBidirectionalStream(),B=sC.wrapWebTransport(g);Ha(B,i.role).catch(()=>{e.close()});const C=new Fl(e,B,i.url.toString());return new zQ(C,i.authToken)})}function kl(i){return r(this,null,function*(){if(self.WebTransport&&(i==null?void 0:i.preferredTransport)!=="websocket"&&i.url.protocol.startsWith("https")){const A=Gl(i).catch(()=>_Q(i)),t=yield Promise.race([A,ce(i.websocketFallbackTimeoutMs)]);return t||_Q(i)}return _Q(i)})}class Vt{constructor(){n(this,ge,{name:"",priority:0,groupOrder:"ascending",filterType:{type:"latest-group"}})}name(A){return s(this,ge).name=A,this}priority(A){return s(this,ge).priority=A,this}groupOrder(A){return s(this,ge).groupOrder=A,this}startGroup(A){return s(this,ge).filterType={type:"absolute-start",start:{group:A,object:v(0)}},this}range(A,t){return s(this,ge).filterType={type:"absolute-range",start:{group:A,object:v(0)},end:{group:t,object:v(0)}},this}build(){return s(this,ge)}}ge=new WeakMap;class va{constructor(A,t){n(this,WI);n(this,Ys);E(this,WI,A),E(this,Ys,t)}subscribe(A,t=new Map){return s(this,WI).subscribe(this.namespace(),A,t)}closed(){return s(this,WI).closed()}namespace(){return s(this,Ys).namespace}}WI=new WeakMap,Ys=new WeakMap;function Rl(i,A){return["com.vindral.moq",i]}function $e(i){const A=i[1];if(!A)throw new Error("namespace must contain a channel ID");return A}function Ul(i){return"tracks"in i}function Nl(i){const A=new TextDecoder().decode(i);return JSON.parse(A)}const Zo=class Zo{constructor(A,t){n(this,Ps);n(this,$A);n(this,Jt);n(this,ki,new W(100));n(this,Bt);n(this,Ts);n(this,qC,A=>r(this,null,function*(){if(!A)return s(this,$A).close();if(s(this,Bt))return;const t=s(this,ki).items().reduce((e,g)=>e<g?e:g,A);E(this,Bt,d(this,Ps,an).call(this,t,A)),s(this,Bt).size===0&&(yield s(this,$A).close())}));E(this,$A,A),E(this,Jt,t),A.done().then(e=>r(this,null,function*(){var g;return s(this,qC).call(this,(g=e.finalInfo)==null?void 0:g.group)})).catch(F),E(this,Ts,A.groups())}static subscribe(A,t){return r(this,null,function*(){const e=yield A.subscribe(t);return new Zo(e,void 0)})}subscribeId(){return s(this,$A).id}name(){return s(this,$A).name}largestGroupId(){return s(this,Jt)}needsRenewal(){return s(this,$A).expiryState()==="active"&&s(this,Bt)===void 0}endOfTrack(A){const t=s(this,ki).items().reduce((e,g)=>e<g?e:g,A);return this.update(t,A)}update(A,t){return r(this,null,function*(){return E(this,Bt,d(this,Ps,an).call(this,A,t)),s(this,Bt).size===0&&(yield s(this,$A).close()),s(this,$A).update(A,t)})}unsubscribe(){return s(this,$A).unsubscribe()}next(){return r(this,null,function*(){var e;if(s(this,Bt)&&s(this,Bt).size===0)return{done:!0,value:void 0};const A=yield s(this,Ts).next();if(A.done)return A;const t=A.value.groupId();return(e=s(this,Bt))==null||e.delete(t),s(this,ki).push(t),s(this,Jt)||E(this,Jt,t),E(this,Jt,s(this,Jt)<t?t:s(this,Jt)),A})}return(){return s(this,$A).return()}[Symbol.asyncIterator](){return this}};$A=new WeakMap,Jt=new WeakMap,ki=new WeakMap,Bt=new WeakMap,Ts=new WeakMap,qC=new WeakMap,Ps=new WeakSet,an=function(A,t){const e=new Set;for(let g=A;g<=t;g++)e==null||e.add(g);return s(this,ki).items().forEach(g=>{e==null||e.delete(g)}),e};let QC=Zo;const Xo=class Xo{constructor(A){n(this,xs);n(this,wt);n(this,Ri);n(this,se,new We(10));n(this,Mt);n(this,Ws,(A,t)=>r(this,null,function*(){var h=[];try{const e=ot(h,yield s(this,wt).lock());const g={subscribeId:e.value.subscribeId()};if(!e.value.needsRenewal()){s(this,Mt).debug("Subscription does not need renewal",g);return}const B=e.value.largestGroupId();const C=B!==void 0;const Q=new Vt().name(t.name).priority(t.priority).groupOrder(t.groupOrder);g.largestGroupId=B;s(this,Mt).debug("Renewing subscription",g);switch(t.filterType.type){case"absolute-range":s(this,Mt).debug("Absolute range is not renewed",g);return;case"absolute-start":case"latest-group":case"latest-object":C&&Q.startGroup(B+v(1));break}const o=Q.build();g.newTrack=o;const[a]=yield Promise.all([A.subscribe(o),C?e.value.update(B,B):e.value.unsubscribe()]);a.done().then(()=>d(this,xs,En).call(this,a)).catch(F);a.expiryNotification().then(()=>s(this,Ws).call(this,A,o)).catch(F);const c=new QC(a,B);e.value=c;yield s(this,se).push(c);s(this,Mt).info("Subscription renewed",g)}catch(l){var m=l,y=!0}finally{nt(h,m,y)}}));E(this,wt,new _r(A)),E(this,Ri,A),E(this,Mt,UA.get().createContext(`Renewable '${A.name()}'`))}static subscribe(A,t,e){return r(this,null,function*(){const g=e==null?void 0:e.params,B=e==null?void 0:e.largestGroupId,C=yield A.subscribe(t,g),Q=new Xo(new QC(C,B));return C.done().then(()=>{var o;return d(o=Q,xs,En).call(o,C)}).catch(F),C.expiryNotification().then(()=>{var o;return s(o=Q,Ws).call(o,A,t)}).catch(F),Q})}largestGroupId(){return s(this,wt).unsafeValue().largestGroupId()}update(A,t){return r(this,null,function*(){var g=[];try{const e=ot(g,yield s(this,wt).lock());s(this,se).close();return e.value.update(A,t)}catch(B){var C=B,Q=!0}finally{nt(g,C,Q)}})}endOfTrack(A){return r(this,null,function*(){var e=[];try{const t=ot(e,yield s(this,wt).lock());s(this,se).close();return t.value.endOfTrack(A)}catch(g){var B=g,C=!0}finally{nt(e,B,C)}})}unsubscribe(){return r(this,null,function*(){var t=[];try{const A=ot(t,yield s(this,wt).lock());s(this,se).close();return A.value.unsubscribe()}catch(e){var g=e,B=!0}finally{nt(t,g,B)}})}return(){return r(this,null,function*(){var t=[];try{const A=ot(t,yield s(this,wt).lock());s(this,se).close();return A.value.return()}catch(e){var g=e,B=!0}finally{nt(t,g,B)}})}next(){return r(this,null,function*(){var t,e;const A=yield s(this,Ri).next();if(A.done){yield(e=(t=s(this,Ri)).return)==null?void 0:e.call(t);const g=yield s(this,se).pop();if(g)return E(this,Ri,g),this.next()}return A})}[Symbol.asyncIterator](){return this}objects(){return Ee(this,null,function*(){try{for(var Q=rA(this),o,a,c;o=!(a=yield new EA(Q.next())).done;o=!1){var A=a.value;var t=[];try{const h=ot(t,A,!0);yield*Bn(h)}catch(e){var g=e,B=!0}finally{var C=nt(t,g,B);C&&(yield new EA(C))}}}catch(a){c=[a]}finally{try{o&&(a=Q.return)&&(yield new EA(a.call(Q)))}finally{if(c)throw c[0]}}})}};wt=new WeakMap,Ri=new WeakMap,se=new WeakMap,Mt=new WeakMap,xs=new WeakSet,En=function(A){return r(this,null,function*(){var t;if(A.unsubscribed()||(t=A.range())!=null&&t.endGroup){s(this,Mt).info("Server initiated subscribe done but the subscription is already closing");return}if(s(this,wt).unsafeValue().subscribeId()!==A.id){s(this,Mt).info("subscribeId mismatch - the subscription already has been renewed");return}return this.return()})},Ws=new WeakMap;let de=Xo;const bl="catalog";function Ka(i){const A=Nl(i.payload);if(!Ul(A))throw new Error("unexpected catalog type");return A}const KC=class KC{constructor(A,t,e){n(this,vC);n(this,Ne);n(this,Os);n(this,Vs);n(this,Zs);E(this,Os,A),E(this,Ne,t),E(this,Vs,e),E(this,Zs,d(this,vC,hr).call(this)),this.closed().finally(()=>s(this,Ne).close()).catch(F)}catalog(){return s(this,Ne)}closed(){return s(this,Zs)}close(){return r(this,null,function*(){return s(this,Ne).close(),(yield s(this,Os).promise).unsubscribe()})}static start(A,t){return r(this,null,function*(){const e=$.fromPromise(de.subscribe(A,new Vt().name(t.catalogName||bl).groupOrder("ascending").build())),g=$.fromPromise(e.promise.then(o=>o.objects()));if(t.catalog)return new KC(e,new vA(t.catalog),g);const C=yield(yield g.promise).next();if(!C.value)throw new Error("No catalog found");const Q=Ka(C.value);return new KC(e,new vA(Q),g)})}};Ne=new WeakMap,Os=new WeakMap,Vs=new WeakMap,Zs=new WeakMap,vC=new WeakSet,hr=function(){return r(this,null,function*(){const A=yield s(this,Vs).promise;try{for(var t=rA(A),e,g,B;e=!(g=yield t.next()).done;e=!1){const C=g.value;if(C.objectStatus!==KA.Normal)continue;const Q=Ka(C);s(this,Ne).update(Q)}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield g.call(t))}finally{if(B)throw B[0]}}})};let $Q=KC;class Ll{constructor(A,t,e,g){n(this,zs);n(this,Xs);n(this,OI);n(this,js);I(this,"track");n(this,VI,UA.get().createContext("CmafGroup"));this.track=g,E(this,Xs,e),E(this,OI,A),E(this,js,t)}[Symbol.asyncIterator](){return Ee(this,null,function*(){const A={name:this.track.trackObject.name,namespace:this.track.namespace};s(this,VI).debug("start",D({},A));try{for(var t=rA(s(this,OI)),e,g,B;e=!(g=yield new EA(t.next())).done;e=!1){const C=g.value;if(C.objectStatus===KA.EndOfTrackAndGroup&&(yield new EA(this.track.endOfTrack(C.groupId))),C.objectStatus!==KA.Normal)continue;const Q=s(this,js).createFragment(C.payload),o=Q.timescale(),a=Q.baseMediaDecodeTime()/o*1e3,c=Q.duration()/o*1e3,h=a+c,l=s(this,Xs)/1e3*o;Q.updateBaseMediaDecodeTime(Q.baseMediaDecodeTime()-l);const m=this.track.timestampRange();if(m&&a>=m[1])break;s(this,VI).debug("fragment",V(D({},A),{startTime:a,endTime:h,subscribeId:C.subscribeId,groupId:C.groupId,objectId:C.objectId,streamId:C.streamId})),yield[C.groupId,Q]}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield new EA(g.call(t)))}finally{if(B)throw B[0]}}s(this,VI).debug("end",D({},A))})}[pt()](){return d(this,zs,rn).call(this)}[Symbol.asyncDispose](){return d(this,zs,rn).call(this)}}Xs=new WeakMap,OI=new WeakMap,js=new WeakMap,VI=new WeakMap,zs=new WeakSet,rn=function(){return r(this,null,function*(){var A,t;return yield(t=(A=s(this,OI)).return)==null?void 0:t.call(A),Promise.resolve()})};const ZI=class ZI{constructor(A,t,e,g,B){n(this,_s);n(this,Ht);n(this,$s);n(this,AB);I(this,"trackObject");I(this,"namespace");this.trackObject=A,this.namespace=t,E(this,Ht,e),E(this,_s,g),E(this,$s,B)}static subscribe(C,Q,o){return r(this,arguments,function*(A,t,{timestampOffsetMs:e,startGroup:g,params:B}){var y;if(t.format!=="cmaf")throw new Error("format must be cmaf");const a=new Vt().name(t.name);g&&a.startGroup(g);const c=a.build();if(t.initTrack){const f=new Vt().name(t.initTrack).build(),[k,q]=yield Promise.all([d(y=ZI,YC,dr).call(y,A,f),de.subscribe(A,c,{params:B,largestGroupId:g?g-v(1):void 0})]),U=new ia(k);return new ZI(t,A.namespace(),q,U,e)}lA(t.initData,"no init data found on track");const h=ln(t.initData),l=new ia(new Uint8Array(h)),m=yield de.subscribe(A,c,{params:B,largestGroupId:g?g-v(1):void 0});return new ZI(t,A.namespace(),m,l,e)})}largestGroupId(){return s(this,Ht).largestGroupId()}stopAfterTimestampReached(A){E(this,AB,[0,A])}timestampRange(){return s(this,AB)}endOfTrack(A){return s(this,Ht).endOfTrack(A)}update(A,t){return s(this,Ht).update(A,t)}unsubscribe(){return r(this,null,function*(){return s(this,Ht).unsubscribe()})}next(){return r(this,null,function*(){const A=yield s(this,Ht).next();return A.done?A:{done:!1,value:new Ll(A.value,s(this,_s),s(this,$s),this)}})}return(){return r(this,null,function*(){return yield s(this,Ht).return(),{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[pt()](){return this.unsubscribe()}[Symbol.asyncDispose](){return r(this,null,function*(){return this.unsubscribe()})}};_s=new WeakMap,Ht=new WeakMap,$s=new WeakMap,AB=new WeakMap,YC=new WeakSet,dr=function(A,t){return r(this,null,function*(){var B=[];try{const e=ot(B,yield A.subscribe(t),!0);const g=yield e.objects().next();if(g.done)throw new Error("No init object");yield e.close();return g.value.payload}catch(C){var Q=C,o=!0}finally{var a=nt(B,Q,o);a&&(yield a)}})},n(ZI,YC);let Ao=ZI;const Ya=1e4,Jl=3e4,jo=class jo{constructor(A,t,e){n(this,Ni);n(this,TC,UA.get().createContext("Timeline"));n(this,be,new vA([]));n(this,Ui);n(this,tB);n(this,eB);n(this,iB);E(this,tB,A),E(this,eB,e),E(this,Ui,t),E(this,iB,d(this,Ni,cn).call(this,s(this,Ui))),this.closed().finally(()=>s(this,be).close()).catch(F)}closed(){return s(this,iB)}close(){return r(this,null,function*(){return(yield s(this,Ui).promise).unsubscribe()})}timeline(){const[A,t]=s(this,be).value();return A}timestampWallclockOffset(){return Wt(this.timeline().map(A=>A.mediaPts-A.wallclock))}static start(A,t){const e=$.fromPromise(de.subscribe(A,new Vt().name(t).groupOrder("ascending").build()));return new jo(A,e,t)}waitForWallclockTime(A){return r(this,null,function*(){return yield s(this,be).waitFor(t=>!!t.find(e=>e.wallclock>=A)),this.timeline()})}waitForTimelineToHaveMinDuration(){return r(this,null,function*(){return yield s(this,be).waitFor(A=>{const t=A[0],e=A[A.length-1];return!t||!e?!1:e.wallclock-t.wallclock>Ya}),this.timeline()})}};TC=new WeakMap,be=new WeakMap,Ui=new WeakMap,tB=new WeakMap,eB=new WeakMap,iB=new WeakMap,Ni=new WeakSet,cn=function(A){return r(this,null,function*(){const t=yield A.promise;try{for(var m=rA(t),y,f,k;y=!(f=yield m.next()).done;y=!1){var Q=f.value;var o=[];try{const q=ot(o,Q,!0);try{for(var e=rA(q),g,B,C;g=!(B=yield e.next()).done;g=!1){const U=B.value;if(U.objectStatus!==KA.Normal)continue;const H=Ml(U.payload);s(this,be).update(T=>{var z,Y;for(T.push(...H),T.sort((FA,nA)=>FA.wallclock-nA.wallclock);T[0]&&((Y=(z=T[T.length-1])==null?void 0:z.wallclock)!=null?Y:0)-T[0].wallclock>Jl;)T.shift();return T}),t===s(this,Ui).resolved&&U.groupId>v(0)&&U.objectId==v(0)&&d(this,Ni,lr).call(this,U.groupId).catch(T=>{s(this,TC).warn("backfill failed",T)})}}catch(B){C=[B]}finally{try{g&&(B=e.return)&&(yield B.call(e))}finally{if(C)throw C[0]}}}catch(a){var c=a,h=!0}finally{var l=nt(o,c,h);l&&(yield l)}}}catch(f){k=[f]}finally{try{y&&(f=m.return)&&(yield f.call(m))}finally{if(k)throw k[0]}}})},lr=function(A){return r(this,null,function*(){const t=A-v(1),e=this.timeline(),g=e[0],B=e[e.length-1];if(!g||!B||B.wallclock-g.wallclock>Ya)return;const C=$.fromPromise(de.subscribe(s(this,tB),new Vt().name(s(this,eB)).groupOrder("ascending").range(t,t).build()));return d(this,Ni,cn).call(this,C)})};let to=jo;function Ml(i){var t;const A=new TextDecoder("utf-8").decode(i).split(`
|
|
1
|
+
(function(u,S){typeof exports=="object"&&typeof module!="undefined"?S(exports):typeof define=="function"&&define.amd?define(["exports"],S):(u=typeof globalThis!="undefined"?globalThis:u||self,S(u.Vindral={}))})(this,(function(u){"use strict";var Fw=Object.create;var gn=Object.defineProperty,Gw=Object.defineProperties,kw=Object.getOwnPropertyDescriptor,Rw=Object.getOwnPropertyDescriptors;var cQ=Object.getOwnPropertySymbols;var KE=Object.prototype.hasOwnProperty,YE=Object.prototype.propertyIsEnumerable;var Pt=(u,S)=>(S=Symbol[u])?S:Symbol.for("Symbol."+u),ae=u=>{throw TypeError(u)};var hQ=(u,S,p)=>S in u?gn(u,S,{enumerable:!0,configurable:!0,writable:!0,value:p}):u[S]=p,D=(u,S)=>{for(var p in S||(S={}))KE.call(S,p)&&hQ(u,p,S[p]);if(cQ)for(var p of cQ(S))YE.call(S,p)&&hQ(u,p,S[p]);return u},V=(u,S)=>Gw(u,Rw(S)),vE=(u,S)=>gn(u,"name",{value:S,configurable:!0});var TE=(u,S)=>{var p={};for(var J in u)KE.call(u,J)&&S.indexOf(J)<0&&(p[J]=u[J]);if(u!=null&&cQ)for(var J of cQ(u))S.indexOf(J)<0&&YE.call(u,J)&&(p[J]=u[J]);return p};var Wi=u=>{var S;return[,,,Fw((S=u==null?void 0:u[Pt("metadata")])!=null?S:null)]},PE=["class","method","getter","setter","accessor","field","value","get","set"],mB=u=>u!==void 0&&typeof u!="function"?ae("Function expected"):u,Uw=(u,S,p,J,N)=>({kind:PE[u],name:S,metadata:J,addInitializer:K=>p._?ae("Already initialized"):N.push(mB(K||null))}),Te=(u,S)=>hQ(S,Pt("metadata"),u[3]),Oi=(u,S,p,J)=>{for(var N=0,K=u[S>>1],j=K&&K.length;N<j;N++)S&1?K[N].call(p):J=K[N].call(p,J);return J},OA=(u,S,p,J,N,K)=>{var j,tA,sA,oA,xt,F=S&7,$=!!(S&8),W=!!(S&16),xe=F>3?u.length+1:F?$?1:2:0,We=PE[F+5],lA=F>3&&(u[xe-1]=[]),v=u[xe]||(u[xe]=[]),VA=F&&(!W&&!$&&(N=N.prototype),F<5&&(F>3||!W)&&kw(F<4?N:{get[p](){return s(this,K)},set[p](SA){return E(this,K,SA)}},p));F?W&&F<4&&vE(K,(F>2?"set ":F>1?"get ":"")+p):vE(N,p);for(var Oe=J.length-1;Oe>=0;Oe--)oA=Uw(F,p,sA={},u[3],v),F&&(oA.static=$,oA.private=W,xt=oA.access={has:W?SA=>Nw(N,SA):SA=>p in SA},F^3&&(xt.get=W?SA=>(F^1?s:d)(SA,N,F^4?K:VA.get):SA=>SA[p]),F>2&&(xt.set=W?(SA,mg)=>E(SA,N,mg,F^4?K:VA.set):(SA,mg)=>SA[p]=mg)),tA=(0,J[Oe])(F?F<4?W?K:VA[We]:F>4?void 0:{get:VA.get,set:VA.set}:N,oA),sA._=1,F^4||tA===void 0?mB(tA)&&(F>4?lA.unshift(tA):F?W?K=tA:VA[We]=tA:N=tA):typeof tA!="object"||tA===null?ae("Object expected"):(mB(j=tA.get)&&(VA.get=j),mB(j=tA.set)&&(VA.set=j),mB(j=tA.init)&&lA.unshift(j));return F||Te(u,N),VA&&gn(N,p,VA),W?F^4?K:VA:N},I=(u,S,p)=>hQ(u,typeof S!="symbol"?S+"":S,p),sn=(u,S,p)=>S.has(u)||ae("Cannot "+p),Nw=(u,S)=>Object(S)!==S?ae('Cannot use the "in" operator on this value'):u.has(S),s=(u,S,p)=>(sn(u,S,"read from private field"),p?p.call(u):S.get(u)),n=(u,S,p)=>S.has(u)?ae("Cannot add the same private member more than once"):S instanceof WeakSet?S.add(u):S.set(u,p),E=(u,S,p,J)=>(sn(u,S,"write to private field"),J?J.call(u,p):S.set(u,p),p),d=(u,S,p)=>(sn(u,S,"access private method"),p);var ft=(u,S,p,J)=>({set _(N){E(u,S,N,p)},get _(){return s(u,S,J)}});var r=(u,S,p)=>new Promise((J,N)=>{var K=sA=>{try{tA(p.next(sA))}catch(oA){N(oA)}},j=sA=>{try{tA(p.throw(sA))}catch(oA){N(oA)}},tA=sA=>sA.done?J(sA.value):Promise.resolve(sA.value).then(K,j);tA((p=p.apply(u,S)).next())}),EA=function(u,S){this[0]=u,this[1]=S},Ee=(u,S,p)=>{var J=(j,tA,sA,oA)=>{try{var xt=p[j](tA),F=(tA=xt.value)instanceof EA,$=xt.done;Promise.resolve(F?tA[0]:tA).then(W=>F?J(j==="return"?j:"next",tA[1]?{done:W.done,value:W.value}:W,sA,oA):sA({value:W,done:$})).catch(W=>J("throw",W,sA,oA))}catch(W){oA(W)}},N=j=>K[j]=tA=>new Promise((sA,oA)=>J(j,tA,sA,oA)),K={};return p=p.apply(u,S),K[Pt("asyncIterator")]=()=>K,N("next"),N("throw"),N("return"),K},Bn=u=>{var S=u[Pt("asyncIterator")],p=!1,J,N={};return S==null?(S=u[Pt("iterator")](),J=K=>N[K]=j=>S[K](j)):(S=S.call(u),J=K=>N[K]=j=>{if(p){if(p=!1,K==="throw")throw j;return j}return p=!0,{done:!1,value:new EA(new Promise(tA=>{var sA=S[K](j);sA instanceof Object||ae("Object expected"),tA(sA)}),1)}}),N[Pt("iterator")]=()=>N,J("next"),"throw"in S?J("throw"):N.throw=K=>{throw K},"return"in S&&J("return"),N},rA=(u,S,p)=>(S=u[Pt("asyncIterator")])?S.call(u):(u=u[Pt("iterator")](),S={},p=(J,N)=>(N=u[J])&&(S[J]=K=>new Promise((j,tA,sA)=>(K=N.call(u,K),sA=K.done,Promise.resolve(K.value).then(oA=>j({value:oA,done:sA}),tA)))),p("next"),p("return"),S);var ot=(u,S,p)=>{if(S!=null){typeof S!="object"&&typeof S!="function"&&ae("Object expected");var J,N;p&&(J=S[Pt("asyncDispose")]),J===void 0&&(J=S[Pt("dispose")],p&&(N=J)),typeof J!="function"&&ae("Object not disposable"),N&&(J=function(){try{N.call(this)}catch(K){return Promise.reject(K)}}),u.push([p,J,S])}else p&&u.push([p]);return S},nt=(u,S,p)=>{var J=typeof SuppressedError=="function"?SuppressedError:function(j,tA,sA,oA){return oA=Error(sA),oA.name="SuppressedError",oA.error=j,oA.suppressed=tA,oA},N=j=>S=p?new J(j,S,"An error was suppressed during disposal"):(p=!0,j),K=j=>{for(;j=u.pop();)try{var tA=j[1]&&j[1].call(j[2]);if(j[0])return Promise.resolve(tA).then(K,sA=>(N(sA),K()))}catch(sA){N(sA)}if(p)throw S};return K()};var Zt,eI,Et,Jg,Mg,Ft,rt,wA,Xt,le,ii,Hg,Ii,iI,II,qg,Cn,gi,si,It,ct,Bi,Ci,vg,IA,Qi,jt,ht,Gt,GA,we,De,mC,gI,Kg,Yg,DA,xE,WE,OE,VE,SC,yC,ZE,SB,fC,XE,jE,ss,Bs,Cs,Qs,YA,XA,CA,QI,me,zt,oi,zE,Qn,kt,oI,nI,os,ns,aI,as,Es,Rt,EI,rs,cs,rI,ni,_E,on,dt,cI,hs,hI,ds,ls,us,dI,FC,ai,$E,nn,ye,ws,Ut,Ei,ri,ci,Nt,Ds,hi,bt,GC,BA,yB,dQ,Vi,lQ,Pe,lI,uI,_t,kC,jA,zA,di,RC,$t,wI,hA,Ar,tr,er,ir,Ir,gr,sr,Br,Cr,Qr,DI,Ss,ys,fA,fs,mI,SI,ps,UC,or,NC,fI,pI,fe,li,bC,ui,lt,MA,Fs,Gs,gt,ks,Rs,GI,Us,LC,nr,wi,Ns,kI,bs,RI,Ls,Di,pe,ug,yE,UI,Js,NI,mi,Fe,Ge,ke,Oo,Si,fE,bI,kA,LI,JI,Vo,MI,fB,pE,FE,GE,kE,Ae,_A,yi,fi,HI,Lt,uQ,wg,RE,UE,NE,bE,ut,Ms,pi,qI,vI,pA,ar,Er,KI,wQ,DQ,mQ,pB,st,Hs,Fi,YI,qs,HA,Zi,Xi,Re,te,TI,Gi,ee,PI,xI,JC,rr,ie,Ie,Ue,vs,Ks,MC,HC,cr,ge,WI,Ys,$A,Jt,ki,Bt,Ts,qC,Ps,an,wt,Ri,se,Mt,xs,En,Ws,Ne,Os,Vs,Zs,vC,hr,Xs,OI,js,VI,zs,rn,_s,Ht,$s,AB,YC,dr,TC,be,Ui,tB,eB,iB,Ni,cn,lr,PC,IB,Le,XI,LE,bi,Li,Ji,Je,_o,jI,SQ,Mi,gB,xC,ur,sB,WC,wr,OC,_I,$I,BB,CB,JE,ME,HE,Ag,tg,Hi,bA,Dt,mt,Me,eg,QB,oB,Be,TA,yQ,FB,Dr,hn,RA,PA,Ct,qi,dA,He,nB,ig,aB,Ig,xA,mr,gg,EB,sg,Sr,yr,fr,pr,dn,Ce,vi,VC,Fr,Bg,qe,Cg,vt,Kt,Qg,Qe,og,ng,ag,ZC,XC,jC,Gr,rB,Yt,LA,Ki,Qt,kr,Dg,Rr,AQ,eA,cB,hB,dB,Ke,cg,Ur,Nr,tQ,Ye,Yi,At,Ti,hg,br,Lr;const J={buffering:"_buffering_1ccif_1","buffering-fullscreen":"_buffering-fullscreen_1ccif_16",hidden:"_hidden_1ccif_25","buffering-indicator":"_buffering-indicator_1ccif_31"};class N{constructor(A){I(this,"attach",A=>{this.detach(),A.appendChild(this.element)});I(this,"attachBefore",(A,t)=>{this.detach(),A.insertBefore(this.element,t)});I(this,"detach",()=>this.element.remove());this.element=A}}const K=J.hidden,j=J.buffering,tA=J["buffering-fullscreen"],sA=J["buffering-indicator"];class oA extends N{constructor(){super(document.createElement("div"));I(this,"indicator",document.createElement("div"));I(this,"isHidden",()=>this.element.classList.contains(K));I(this,"setHidden",t=>t?this.hide():this.show());I(this,"hide",()=>this.element.classList.add(K));I(this,"show",()=>this.element.classList.remove(K));I(this,"fullscreen",t=>{t?this.element.classList.add(tA):this.element.classList.remove(tA)});this.element.className=j,this.indicator.className=sA,this.element.appendChild(this.indicator)}}class xt{constructor(A){I(this,"maxSize",0);I(this,"size",0);I(this,"buffers",[]);I(this,"_borrowedBuffers",0);I(this,"get",A=>{const t=this.buffers.shift();return this._borrowedBuffers++,this.size<A||!t?(this.buffers=[],this.size=A,new ArrayBuffer(A)):t});I(this,"reclaim",A=>{this._borrowedBuffers=Math.max(0,this._borrowedBuffers-1),!(A.byteLength<this.size)&&(this.buffers.length>=this.maxSize||this.buffers.push(A))});this.maxSize=A}get bufferSize(){return this.size}get poolSize(){return this.buffers.length}get borrowedBuffers(){return this._borrowedBuffers}}const F=()=>{};class ${constructor(){I(this,"promise");I(this,"resolved");I(this,"resolve");I(this,"reject");I(this,"pending",!0);this.promise=new Promise((A,t)=>{this.resolve=e=>{this.pending=!1,this.resolved=e,A(e)},this.reject=e=>{this.pending=!1,t(e)}}),this.promise.catch(F)}static resolved(A){const t=new $;return t.resolve(A),t}static fromPromise(A){const t=new $;return t.promise=A,A.then(e=>{t.pending=!1,t.resolved=e},e=>{t.pending=!1,t.reject(e)}),t}}class W{constructor(A=50){I(this,"maxSize");I(this,"values",[]);I(this,"push",A=>{this.isFull()&&this.pop(),this.values.push(A)});I(this,"clear",()=>void(this.values=[]));I(this,"pop",()=>this.values.shift());I(this,"peekFirst",()=>this.values[0]);I(this,"peekLast",()=>this.values[this.values.length-1]);I(this,"isFull",()=>this.values.length>=this.maxSize);I(this,"isEmpty",()=>this.values.length===0);I(this,"items",()=>this.values);I(this,"filterPop",A=>{for(;this.peekFirst()&&!A(this.peekFirst());)this.pop()});this.maxSize=A}}function xe(i){const A=new We(i);return[A,A]}class We{constructor(A){n(this,Zt);n(this,eI,new $);n(this,Et);n(this,Jg,!1);E(this,Zt,new W(A))}isFull(){return s(this,Zt).isFull()}close(){var A;(A=s(this,Et))==null||A.resolve(),E(this,Jg,!0)}abort(A){var t,e;(t=s(this,Et))==null||t.promise.catch(F),(e=s(this,Et))==null||e.reject(A)}push(A){return r(this,null,function*(){var t;s(this,Zt).isFull()&&(yield s(this,eI).promise),s(this,Zt).push(A),(t=s(this,Et))==null||t.resolve(),E(this,Et,new $)})}pop(){return r(this,null,function*(){var A;for(;!(s(this,Jg)&&s(this,Zt).isEmpty());){const t=s(this,Zt).pop();if(t)return s(this,eI).resolve(),E(this,eI,new $),t;s(this,Et)||E(this,Et,new $),yield(A=s(this,Et))==null?void 0:A.promise}})}start(A){}pull(A){return r(this,null,function*(){const t=yield this.pop();t?A.enqueue(t):A.close()})}cancel(A){this.abort(new Error(A))}next(){return r(this,null,function*(){const A=yield this.pop().catch(()=>{});return A?{done:!1,value:A}:{done:!0,value:void 0}})}return(){return this.close(),Promise.resolve({done:!0,value:void 0})}[Symbol.asyncIterator](){return this}}Zt=new WeakMap,eI=new WeakMap,Et=new WeakMap,Jg=new WeakMap;function lA(i,A){if(!i)throw new Error(A)}function v(i){return typeof BigInt=="function"?BigInt(i):i}class VA{constructor(A,t=0){n(this,Mg);n(this,Ft);n(this,rt);I(this,"position",()=>s(this,rt));I(this,"peekBit",()=>this.getBit(s(this,Ft),s(this,rt)));I(this,"readBit",()=>{const A=this.peekBit();return ft(this,rt)._++,A});I(this,"readBits",A=>{let t=0;for(let e=0;e<A;e++)t=t<<1|(this.getBit(s(this,Ft),ft(this,rt)._++)?1:0);return t});I(this,"remainingBits",()=>s(this,Ft).byteLength*8-s(this,rt));I(this,"readSignedExpGolomb",()=>{const A=this.readUnsignedExpGolomb();return A&1?(A+1)/2:-(A/2)});I(this,"readUnsignedExpGolomb",()=>{let A=0;for(;this.getBit(s(this,Ft),ft(this,rt)._++)===0;)A++;let t=1<<A;for(let e=A-1;e>=0;e--)t|=this.getBit(s(this,Ft),ft(this,rt)._++)<<e;return t-1});I(this,"getBit",(A,t)=>{if(A.byteLength*8<=t)throw new Error("BitReader: Out of bounds");return A[t>>3]>>7-(t&7)&1});E(this,Mg,A),E(this,Ft,new Uint8Array(s(this,Mg))),E(this,rt,t)}bytes(){return s(this,Ft)}}Mg=new WeakMap,Ft=new WeakMap,rt=new WeakMap;const Oe=(i,A,t)=>{let e=0;for(let g=A;g<=t;g++)if(g===A){const B=i[g];e+=B&127,B&128&&(e-=128)}else e=e*256+i[g];return e};class SA{constructor(A){n(this,wA);n(this,Xt);n(this,le);E(this,Xt,A),E(this,le,new DataView(A.buffer,A.byteOffset,A.byteLength)),E(this,wA,0)}position(){return s(this,wA)}byteOffset(){return s(this,Xt).byteOffset+s(this,wA)}buffer(){return s(this,Xt)}remaining(){return s(this,Xt).length-s(this,wA)}readUint8(){const A=s(this,le).getUint8(s(this,wA));return E(this,wA,s(this,wA)+1),A}readUint24(){const A=s(this,le).getUint32(s(this,wA))>>8&16777215;return E(this,wA,s(this,wA)+3),A}readUint16(){const A=s(this,le).getUint16(s(this,wA));return E(this,wA,s(this,wA)+2),A}readUint32(){const A=s(this,le).getUint32(s(this,wA));return E(this,wA,s(this,wA)+4),A}readUint64(){const A=Oe(s(this,Xt),s(this,wA),s(this,wA)+7);return E(this,wA,s(this,wA)+8),A}readBytes(A){const t=s(this,Xt).subarray(s(this,wA),s(this,wA)+A);return E(this,wA,s(this,wA)+A),t}readRemaining(){return this.readBytes(this.remaining())}readUtf8String(){const A=[];let t;for(;(t=this.readUint8())!==0&&(A.push(t),this.remaining()!=0););return new TextDecoder().decode(new Uint8Array(A))}}wA=new WeakMap,Xt=new WeakMap,le=new WeakMap;class mg{constructor(A=100,t=100){I(this,"resizeSteps");I(this,"internalBuffer");I(this,"view");I(this,"uint8");I(this,"_position",0);I(this,"_end",0);this.resizeSteps=t,this.internalBuffer=new ArrayBuffer(A),this.view=new DataView(this.internalBuffer),this.uint8=new Uint8Array(this.internalBuffer)}position(){return this._position}seek(A){this._position=Math.max(0,Math.min(this._end,A))}seekToEnd(){this._position=this._end}writeUint8(A){this.writeAndMove(A,1)}writeUint16(A){this.writeAndMove(A,2)}writeUint24(A){this.writeAndMove(A,3)}writeUint32(A){this.writeAndMove(A,4)}writeUint64(A){const t=Math.floor(A/4294967296),e=(A&4294967295)>>>0;this.writeUint32(t),this.writeUint32(e)}writeUint32At(A,t){this.view.setUint32(A,t)}writeBytes(A){this.resizeIfNeeded(this.position()+A.byteLength),this.uint8.set(A,this.position()),this._position+=A.byteLength,this._end=Math.max(this._end,this._position)}buffer(){return this.internalBuffer.slice(0,this._end)}write(A,t){switch(this.resizeIfNeeded(this.position()+t),t){case 1:this.view.setUint8(this.position(),A);break;case 2:this.view.setUint16(this.position(),A);break;case 3:this.view.setUint8(this.position(),A>>16&255),this.view.setUint8(this.position()+1,A>>8&255),this.view.setUint8(this.position()+2,A&255);break;case 4:this.view.setUint32(this.position(),A);break}}writeAndMove(A,t){this.write(A,t),this._position+=t,this._end=Math.max(this._end,this._position)}resizeIfNeeded(A){if(A>this.internalBuffer.byteLength){const t=new ArrayBuffer(A+this.resizeSteps),e=new Uint8Array(t);e.set(this.uint8),this.internalBuffer=t,this.view=new DataView(this.internalBuffer),this.uint8=e}}}function ln(i){const A=atob(i),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t.buffer}function Sg(){const i=self.MediaSource,A=self.ManagedMediaSource;return i!=null?i:A}const Jr=/(android|bbd+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up.(browser|link)|vodafone|wap|windows ce|xda|xiino\/i.test(a)||\/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-\//i,qA=navigator.userAgent.toLowerCase(),Mr=Jr.test(qA),Hr=()=>{const i=document.createElement("video");return i.canPlayType("application/vnd.apple.mpegURL")!==""||i.canPlayType("audio/mpegurl")!==""},qr=()=>{try{if(typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function"){const i=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(i instanceof WebAssembly.Module)return new WebAssembly.Instance(i)instanceof WebAssembly.Instance}}catch(i){return!1}return!1},vr=()=>qA.indexOf("CrKey")!==-1,un=()=>navigator.platform==="MacIntel"&&navigator.maxTouchPoints===0,GB=()=>navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,Kr=()=>qA.indexOf("iphone")>=0&&qA.indexOf("like iphone")<0||qA.indexOf("ipad")>=0&&qA.indexOf("like ipad")<0||qA.indexOf("ipod")>=0&&qA.indexOf("like ipod")<0||GB(),Yr=()=>{var i,A;return GB()?!1:(A=(i=Sg())==null?void 0:i.isTypeSupported('audio/mp4; codecs="opus"'))!=null?A:!1},Tr=()=>/^(?!.*chrome).*safari/i.test(qA);function Pr(){var i,A;if(/(iPhone|iPod|iPad)/i.test(qA))return(A=(i=qA==null?void 0:qA.match(/OS [\d_]+/i))==null?void 0:i[0])==null?void 0:A.substring(3).split("_").map(t=>parseInt(t))[0]}function xr(){var i,A;if(/^((?!chrome|android).)*safari/i.test(qA))return(A=(i=qA.match(/version\/([\d.]+)/))==null?void 0:i[1])==null?void 0:A.split(".").map(t=>parseInt(t))[0]}const fQ=()=>{var t,e;const i=!!Sg();let A=!1;return i&&(A=Yr()),{isMobile:Mr,supportsMp4Opus:A,supportsMediaSource:i,supportsHls:Hr(),supportsWebAssembly:qr(),platform:{iosVersion:(t=Pr())!=null?t:Number.MAX_SAFE_INTEGER,safariVersion:(e=xr())!=null?e:Number.MAX_SAFE_INTEGER,isIpadOS:GB(),isMacOS:un(),isIOS:Kr()}}};class ji{constructor(A,t,e){I(this,"onSuccess");I(this,"onError");I(this,"doExecute");this.doExecute=A,this.onSuccess=t,this.onError=e}execute(A){try{this.doExecute(A),this.onSuccess()}catch(t){this.onError(t)}}}const Wt=i=>i.reduce((A,t)=>A+t,0)/i.length,re=i=>({last:i[i.length-1]||0,average:i.length===0?0:Wt(i),max:i.length===0?0:Math.max(...i),min:i.length===0?0:Math.min(...i)}),Wr=i=>{let A=0,t=0,e=0,g=0,B=0;for(let a=0;a<i.length;a++){const{x:c,y:h}=i[a];A+=c,t+=h,e+=c*h,g+=c*c,B+=h*h}const C=(i.length*e-A*t)/(i.length*g-A*A),Q=(t-C*A)/i.length,o=((i.length*e-A*t)/Math.sqrt((i.length*g-A*A)*(i.length*B-t*t)))**2;return{slope:C,intercept:Q,r2:o,predict:a=>C*(i.length+a)+Q}};class Or{constructor(A=10){I(this,"rates");I(this,"_total",0);I(this,"accumulatedValues",0);I(this,"lastTickTime",Date.now());I(this,"add",A=>{this.accumulatedValues+=A,this._total+=A});I(this,"tick",()=>{const A=this.accumulatedValues/((Date.now()-this.lastTickTime)/1e3);this.rates.push(A),this.accumulatedValues=0,this.lastTickTime=Date.now()});this.rates=new W(A)}get total(){return this._total}get average(){return this.rates.isEmpty()?0:Wt(this.rates.items())}get minMaxAverage(){return re(this.rates.items())}}const Ve=(i,A)=>{if(i===A)return!0;if(i==null||typeof i!="object"||A==null||typeof A!="object")return!1;let t=0,e=0;for(const g in i)t+=1;for(const g in A)if(e+=1,!(g in i)||!Ve(i[g],A[g]))return!1;return t==e};class it{constructor(){I(this,"listeners",{})}emit(A,t){const e=this.listeners[A];e&&(this.listeners[A]=e.filter(B=>!B.once),e.map(B=>B.fn(t)).map(B=>typeof B=="function"&&(B==null?void 0:B())))}off(A,t){const e=this.listeners[A];e&&(this.listeners[A]=e.filter(g=>g.fn!==t))}on(A,t){this.add(A,t,!1)}once(A,t){this.add(A,t,!0)}reset(){this.listeners={}}add(A,t,e){const g=this.listeners[A],B={fn:t,once:e};g?g.push(B):this.listeners[A]=[B]}}const pQ=1e3,FQ=pQ*1e3,wn=FQ*1e3,GQ=(i,A,t)=>i%A===0?i/A:(i/A).toFixed(t),Vr=(i,A=1)=>i>=wn?`${GQ(i,wn,A)} Gbit/s`:i>=FQ?`${GQ(i,FQ,A)} Mbit/s`:i>=pQ?`${GQ(i,pQ,A)} Kbit/s`:`${i} bit/s`,Zr=({width:i,height:A})=>`${i}x${A}`,Xr=i=>i%1e3===0?`${i/1e3} kHz`:i>1e3?`${(i/1e3).toFixed(1)} kHz`:`${i} Hz`,Dn=["off","error","warn","info","debug","trace"],jr={OFF:"off"},ue=class ue{constructor({context:A,logLevel:t,debug:e}){n(this,ii,new Map);n(this,Hg,"");n(this,Ii,!1);n(this,iI,"off");I(this,"trace",(...A)=>{});I(this,"debug",(...A)=>{});I(this,"info",(...A)=>{});I(this,"warn",(...A)=>{});I(this,"error",(...A)=>{});I(this,"table",(...A)=>{});I(this,"count",(...A)=>{});E(this,Hg,A),E(this,iI,t),E(this,Ii,e||!1),this.setLevel(t),this.setDebug(s(this,Ii))}setDebug(A){E(this,Ii,A);for(const[t,e]of s(this,ii))e.setDebug(A);A?(this.table=console.table.bind(console),this.count=console.count.bind(console)):(this.table=()=>{},this.count=()=>{})}setLevel(A){E(this,iI,A);for(const[e,g]of s(this,ii))g.setLevel(A);const t=Dn.indexOf(A);for(const[e,g]of Dn.entries())g!=="off"&&(e<=t?this[g]=console[g].bind(console,"%c%s %c%s","font-weight:bold;",g.toUpperCase(),"font-weight:normal;",s(this,Hg)):this[g]=()=>{})}createContext(A){const t=s(this,ii).get(A);if(!t){const e=new ue({context:`${A}`,logLevel:s(this,iI),debug:s(this,Ii)});return s(this,ii).set(A,e),e}return t}static get(){return s(ue,II)||E(ue,II,new ue({context:"Vindral",logLevel:"off"})),s(ue,II)}};ii=new WeakMap,Hg=new WeakMap,Ii=new WeakMap,iI=new WeakMap,II=new WeakMap,n(ue,II);let UA=ue;function ZA(i){const A=UA.get().createContext(i.context);return function(e,g){const B=String(g.name);function C(...Q){i.enter&&A[i.enter](`Enter '${B}'`,D({},Q));try{const o=e.call(this,...Q);return o instanceof Promise?o.then(a=>{i.return&&A[i.return](`Return '${B}'`,a)}).catch(a=>{i.error&&A[i.error](`Error '${B}'`,a)}):i.return&&A[i.return](`Return '${B}'`,o),o}catch(o){throw i.error&&A[i.error](`Error '${B}'`,o),o}}return C}}function pt(){return typeof Symbol.asyncDispose!="symbol"&&Object.defineProperty(Symbol,"asyncDispose",{value:Symbol.for("asyncDispose")}),Symbol.asyncDispose}function mn(){return typeof Symbol.dispose!="symbol"&&Object.defineProperty(Symbol,"dispose",{value:Symbol.for("dispose")}),Symbol.dispose}class zr{constructor(A,t){n(this,qg);I(this,"value");I(this,"unlocker");this.value=A,this.unlocker=t}unlocked(){var A;return(A=this.unlocker)==null?void 0:A.promise}[mn()](){d(this,qg,Cn).call(this)}[Symbol.dispose](){d(this,qg,Cn).call(this)}}qg=new WeakSet,Cn=function(){this.unlocker.resolve(this.value)};class _r{constructor(A){n(this,gi);n(this,si,new $);E(this,gi,A),s(this,si).resolve(A)}unsafeValue(){return s(this,gi)}isLocked(){return s(this,si).pending}lock(){return r(this,null,function*(){const A=new $;A.promise.then(e=>{E(this,gi,e)}).catch(F);const t=s(this,si).promise.then(()=>A);return E(this,si,A),yield t,new zr(s(this,gi),A)})}}gi=new WeakMap,si=new WeakMap;class vA{constructor(A){n(this,It);n(this,ct);E(this,It,A),E(this,ct,new $)}isClosed(){var A;return!((A=s(this,ct))!=null&&A.pending)}current(){return s(this,It)}value(){var A;return[s(this,It),(A=s(this,ct))==null?void 0:A.promise]}update(A){var t;if(!((t=s(this,ct))!=null&&t.pending))throw new Error("ObservableValue is closed");E(this,It,A instanceof Function?A(s(this,It)):A),s(this,ct).resolve(s(this,It)),E(this,ct,new $)}close(){var A;(A=s(this,ct))==null||A.resolve(s(this,It)),E(this,ct,void 0)}waitFor(A){return r(this,null,function*(){if(A(s(this,It)))return s(this,It);for(;;){const[t,e]=this.value();if(!e)throw new Error("ObservableValue was closed while waiting for condition");const g=yield e;if(A(g))return g}})}[Symbol.asyncIterator](){return Ee(this,null,function*(){for(;;){const[A,t]=this.value();if(yield A,!t)return;yield new EA(t)}})}}It=new WeakMap,ct=new WeakMap;const Sn=(i,A)=>{const t=D({},i);return typeof t!="object"||A.forEach(e=>{delete t[e]}),t},DC=class DC{constructor(){I(this,"pendingTimeouts",new Set);I(this,"pendingIntervals",new Set);I(this,"clearTimeout",A=>{this.pendingTimeouts.delete(A)&&window.clearTimeout(A)});I(this,"clearInterval",A=>{this.pendingIntervals.delete(A)&&window.clearInterval(A)});I(this,"setTimeout",(A,t,...e)=>{const g=window.setTimeout(()=>{A(...e),this.clearTimeout(g)},t);return this.pendingTimeouts.add(g),g});I(this,"setInterval",(A,t,...e)=>{const g=window.setInterval(()=>{A(...e)},t);return this.pendingIntervals.add(g),g});I(this,"unload",()=>{this.pendingIntervals.forEach(this.clearInterval),this.pendingTimeouts.forEach(this.clearTimeout)})}};I(DC,"create",()=>new DC);let NA=DC;const Ze=(i,A=Date.now())=>{const t=i.length;if(t>0){const e=t-1,g=i[e];g.end||(g.end=A)}},zi=(i,A=Date.now())=>{Ze(i),i.push({start:A})},_i=i=>i.reduce((A,t)=>{var e;return A+(((e=t.end)!=null?e:Date.now())-t.start)},0),yn=(i,A,t=Date.now())=>i.reduce((e,g)=>{var Q;const B=Math.max(t-A,g.start),C=(Q=g.end)!=null?Q:t;return Math.max(0,C-B)+e},0);function fn(i){try{return i()}catch(A){return A}}const pn=i=>{try{return JSON.parse(i)}catch(A){return}},Fn=()=>{const i=[...Array(256).keys()].map(t=>t.toString(16).padStart(2,"0")),A=crypto.getRandomValues(new Uint8Array(16));return A[6]=A[6]&15|64,A[8]=A[8]&63|128,[...A.entries()].map(([t,e])=>[4,6,8,10].includes(t)?`-${i[e]}`:i[e]).join("")},ce=i=>r(null,null,function*(){return new Promise(A=>setTimeout(A,i))}),kQ=(t,...e)=>r(null,[t,...e],function*(i,A=new Error("Timeout")){return new Promise((g,B)=>setTimeout(()=>B(A),i))}),$r=(i,A)=>r(null,null,function*(){throw yield i,new Error(A)});class Gn extends it{constructor(t){super();I(this,"config");I(this,"hlsUrl");I(this,"element");I(this,"connectingTimeout");I(this,"castingAvailable",!1);I(this,"updateAuthenticationToken",t=>{this.config.authenticationToken=t,this.hlsUrl=this.getHlsUrl(),this.castingAvailable&&(this.element.src=this.hlsUrl)});I(this,"unload",()=>{this.element&&(this.element.removeEventListener("webkitplaybacktargetavailabilitychanged",this.onAirPlayAvailable),this.element.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",this.onAirPlayPlaybackChanged),this.element.remove())});I(this,"onAirPlayAvailable",t=>{switch(t.availability){case"available":{this.castingAvailable=!0,this.element.src!==this.hlsUrl&&this.checkHlsUrl(this.hlsUrl).then(g=>{g&&(this.element.src=this.hlsUrl,this.emit("available"))});break}case"not-available":this.castingAvailable=!1;break}});I(this,"onAirPlayPlaybackChanged",()=>{window.clearTimeout(this.connectingTimeout),this.element.webkitCurrentPlaybackTargetIsWireless?(this.emit("connected"),this.element.style.display="block",this.element.paused&&this.element.play()):(this.emit("disconnected"),this.element.pause(),this.element.src="",this.element.src=this.hlsUrl,this.element.style.display="none")});this.config=t,this.hlsUrl=this.getHlsUrl(),this.element=document.createElement("video"),this.element.style.position="absolute",this.element.style.top="0",this.element.style.bottom="0",this.element.style.left="0",this.element.style.right="0",this.element.style.width="100%",this.element.style.height="100%",this.element.style.zIndex="1001",this.element.style.display="none",this.element.id="vindral-airplay-element",this.element.slot="overlay",this.element.playsInline=!0,this.element.controls=!0,this.element.preload="metadata",this.element.addEventListener("webkitplaybacktargetavailabilitychanged",this.onAirPlayAvailable),this.element.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",this.onAirPlayPlaybackChanged),this.config.container.appendChild(this.element)}get casting(){return this.element.webkitCurrentPlaybackTargetIsWireless}set channelId(t){}showPlaybackTargetPicker(){this.element.paused&&(this.element.play(),this.connectingTimeout=window.setTimeout(()=>{this.casting||(this.element.pause(),this.element.src="",this.element.src=this.hlsUrl)},3e4)),this.element.webkitShowPlaybackTargetPicker()}static isAirPlaySupported(){return!!window.WebKitPlaybackTargetAvailabilityEvent}getHlsUrl(){const t=new URL(`/api/hls?channelId=${this.config.channelId}`,this.config.url);return this.config.authenticationToken&&t.searchParams.set("authenticationToken",this.config.authenticationToken),t.toString()}checkHlsUrl(t){return r(this,null,function*(){try{return(yield fetch(t,{method:"HEAD"})).ok}catch(e){return!1}})}}class kn extends it{constructor(t){super();I(this,"state","not casting");I(this,"config");I(this,"unloaded",!1);I(this,"updateAuthenticationToken",t=>{this.config&&(this.config.options.authenticationToken=t,this.send({type:"updateAuthToken",token:t}))});I(this,"unload",()=>{var t;this.unloaded=!0,(t=this.getSession())==null||t.removeMessageListener("urn:x-cast:com.vindral.castdata",this.onMessage)});I(this,"init",()=>r(this,null,function*(){return new Promise((t,e)=>{let g=!1;const B=setTimeout(()=>{g=!0,e()},1e4);window.__onGCastApiAvailable=C=>{if(g){g=!1;return}if(clearTimeout(B),!C)return e();setTimeout(()=>{try{this.onGCastApiAvailable(),t()}catch(Q){e()}},1e3)},this.castLibrariesAdded()&&window.cast?window.__onGCastApiAvailable(!0):this.verifyCastLibraries()})}));I(this,"start",()=>r(this,null,function*(){var t;yield(t=this.getInstance())==null?void 0:t.requestSession()}));I(this,"stop",()=>{var t;(t=this.getSession())==null||t.endSession(!0)});I(this,"getReceiverName",()=>{var t,e;return((e=(t=this.getSession())==null?void 0:t.getCastDevice())==null?void 0:e.friendlyName)||void 0});I(this,"onGCastApiAvailable",()=>{var B;const t=this.getInstance();if(!t)throw"cast context should exist";const e=t.getSessionState(),g=((B=this.config)==null?void 0:B.receiverApplicationId)||"A5452297";t.setOptions({receiverApplicationId:g,autoJoinPolicy:chrome.cast.AutoJoinPolicy.TAB_AND_ORIGIN_SCOPED,resumeSavedSession:!0}),t.addEventListener(cast.framework.CastContextEventType.SESSION_STATE_CHANGED,this.onSessionStateChanged),e===cast.framework.SessionState.SESSION_STARTED&&setTimeout(()=>{this.state="casting",this.emit("resumed")})});I(this,"send",t=>{var e;(e=this.getSession())==null||e.sendMessage("urn:x-cast:com.vindral.castdata",t)});I(this,"onMessage",(t,e)=>{if(t==="urn:x-cast:com.vindral.castdata")try{const g=JSON.parse(e);switch(g.type){case"metadata":this.emit("metadata",g.metadata);break;case"serverWallclockTime":this.emit("server wallclock time",g.serverWallclockTime);break;default:break}}catch(g){}});I(this,"onSessionStarted",()=>{var t;(t=this.getSession())==null||t.addMessageListener("urn:x-cast:com.vindral.castdata",this.onMessage),this.send({type:"start",config:this.config})});I(this,"onSessionStateChanged",t=>{if(!this.unloaded)switch(t.sessionState){case cast.framework.SessionState.SESSION_START_FAILED:this.state="not casting",this.emit("failed");break;case cast.framework.SessionState.SESSION_ENDED:this.state="not casting",this.emit("disconnected");break;case cast.framework.SessionState.SESSION_ENDING:break;case cast.framework.SessionState.SESSION_RESUMED:this.onSessionStarted(),this.state="casting",this.emit("resumed");break;case cast.framework.SessionState.SESSION_STARTED:this.onSessionStarted(),this.state="casting",this.emit("connected");break;case cast.framework.SessionState.SESSION_STARTING:break}});I(this,"getInstance",()=>{var t;return(t=window.cast)==null?void 0:t.framework.CastContext.getInstance()});I(this,"getSession",()=>{var t;return(t=this.getInstance())==null?void 0:t.getCurrentSession()});I(this,"castLibrariesAdded",()=>!!(document.querySelector("#vindralCastFrameworkLib")&&document.querySelector("#vindralCastSenderLib")));I(this,"verifyCastLibraries",()=>{if(this.castLibrariesAdded())return;const t=document.createElement("script");t.type="text/javascript",t.id="vindralCastFrameworkLib",t.src="//www.gstatic.com/cast/sdk/libs/sender/1.0/cast_framework.js",document.head.appendChild(t);const e=document.createElement("script");e.type="text/javascript",e.id="vindralCastSenderLib",e.src="//www.gstatic.com/cv/js/sender/v1/cast_sender.js",document.head.appendChild(e)});this.config=t}get casting(){return this.state==="casting"}get volume(){var t,e;return(e=(t=this.getSession())==null?void 0:t.getVolume())!=null?e:0}set volume(t){var e;(e=this.getSession())==null||e.setVolume(t)}get language(){var t,e;return(e=(t=this.config)==null?void 0:t.options)==null?void 0:e.language}set language(t){this.config&&(this.config.options.language=t,this.send({type:"setLanguage",language:t}))}get channelId(){var t;return((t=this.config)==null?void 0:t.options.channelId)||""}set channelId(t){this.config&&(this.config.options.channelId=t,this.send({type:"setChannelId",channelId:t}))}}const RQ=i=>{switch(i){case"h264":case"av1":return"video";case"aac":case"opus":case"mp3":return"audio";case"webvtt":return"text";default:throw new Error("Unknown codec")}};function UQ(i){if(i.startsWith("opus"))return"opus";if(i.startsWith("mp4a"))return"aac";if(i.startsWith("avc1"))return"h264";if(i.startsWith("av01"))return"av1";if(i.startsWith("webvtt"))return"webvtt"}function Rn(i){return!(typeof i.edges[0]=="string"||i.channels[0]&&!("catalog"in i.channels[0]))}function Un(i){return i.tracks.filter(A=>!!A.codec).filter(A=>UQ(A.codec||"")).map((A,t)=>{const e=A.codec,g=A.bitrate;lA(e,"codec is required"),lA(g!=null,"bitrate is required");const B=UQ(e);if(lA(B,"codec is required"),RQ(B)==="audio"){const C=A.samplerate||0,Q=A.channelConfig==="stereo"?2:1;return{track:A,id:t,codec:B,codecString:e,bitRate:g,channels:Q,sampleRate:C,language:A.language}}return RQ(B)==="text"?{track:A,id:t,bitRate:0,codec:B,kind:"subtitles",codecString:e,label:A.label,language:A.language}:(lA(A.width,"width is required"),lA(A.height,"width is required"),lA(A.framerate,"framerate is required"),{track:A,id:t,codec:B,bitRate:g,codecString:e,width:A.width,height:A.height,frameRate:A.framerate})}).sort((A,t)=>A.bitRate-t.bitRate)}const Xe=i=>"width"in i&&typeof i.width=="number",je=i=>"sampleRate"in i&&typeof i.sampleRate=="number",ze=i=>{switch(i.codec){case"opus":return'audio/mp4; codecs="opus"';case"mp3":return"audio/mpeg";case"webvtt":return"text/vtt";case"aac":return i.codecString?`audio/mp4; codecs="${i.codecString}"`:"audio/mp4";case"h264":return i.codecString?`video/mp4; codecs="${i.codecString}"`:"video/mp4";case"av1":return i.codecString?`video/mp4; codecs="${i.codecString}"`:"video/mp4"}},he=()=>Number.MAX_SAFE_INTEGER,kB=()=>({width:Number.MAX_SAFE_INTEGER,height:Number.MAX_SAFE_INTEGER}),Nn=i=>!(typeof i!="object"||i===null||!("type"in i)),Ac={sizeBasedResolutionCapEnabled:!0,pictureInPictureEnabled:!0,abrEnabled:!0,burstEnabled:!1,mseEnabled:!0,mseOpusEnabled:!0,muted:!1,volume:1,minBufferTime:1500,maxBufferTime:1500,logLevel:jr.OFF,maxSize:kB(),maxVideoBitRate:he(),maxAudioBitRate:he(),maxInitialBitRate:2.5*1e3*1e3,tags:[],media:"audio+video",poster:!0,reconnectHandler:i=>i.reconnectRetries<30,iosWakeLockEnabled:!1,telemetryEnabled:!0,iosMediaElementEnabled:!1,pauseSupportEnabled:!0,advanced:{wasmDecodingConstraint:{bitRate:Number.MAX_SAFE_INTEGER,width:1280,height:1280}},videoCodecs:["av1","h264"],webtransportEnabled:!0},bn="connection_failed",Ln="connection_failed_will_not_attempt_again",Jn="authentication_error",Mn="authentication_expired",Hn="channel_not_found",qn="no_incoming_data_error",vn="connection_inactivity",tc="missing_init_segment",ec="no_track_context",ic="invalid_track_context_state",Kn="disconnected_by_edge",Ic="decoder_error",gc="audio_player_error",sc="media_source_error",Bc="webgl_context_lost_error",Cc="access_forbidden",Qc="channel_switch_failed",oc="drm_error";class x extends Error{constructor(t,e,g={}){super(t);I(this,"props");I(this,"extra",{});I(this,"code",()=>this.props.code);I(this,"isFatal",()=>this.props.isFatal);I(this,"source",()=>this.props.source);I(this,"type",()=>{var t;return(t=this.props.type)!=null?t:"external"});I(this,"toStringifiable",()=>{var g;const t=this.source(),e=t instanceof Error?t.stack:this.stack;return V(D({},this.extra),{code:this.props.code,isFatal:this.props.isFatal,type:this.props.type,message:this.message,sourceMessage:(g=this.source())==null?void 0:g.message,stack:e})});this.props=e,this.extra=g,Object.setPrototypeOf(this,new.target.prototype)}}const nc=(i,A)=>new x("MediaElement Error",{isFatal:i,code:"media_element_error",source:A},{mediaErrorCode:A.code}),Yn=(i,A)=>new x("Decoder Error",{isFatal:i,code:Ic,source:A,type:"internal"}),Tn=(i,A)=>new x("Audio Player Error",{isFatal:i,code:gc,source:A,type:"internal"}),ac=(i,A)=>new x(`No init segment for rendition id ${i} for channel ${A}`,{isFatal:!1,code:tc,type:"internal"}),Pn=(i,A,t,e)=>new x("MediaSource Error",{isFatal:i,code:sc,source:A,type:"internal"},{type:e,consecutiveErrorsCount:t}),RB=(i,A)=>new x(`No track context for ${i}${A?`, rendition id ${A}`:""}`,{isFatal:!1,code:ec,type:"internal"}),Ec=(i,A)=>new x(`Track context is in an invalid state for ${i}${A?`, rendition id ${A}`:""}`,{isFatal:!1,code:ic,type:"internal"}),rc=()=>new x("Web Audio Context resume timeout",{isFatal:!1,code:"web_audio_context_resume_timeout"}),yg=i=>new x("Disconnected From Edge Server",{type:"external",source:i,isFatal:!1,code:Kn}),UB=i=>new x("Authentication Failed",{isFatal:!0,code:Jn,source:i}),cc=i=>new x("Authentication Expired",{isFatal:!0,code:Mn,source:i}),hc=(i,A)=>new x("Connection closed due to inactivity",{isFatal:!1,code:vn,source:A,type:i}),xn=(i,A)=>new x("Channel not found",{isFatal:!1,code:Hn,source:A,type:i}),dc=i=>new x("No Incoming Data",{isFatal:!1,code:qn,source:i}),lc=i=>new x("Connection attempt failed",{isFatal:!1,code:bn,source:i}),Wn=()=>new x("Connection failed - no more reconnect attempts",{isFatal:!0,code:Ln}),uc=i=>new x("WebGL Context Lost",{isFatal:!1,code:Bc,source:i,type:"internal"}),On=i=>new x(i,{isFatal:!0,code:Cc}),Vn=i=>new x(`Channel switch to '${i}' failed`,{isFatal:!1,code:Qc}),Zn=(i,A=!1,t)=>new x(i,{isFatal:A,code:oc,source:t});class NB{constructor(A,t,e,g){I(this,"keySystem");I(this,"licenseServerUrl");I(this,"certificate");I(this,"headers",{});I(this,"queryParams",{});n(this,Bi);n(this,Ci);E(this,Bi,t),this.keySystem=A,this.licenseServerUrl=e,this.certificate=g}get statistics(){return{keySystem:s(this,Bi).keySystem,licenseServerUrl:this.licenseServerUrl,mediaKeySystemConfiguration:s(this,Bi).getConfiguration()}}getMediaKeys(){return r(this,null,function*(){return s(this,Ci)?s(this,Ci):(E(this,Ci,yield s(this,Bi).createMediaKeys()),s(this,Ci))})}requestLicense(A){return r(this,null,function*(){const t=new URL(this.licenseServerUrl);for(const[B,C]of Object.entries(this.queryParams))t.searchParams.append(B,C);const e=yield fetch(t,{method:"POST",body:A,headers:D({"Content-Type":"application/octet-stream"},this.headers)});if(!e.ok)throw new Error(`Failed to fetch license: ${e.statusText}`);return yield e.arrayBuffer()})}}Bi=new WeakMap,Ci=new WeakMap;function Xn(i){const A=window.atob(i.replace(/-/g,"+").replace(/_/g,"/"));let t="";for(let e=0;e<A.length;e++)t+=("0"+A.charCodeAt(e).toString(16)).substr(-2);return t}function wc(i){let A="";for(let t=0;t<i.length;t+=2)A+=String.fromCharCode(parseInt(i.substr(t,2),16));return window.btoa(A).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Dc(i,A){if(i.byteLength!==A.byteLength)return!1;const t=new Uint8Array(i),e=new Uint8Array(A);for(let g=0;g<t.length;g++)if(t[g]!==e[g])return!1;return!0}class mc extends NB{constructor(t,e){super("clearkey",t,"");n(this,vg);E(this,vg,e)}handleLicenseRequest(t){const e=new Uint8Array(t),g=String.fromCharCode(...e),B=JSON.parse(g),C=[];for(let a=0;a<B.kids.length;a++){const c=B.kids[a];if(c){const h=Xn(c).toLowerCase(),l=s(this,vg)[h];l&&C.push({kty:"oct",alg:"A128KW",kid:c,k:wc(l)})}}const Q=JSON.stringify({keys:C,type:B.type});return new TextEncoder().encode(Q)}}vg=new WeakMap;const jn={playready:["150","2000","3000"],widevine:["SW_SECURE_CRYPTO","SW_SECURE_DECODE","HW_SECURE_CRYPTO","HW_SECURE_DECODE","HW_SECURE_ALL"],fairplay:[""],clearkey:[""]},NQ={initDataTypes:["cenc"],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42c01f"'}]},Sc={fairplay:{keySystem:"com.apple.fps",supportedConfig:{initDataTypes:["sinf"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42c01f"'}]}},playready:{keySystem:"com.microsoft.playready",supportedConfig:NQ},widevine:{keySystem:"com.widevine.alpha",supportedConfig:NQ},clearkey:{keySystem:"org.w3.clearkey",supportedConfig:NQ}},zn=(i,A)=>r(null,null,function*(){return navigator.requestMediaKeySystemAccess(i,[A]).catch(()=>{})}),_n=(i,A,t,e,g,B)=>r(null,null,function*(){let C;for(const Q of e){const o=t==null?void 0:t.map(c=>V(D({},c),{robustness:Q,contentType:B?`${g==="audioCapabilities"?"audio/mp4":"video/mp4"}; codecs="${B}"`:c.contentType}));if(!(yield zn(i,{initDataTypes:A,[g]:o})))break;C=o}return C}),yc=(i,A,t,e)=>r(null,null,function*(){const{keySystem:g,supportedConfig:B}=Sc[i],{initDataTypes:C,videoCapabilities:Q,audioCapabilities:o}=B,a=e==null?void 0:e[i],c=(a==null?void 0:a.videoRobustness)||jn[i],h=(a==null?void 0:a.audioRobustness)||jn[i],[l,m]=yield Promise.all([_n(g,C,Q,c,"videoCapabilities",A),_n(g,C,o,h,"audioCapabilities",t)]);return!l&&!m?void 0:yield zn(g,{initDataTypes:C,videoCapabilities:l,audioCapabilities:m})}),fc=(i,A,t,e)=>r(null,null,function*(){let g;for(const B of i)if(g=yield yc(B,A,t,e),g)return{keySystem:B,mediaKeySystemAccess:g}});class pc extends NB{constructor(A,t,e){super("fairplay",A,t,e)}}const Fc=i=>{var Q,o,a,c;const A=String.fromCharCode(...new Uint16Array(i)),t=new window.DOMParser().parseFromString(A,"application/xml"),e=t.getElementsByTagName("HttpHeaders")[0];let g={};if(e){const h=e.getElementsByTagName("name"),l=e.getElementsByTagName("value");for(let m=0;m<h.length;m++){const y=(Q=h[m])==null?void 0:Q.childNodes[0],f=(o=l[m])==null?void 0:o.childNodes[0];y!=null&&y.nodeValue&&f&&f.nodeValue&&(g[y.nodeValue]=f.nodeValue)}}const B=t.getElementsByTagName("Challenge")[0];let C;return B&&((a=B.childNodes[0])!=null&&a.nodeValue)&&(C=window.atob((c=B.childNodes[0])==null?void 0:c.nodeValue)),t.querySelector("parsererror")&&(g={"Content-Type":"text/xml; charset=utf-8",SOAPAction:'"http://schemas.microsoft.com/DRM/2007/03/protocols/AcquireLicense"'},C=i),{headers:g,message:C}};class Gc extends NB{constructor(A,t){super("playready",A,t)}requestLicense(A){return r(this,null,function*(){lA(this.licenseServerUrl,"No license server URL set");const t=new URL(this.licenseServerUrl);for(const[B,C]of Object.entries(this.queryParams))t.searchParams.append(B,C);const e=Fc(A),g=yield fetch(t,{method:"POST",headers:D(D({},e.headers),this.headers),body:e.message});if(!g.ok)throw new Error(`Failed to fetch license: ${g.statusText}`);return yield g.arrayBuffer()})}}class kc extends NB{constructor(A,t){super("widevine",A,t)}}const Rc=5e3;class $n{constructor(A,t,e={}){n(this,DA);n(this,IA);n(this,Qi);n(this,jt);n(this,ht,new $);n(this,Gt);n(this,GA);n(this,we,new Map);n(this,De);n(this,mC,fQ());n(this,gI);n(this,Kg,A=>{if(s(this,IA).info("Received DRM data",{drmData:A}),window.clearTimeout(s(this,gI)),s(this,GA)){const t=d(this,DA,jE).call(this,A)[s(this,GA).keySystem];t&&(s(this,GA).licenseServerUrl=t)}s(this,ht).resolve(A)});n(this,Yg,A=>{s(this,IA).info("Encrypted event received",{event:A}),d(this,DA,xE).call(this,A)});n(this,SC,A=>{var B,C;s(this,IA).debug("Session message received",{event:A});const t=A.target,e=A.message;if(!s(this,we).get(t)){s(this,IA).error("No active session found for event",{event:A});return}s(this,IA).debug("Requesting license for session",{sessionId:t.sessionId,licenseServerUrl:(B=s(this,GA))==null?void 0:B.licenseServerUrl}),(C=s(this,GA))==null||C.requestLicense(e).then(Q=>{s(this,IA).debug("License received for session",{sessionId:t.sessionId}),t.update(Q).catch(o=>{d(this,DA,SB).call(this,{message:"Failed to update session with license",isFatal:!1,error:o})})}).catch(Q=>{d(this,DA,SB).call(this,{message:"Failed to request license",isFatal:!1,error:Q})})});n(this,yC,A=>{const t=A.target;s(this,IA).debug("Key status changed for session",{sessionId:t.sessionId}),t.keyStatuses.forEach((e,g)=>{const B=Xn(window.btoa(String.fromCharCode(...new Uint8Array(g))));s(this,IA).debug("Key status",{base64kid:B,status:e})})});n(this,fC,A=>r(this,null,function*(){const t=d(this,DA,XE).call(this,A);s(this,IA).debug("Prioritized key system list",{keySystemList:t});const e=yield fc(t,A.videoCodec,A.audioCodec,{widevine:s(this,Gt).widevine,playready:s(this,Gt).playready});if(!e)return s(this,IA).warn("No supported key system found"),null;s(this,IA).debug("Supported key system found",e.mediaKeySystemAccess.getConfiguration());const{keySystem:g,mediaKeySystemAccess:B}=e;let C=null;return g==="clearkey"?(lA(A.clearkeys,"No clearkeys found"),C=new mc(B,A.clearkeys)):g==="playready"?(lA(A.playreadyLicenseUrl,"No playreadyLicenseUrl found"),C=new Gc(B,A.playreadyLicenseUrl)):g==="widevine"?(lA(A.widevineLicenseUrl,"No widevineLicenseUrl found"),C=new kc(B,A.widevineLicenseUrl)):g==="fairplay"&&(lA(A.fairplayLicenseUrl,"No fairplayLicenseUrl found"),lA(A.fairplayCertificate,"No fairplayCertificate found"),C=new pc(B,A.fairplayLicenseUrl,A.fairplayCertificate)),C&&(C.headers=s(this,Gt).headers||{},C.queryParams=s(this,Gt).queryParams||{}),C}));E(this,Qi,A),E(this,IA,t),E(this,Gt,e),s(this,Qi).on("received drm data",s(this,Kg))}static isSupported(){return!!navigator.requestMediaKeySystemAccess}attach(A){E(this,jt,A),s(this,IA).info("Media element attached"),s(this,jt).addEventListener("encrypted",s(this,Yg))}getStatistics(){var A,t;return!s(this,ht).resolved&&!((A=s(this,GA))!=null&&A.statistics)?null:D(D({},s(this,ht).resolved),(t=s(this,GA))==null?void 0:t.statistics)}unload(){var A;s(this,IA).info("Unloading EncryptedMediaExtensions"),s(this,Qi).off("received drm data",s(this,Kg)),(A=s(this,jt))==null||A.removeEventListener("encrypted",s(this,Yg)),s(this,we).forEach((t,e)=>{e.close()}),s(this,we).clear(),E(this,De,void 0),E(this,GA,void 0)}set headers(A){s(this,Gt).headers=A,s(this,GA)&&(s(this,GA).headers=A)}set queryParams(A){s(this,Gt).queryParams=A,s(this,GA)&&(s(this,GA).queryParams=A)}onChannelSwitch(){if(!s(this,ht).resolved){s(this,IA).debug("DRM is not used, skipping channel switch handling");return}Tr()&&s(this,mC).platform.safariVersion<18&&d(this,DA,SB).call(this,{message:"DRM channel switch not supported on Safari < 18",isFatal:!0}),window.clearTimeout(s(this,gI));const A=s(this,ht).resolved;E(this,ht,new $),E(this,gI,window.setTimeout(()=>{s(this,ht).resolve(A)},Rc))}}IA=new WeakMap,Qi=new WeakMap,jt=new WeakMap,ht=new WeakMap,Gt=new WeakMap,GA=new WeakMap,we=new WeakMap,De=new WeakMap,mC=new WeakMap,gI=new WeakMap,Kg=new WeakMap,Yg=new WeakMap,DA=new WeakSet,xE=function(A){return r(this,null,function*(){try{yield d(this,DA,WE).call(this),s(this,IA).debug("Media keys initialization completed"),yield d(this,DA,OE).call(this,A.initData,A.initDataType)}catch(t){d(this,DA,SB).call(this,{message:"Failed to handle encrypted event",isFatal:!0,error:t})}})},WE=function(){return r(this,null,function*(){var t;s(this,IA).debug("Initializing media keys");const A=yield s(this,ht).promise;if((t=s(this,jt))!=null&&t.mediaKeys){s(this,IA).debug("Media keys already set on media element");return}if(s(this,De)){s(this,IA).debug("Media keys initialization already in progress, waiting for completion"),yield s(this,De);return}E(this,De,r(this,null,function*(){const e=yield s(this,fC).call(this,A);s(this,IA).debug("CDM obtained",{cdm:e}),lA(s(this,jt),"No media element found"),lA(e,"No CDM found");const g=yield e.getMediaKeys();e.certificate&&(yield d(this,DA,ZE).call(this,g,e.certificate)),s(this,IA).debug("Setting media keys on media element"),yield s(this,jt).setMediaKeys(g),E(this,GA,e)})),yield s(this,De)})},OE=function(A,t){return r(this,null,function*(){lA(s(this,GA),"No CDM manager found");const e=yield s(this,GA).getMediaKeys();if(!A||!d(this,DA,VE).call(this,A)){s(this,IA).debug("Duplicate initData, no need to create new session",{initData:A});return}const g=e.createSession();s(this,IA).debug("Creating new session",{session:g}),g.addEventListener("keystatuseschange",s(this,yC)),g.closed.then(B=>{s(this,IA).info("Session is closed",{reason:B})}),g.addEventListener("message",s(this,SC)),s(this,we).set(g,A),s(this,IA).debug("Generating request for session",{session:g,initDataType:t,initData:A}),yield g.generateRequest(t,A)})},VE=function(A){for(const[t,e]of s(this,we))if(Dc(A,e))return!1;return!0},SC=new WeakMap,yC=new WeakMap,ZE=function(A,t){return r(this,null,function*(){try{s(this,IA).debug("Setting server certificate",{certificate:t}),(yield A.setServerCertificate(t))||s(this,IA).warn("Server certificates are not supported by the CDM.")}catch(e){s(this,IA).error("Failed to set server certificate",{error:e})}})},SB=function(A){const{message:t,isFatal:e,error:g}=A;s(this,IA).error(t,{error:g}),s(this,Qi).emit("error",Zn(t,e,g))},fC=new WeakMap,XE=function(A){const t=[];return A.clearkeys&&t.push("clearkey"),A.playreadyLicenseUrl&&t.push("playready"),A.widevineLicenseUrl&&t.push("widevine"),A.fairplayLicenseUrl&&A.fairplayCertificate&&t.push("fairplay"),t},jE=function(A){return{fairplay:A.fairplayLicenseUrl,playready:A.playreadyLicenseUrl,widevine:A.widevineLicenseUrl,clearkey:void 0}};const Uc=7,Nc=8,bc=i=>{const A=i.getUint32(0,!1),t=i.getUint8(0)<<16|i.getUint16(1,!1);let e=0;return t===1?e+=3:A===1&&(e+=4),e},Lc=i=>bc(new DataView(i,0))!==0,Aa=(i,A=0)=>{for(let t=A;t<i.byteLength-4;t++){const e=i.getUint32(t)===1,g=(i.getUint8(t)<<16|i.getUint16(t+1))===1;if(e||g)return{position:t,nalPrefixSize:e?4:3}}},Jc=i=>i&31,Mc=(i,A)=>{const t=new DataView(i,0);let e=Aa(t);for(;e;){const{position:g,nalPrefixSize:B}=e,C=Aa(t,g+4),Q=C?C.position-g-B:void 0;if(!A(new DataView(i,g+B,Q),B))return;e=C}},ta=i=>{const A=[],t=[];if(!Lc(i)){const e=new DataView(i,0),g=e.getUint8(5)&31;let B=6;for(let Q=0;Q<g;Q++){const o=e.getUint16(B);A.push(i.slice(B+2,B+2+o)),B+=o+2}const C=e.getUint8(B);B+=1;for(let Q=0;Q<C;Q++){const o=e.getUint16(B);t.push(i.slice(B+2,B+2+o)),B+=o+2}return{sequenceParameterSets:A,pictureParameterSets:t}}return Mc(i,e=>{const g=e.byteOffset+e.byteLength;switch(Jc(e.getUint8(0))){case Nc:t.push(e.buffer.slice(e.byteOffset,g));break;case Uc:A.push(e.buffer.slice(e.byteOffset,g));break}return!0}),{sequenceParameterSets:A,pictureParameterSets:t}},Hc=i=>{var y;const A=new DataView(i),t=A.getUint8(1),e=A.getUint8(2),g=A.getUint8(3),B=new VA(i,32);B.readUnsignedExpGolomb();let C=1;switch(t){case 100:case 110:case 122:case 244:case 44:case 83:case 86:case 118:case 128:case 138:case 144:{if(C=B.readUnsignedExpGolomb(),C===3&&B.readBits(1),B.readUnsignedExpGolomb()+8,B.readUnsignedExpGolomb()+8,B.readBit(),B.readBit()){for(let k=0;k<(C!=3?8:12);k++)if(B.readBit()){const U=k<6?16:64;let H=0,T=8,z=8;for(let Y=0;Y<U;Y++)z!=0&&(H=B.readSignedExpGolomb(),z=(T+H+256)%256),T=z==0?T:z}}break}}B.readUnsignedExpGolomb();const Q=B.readUnsignedExpGolomb();if(Q==0)B.readUnsignedExpGolomb();else if(Q==1)throw new Error("Unhandled case");B.readUnsignedExpGolomb(),B.readBit();const o=B.readUnsignedExpGolomb(),a=B.readUnsignedExpGolomb(),c=B.readBit();c===0&&B.readBit(),B.readBit();let h=o+1,l=a+1;if(l*=2-c,l*=16,h*=16,B.readBit()){const f=C==1?1:0,q=1<<(C==1||C==2?1:0),U=2-c<<f,H=B.readUnsignedExpGolomb()*q,T=B.readUnsignedExpGolomb()*q,z=B.readUnsignedExpGolomb()*U,Y=B.readUnsignedExpGolomb()*U;h-=H+T,l-=z+Y}let m={numerator:1,denumerator:1};return B.readBit()&&B.readBit()&&(m=(y=qc[B.readBits(8)])!=null?y:{numerator:0,denumerator:0}),{width:h,height:l,pixelAspectRatio:m,profileIdc:t,constraintFlags:e,levelIdc:g}},qc=[{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}],vc=184549376;function Kc(i){const A=new SA(i),t=Yc(A);(t.flags&vc)!==0&&Tc(A);const e=Pc(A);if(String.fromCharCode(...e.frameId)==="TXXX"){const B=new SA(A.readBytes(e.size));return{header:t,txx:xc(B)}}}function Yc(i){const A=i.readBytes(3),t=i.readUint8(),e=i.readUint8(),g=i.readUint8(),B=i.readUint32();return{id:A,majorVersion:t,minorVersion:e,flags:g,size:B}}function Tc(i){const A=i.readUint32();return i.readBytes(A-4),{}}function Pc(i){const A=i.readBytes(4),t=i.readUint32(),e=i.readUint16();return{frameId:A,size:t,flags:e}}function xc(i){const A=i.readUint8(),t=i.readUtf8String(),e=i.readUtf8String();return{encoding:A,description:t,value:e}}function ea(i){let A=i.readUint32();const t=[i.readUint8(),i.readUint8(),i.readUint8(),i.readUint8()],e=String.fromCharCode.apply(null,t);return A===1&&(A=i.readUint64()-8),{size:A-8,type:e}}function Wc(i,A){const t=ea(A),e=new SA(A.readBytes(t.size));if(t.type!==i.type)throw new Error(`invalid error type: ${t.type}, expected ${i.type}`);const g=i.decodeData(e);return e.readRemaining(),g}function Ot(i){const A=i.readUint8(),t=i.readUint24();return{version:A,flags:t}}const sI=class sI{constructor({timescale:A,presentationTime:t,presentationTimeDelta:e,schemeIdUri:g,value:B,eventDuration:C,id:Q,data:o}){I(this,"type",sI.type);I(this,"timescale");I(this,"presentationTime");I(this,"presentationTimeDelta");I(this,"schemeIdUri");I(this,"value");I(this,"eventDuration");I(this,"id");I(this,"data");this.timescale=A,this.presentationTime=t,this.presentationTimeDelta=e,this.schemeIdUri=g,this.value=B,this.eventDuration=C,this.id=Q,this.data=o}static decodeData(A){const{version:t}=Ot(A);switch(t){case 1:{const e=A.readUint32(),g=A.readUint64(),B=A.readUint32(),C=A.readUint32(),Q=A.readUtf8String(),o=A.readUtf8String(),a=A.remaining(),c=A.readBytes(a);return new sI({timescale:e,presentationTime:g,eventDuration:B,id:C,schemeIdUri:Q,value:o,data:c})}case 0:{const e=A.readUtf8String(),g=A.readUtf8String(),B=A.readUint32(),C=A.readUint32(),Q=A.readUint32(),o=A.readUint32(),a=A.remaining(),c=A.readBytes(a);return new sI({timescale:B,presentationTimeDelta:C,schemeIdUri:e,value:g,eventDuration:Q,id:o,data:c})}default:throw new Error(`unsupported version ${t}`)}}};I(sI,"type","emsg");let bB=sI;const Tg=class Tg{constructor(A){I(this,"type",Tg.type);I(this,"data");this.data=A}static decodeData(A){const t=A.readRemaining();return new Tg(t)}};I(Tg,"type","mdat");let LB=Tg;const Pg=class Pg{constructor(A,t,e){I(this,"type",Pg.type);I(this,"extra");I(this,"byteOffset");I(this,"baseMediaDecodeTime");this.extra=A,this.byteOffset=t,this.baseMediaDecodeTime=e}static decodeData(A){const t=Ot(A),e=A.byteOffset();let g=0;return t.version===1?g=A.readUint64():g=A.readUint32(),new Pg(t,e,g)}};I(Pg,"type","tfdt");let JB=Pg;const Oc=1,Vc=2,Zc=8,Xc=16,jc=32,xg=class xg{constructor(A,t,e,g){I(this,"type",xg.type);I(this,"extra");I(this,"defaultSampleDuration");I(this,"defaultSampleSize");I(this,"defaultSampleFlags");this.extra=A,this.defaultSampleDuration=t,this.defaultSampleSize=e,this.defaultSampleFlags=g}static decodeData(A){const t=Ot(A);let e,g,B;return A.readUint32(),(t.flags&Oc)>0&&A.readUint64(),(t.flags&Vc)>0&&A.readUint32(),(t.flags&Zc)>0&&(e=A.readUint32()),(t.flags&Xc)>0&&(g=A.readUint32()),(t.flags&jc)>0&&(B=A.readUint32()),new xg(t,e,g,B)}};I(xg,"type","tfhd");let MB=xg;const cA=class cA{constructor(A,t,e){I(this,"type",cA.type);I(this,"dataOffset");I(this,"firstSampleFlags");I(this,"samplesCount");I(this,"sampleDurations",[]);I(this,"sampleSizes",[]);I(this,"sampleFlags",[]);I(this,"sampleCts",[]);this.dataOffset=t,this.firstSampleFlags=e,this.samplesCount=A}is_sync_sample(A){const t=cA.FLAG_SAMPLE_FLAG_IS_NON_SYNC|cA.FLAG_SAMPLE_DEPENDS_YES,e=this.sampleFlags[A];if(typeof e!="undefined")return(e&t)===0;if(A===0&&this.firstSampleFlags)return(this.firstSampleFlags&t)===0}static decodeData(A){const{flags:t}=Ot(A),e=A.readUint32();let g,B;t&cA.TRUN_DATA_OFFSET&&(g=A.readUint32()),t&cA.TRUN_FIRST_SAMPLE_FLAGS&&(B=A.readUint32());const C=new cA(e,g,B);for(let Q=0;Q<e;Q++)t&cA.SAMPLE_DURATION&&C.sampleDurations.push(A.readUint32()),t&cA.SAMPLE_SIZE&&C.sampleSizes.push(A.readUint32()),t&cA.SAMPLE_FLAGS&&C.sampleFlags.push(A.readUint32()),t&cA.SAMPLE_CTS&&C.sampleCts.push(A.readUint32());return C}};I(cA,"TRUN_DATA_OFFSET",1),I(cA,"TRUN_FIRST_SAMPLE_FLAGS",4),I(cA,"SAMPLE_DURATION",256),I(cA,"SAMPLE_SIZE",512),I(cA,"SAMPLE_FLAGS",1024),I(cA,"SAMPLE_CTS",2048),I(cA,"FLAG_SAMPLE_FLAG_IS_NON_SYNC",65536),I(cA,"FLAG_SAMPLE_DEPENDS_NO",33554432),I(cA,"FLAG_SAMPLE_DEPENDS_YES",16777216),I(cA,"type","trun");let fg=cA;const Wg=class Wg{constructor(A,t,e){I(this,"type",Wg.type);I(this,"tfhd");I(this,"tfdt");I(this,"trun");this.tfhd=A,this.tfdt=t,this.trun=e}static decodeData(A){let t,e,g;for(;A.remaining()>0;){const B=at(A);B instanceof MB&&(t=B),B instanceof JB&&(e=B),B instanceof fg&&(g=B)}return new Wg(t,e,g)}};I(Wg,"type","traf");let HB=Wg;const Og=class Og{constructor(A){I(this,"type",Og.type);I(this,"traf");this.traf=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=at(A);e instanceof HB&&(t=e)}if(!t)throw new Error("No traf found");return new Og(t)}};I(Og,"type","moof");let qB=Og;const Vg=class Vg{constructor(){I(this,"type",Vg.type)}static decodeData(A){return new Vg}};I(Vg,"type","mvhd");let vB=Vg;const Zg=class Zg{constructor(A){I(this,"type",Zg.type);I(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){Ot(A),A.readUint32();const t=String.fromCharCode(...A.readBytes(4));return new Zg(t)}};I(Zg,"type","hdlr");let KB=Zg;const BI=class BI{constructor(A,t,e,g){I(this,"type",BI.type);I(this,"creationTime");I(this,"modificationTime");I(this,"timescale");I(this,"duration");this.creationTime=A,this.modificationTime=t,this.timescale=e,this.duration=g}static decodeData(A){const{version:t}=Ot(A);if(t===1){const Q=A.readUint64(),o=A.readUint64(),a=A.readUint32(),c=A.readUint64();return new BI(Q,o,a,c)}const e=A.readUint32(),g=A.readUint32(),B=A.readUint32(),C=A.readUint32();return new BI(e,g,B,C)}};I(BI,"type","mdhd");let YB=BI;const Xg=class Xg{constructor(A,t,e,g){I(this,"type",Xg.type);I(this,"av01");I(this,"avc1");I(this,"opus");I(this,"codec");this.avc1=A,this.av01=t,this.opus=e,this.codec=g}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){Ot(A);const t=A.readUint32();let e,g,B,C;for(let Q=0;Q<t;Q++)for(;A.remaining()>0;){const o=at(A);switch(o.type){case"avc1":e="h264",g=o;break;case"av01":e="av1",C=o;break;case"mp4a":e="aac";break;case"Opus":e="opus",B=o;break}}return new Xg(g,C,B,e)}};I(Xg,"type","stsd");let TB=Xg;const jg=class jg{constructor(A){I(this,"type",jg.type);I(this,"stsd");this.stsd=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=at(A);e instanceof TB&&(t=e)}if(!t)throw new Error("No stsd found");return new jg(t)}};I(jg,"type","stbl");let PB=jg;const zg=class zg{constructor(A){I(this,"type",zg.type);I(this,"stbl");this.stbl=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=at(A);e instanceof PB&&(t=e)}if(!t)throw new Error("No stbl found");return new zg(t)}};I(zg,"type","minf");let xB=zg;const _g=class _g{constructor(A,t,e){I(this,"type",_g.type);I(this,"hdlr");I(this,"minf");I(this,"mdhd");this.hdlr=A,this.minf=t,this.mdhd=e}static decodeData(A){let t,e,g;for(;A.remaining()>0;){const B=at(A);B instanceof KB&&(t=B),B instanceof xB&&(e=B),B instanceof YB&&(g=B)}if(!t)throw new Error("No hdlr found");if(!e)throw new Error("No minf found");if(!g)throw new Error("No mdhd found");return new _g(t,e,g)}};I(_g,"type","mdia");let WB=_g;const $g=class $g{constructor(A,t,e,g,B,C,Q,o){I(this,"type",$g.type);I(this,"modificationTime");I(this,"creationTime");I(this,"trackId");I(this,"duration");I(this,"alternateGroup");I(this,"volume");I(this,"width");I(this,"height");this.modificationTime=A,this.creationTime=t,this.trackId=e,this.duration=g,this.alternateGroup=B,this.volume=C,this.width=Q,this.height=o}static decodeData(A){const t=Ot(A);let e=0,g=0;t.version===1?(e=A.readUint64(),g=A.readUint64()):(e=A.readUint32(),g=A.readUint32());const B=A.readUint32();A.readUint32();const C=A.readUint32();A.readUint32(),A.readUint32(),A.readUint16();const Q=A.readUint16(),o=A.readUint16();A.readUint16(),new Array(9).fill(0).map(()=>A.readUint32());const a=A.readUint16();A.readUint16();const c=A.readUint16();return A.readUint16(),new $g(e,g,B,C,Q,o,a,c)}};I($g,"type","tkhd");let OB=$g;const As=class As{constructor(A,t){I(this,"type",As.type);I(this,"tkhd");I(this,"mdia");this.tkhd=A,this.mdia=t}static decodeData(A){let t,e;for(;A.remaining()>0;){const g=at(A);g instanceof OB&&(t=g),g instanceof WB&&(e=g)}if(!t)throw new Error("No tkhd found");if(!e)throw new Error("No mdia found");return new As(t,e)}};I(As,"type","trak");let VB=As;const ts=class ts{constructor(A,t){I(this,"type",ts.type);I(this,"mvhd");I(this,"traks");this.mvhd=A,this.traks=t}static decodeData(A){let t;const e=[];for(;A.remaining()>0;){const g=at(A);g instanceof VB&&e.push(g),g instanceof vB&&(t=g)}if(!t)throw new Error("No mvhd found");return new ts(t,e)}};I(ts,"type","moov");let ZB=ts;const es=class es{constructor(A,t,e,g,B,C,Q,o){I(this,"type",es.type);I(this,"configurationVersion");I(this,"avcProfileIndication");I(this,"profileCompatibility");I(this,"avcLevelIndication");I(this,"lengthSizeMinusOne");I(this,"sequenceParameterSets");I(this,"pictureParameterSets");I(this,"bytes");this.configurationVersion=A,this.avcProfileIndication=t,this.profileCompatibility=e,this.avcLevelIndication=g,this.lengthSizeMinusOne=B,this.sequenceParameterSets=C,this.pictureParameterSets=Q,this.bytes=o}static decodeData(A){const t=A.buffer(),e=A.readUint8(),g=A.readUint8(),B=A.readUint8(),C=A.readUint8(),Q=A.readUint8()&3,o=A.readUint8()&31,a=[];for(let l=0;l<o;l++){const m=A.readBytes(A.readUint16());a.push(m)}const c=A.readUint8(),h=[];for(let l=0;l<c;l++){const m=A.readBytes(A.readUint16());h.push(m)}return new es(e,g,B,C,Q,a,h,t)}};I(es,"type","avcC");let bQ=es;const is=class is{constructor(A,t,e,g,B){I(this,"type",is.type);I(this,"avcC");I(this,"width");I(this,"height");I(this,"horizontalResolution");I(this,"verticalResolution");this.avcC=A,this.width=t,this.height=e,this.horizontalResolution=g,this.verticalResolution=B}static decodeData(A){A.readUint32(),A.readUint16(),A.readUint16(),A.readUint32(),A.readUint64(),A.readUint32();const t=A.readUint16(),e=A.readUint16(),g=A.readUint32(),B=A.readUint32();A.readUint32(),A.readUint16(),A.readBytes(32),A.readUint16(),A.readUint16();let C;for(;A.remaining()>0;){const Q=at(A);switch(Q.type){case"avcC":C=Q;break}}if(!C)throw new Error("no avcC");return new is(C,t,e,g,B)}};I(is,"type","avc1");let LQ=is;const Is=class Is{constructor(){I(this,"type",Is.type)}static decodeData(A){return new Is}};I(Is,"type","dOps");let JQ=Is;const gs=class gs{constructor(A,t,e){I(this,"type",gs.type);I(this,"dops");I(this,"channelCount");I(this,"sampleRate");this.dops=A,this.channelCount=t,this.sampleRate=e}static decodeData(A){A.readUint32(),A.readUint16(),A.readUint16();const t=A.readUint16();A.readUint16(),A.readUint32();const e=A.readUint16();A.readUint16(),A.readUint32();const g=A.readUint16();A.readUint16(),t===1&&(A.readUint64(),A.readUint64());const B=Wc(JQ,A);return new gs(B,e,g)}};I(gs,"type","Opus");let MQ=gs;const CI=class CI{constructor(A,t){I(this,"type",CI.type);I(this,"ntpTimestamp");I(this,"mediaTime");this.ntpTimestamp=A,this.mediaTime=t}date(){const[A,t]=this.ntpTimestamp,e=A*1e3+t/2**32*1e3,g=new Date(Date.UTC(1900,0,1,0,0,0));return new Date(g.getTime()+e)}static decodeData(A){const{version:t}=Ot(A);A.readUint32();const e=A.readUint32(),g=A.readUint32();if(t===1){const C=A.readUint64();return new CI([e,g],C)}const B=A.readUint32();return new CI([e,g],B)}};I(CI,"type","prft");let XB=CI;class zc{constructor(A,t){n(this,ss);n(this,Bs);E(this,ss,A),E(this,Bs,t.readBytes(A.size))}data(){return s(this,Bs)}get type(){return s(this,ss).type}}ss=new WeakMap,Bs=new WeakMap;const _c={moov:ZB,trak:VB,tkhd:OB,mvhd:vB,moof:qB,traf:HB,tfhd:MB,tfdt:JB,trun:fg,mdat:LB,mdia:WB,hdlr:KB,minf:xB,stbl:PB,mdhd:YB,stsd:TB,prft:XB,avc1:LQ,avcC:bQ,Opus:MQ,emsg:bB};function at(i){const A=ea(i),t=_c[A.type],e=new SA(i.readBytes(A.size));if(!t){const B=new zc(A,e);return e.readRemaining(),B}const g=t.decodeData(e);return e.readRemaining(),g}function $c(i){if(i.byteLength<8)throw new Error("Buffer too small");const A=new SA(i),t=new Map;for(;A.remaining()>0;){const B=at(A);t.set(B.type,B)}const e=t.get("ftyp"),g=t.get("moov");if(!e)throw new Error("ftyp atom not found");if(!g||!(g instanceof ZB))throw new Error("moov atom not found");return{ftyp:e,moov:g}}function Ah(i){if(i.byteLength<8)throw new Error("Buffer too small");const A=new SA(i),t=new Map,e=[];for(;A.remaining()>0;){const Q=at(A);Q instanceof bB&&e.push(Q),t.set(Q.type,Q)}const g=t.get("moof"),B=t.get("mdat"),C=t.get("prft");if(!g||!(g instanceof qB))throw new Error("moof atom not found");if(!B||!(B instanceof LB))throw new Error("mdat atom not found");if(C&&!(C instanceof XB))throw new Error("invalid prft found");return{moof:g,mdat:B,prft:C,emsgs:e}}class th{constructor(A){n(this,Cs);n(this,Qs);E(this,Cs,A),E(this,Qs,$c(A))}rawBytes(){return s(this,Cs)}init(){return s(this,Qs)}}Cs=new WeakMap,Qs=new WeakMap;const Wo=class Wo{constructor(A,t){n(this,YA);n(this,XA);n(this,CA);E(this,YA,t),E(this,XA,A),E(this,CA,Ah(t))}clone(){return new Wo(s(this,XA),new Uint8Array(s(this,YA).buffer.slice(s(this,YA).byteOffset,s(this,YA).byteOffset+s(this,YA).byteLength)))}updateBaseMediaDecodeTime(A){const t=new DataView(s(this,YA).buffer,s(this,YA).byteOffset,s(this,YA).byteLength);if(s(this,CA).moof.traf.tfdt)if(s(this,CA).moof.traf.tfdt.baseMediaDecodeTime=A,s(this,CA).moof.traf.tfdt.extra.version===1){const e=Math.floor(A/4294967296),g=(A&4294967295)>>>0;t.setUint32(s(this,CA).moof.traf.tfdt.byteOffset-s(this,YA).byteOffset,e),t.setUint32(s(this,CA).moof.traf.tfdt.byteOffset-s(this,YA).byteOffset+4,g)}else t.setUint32(s(this,CA).moof.traf.tfdt.byteOffset-s(this,YA).byteOffset,A)}producerReferenceTime(){if(s(this,CA).prft)return s(this,CA).prft.date()}duration(){const A=s(this,CA).moof.traf.trun,t=s(this,CA).moof.traf.tfhd;if((A==null?void 0:A.sampleDurations.length)===0){const e=(A==null?void 0:A.samplesCount)||1;if(t!=null&&t.defaultSampleDuration)return(t==null?void 0:t.defaultSampleDuration)*e}return(A==null?void 0:A.sampleDurations.reduce((e,g)=>e+g,0))||0}baseMediaDecodeTime(){var t;const A=(t=s(this,CA).moof.traf.tfdt)==null?void 0:t.baseMediaDecodeTime;if(!A)throw new Error("no baseMediaDecodeTime");return A}startsWithKeyframe(){var e;const A=s(this,CA).moof.traf.trun,t=(A==null?void 0:A.firstSampleFlags)||(A==null?void 0:A.sampleFlags[0])||((e=s(this,CA).moof.traf.tfhd)==null?void 0:e.defaultSampleFlags);return t?(t&fg.FLAG_SAMPLE_DEPENDS_NO)!==0:!1}compositionTimeOffset(A){var t;return(t=s(this,CA).moof.traf.trun)==null?void 0:t.sampleCts[A]}timescale(){const A=s(this,XA).init().moov.traks[0];if(!A)throw new Error("no tracks");return A.mdia.mdhd.timescale}mediaType(){var t;const A=(t=s(this,XA).init().moov.traks[0])==null?void 0:t.mdia.hdlr.mediaType();if(!A)throw new Error("no media type");return A}header(){return s(this,XA)}fragment(){return s(this,CA)}samplesCount(){var A;return((A=s(this,CA).moof.traf.trun)==null?void 0:A.samplesCount)||0}sample(A){var y,f,k,q,U,H,T,z,Y,FA,nA,mA,tt,JA,w;const t=(y=s(this,XA).init().moov.traks[0])==null?void 0:y.mdia.minf.stbl.stsd.codec,e=((f=s(this,CA).moof.traf.trun)==null?void 0:f.samplesCount)||0,g=(k=s(this,CA).moof.traf.tfdt)==null?void 0:k.baseMediaDecodeTime;if(A>=e||typeof g=="undefined"||!t)return;const B=this.compositionTimeOffset(A),C=((q=s(this,CA).moof.traf.trun)==null?void 0:q.sampleDurations[A])||0,Q=((U=s(this,CA).moof.traf.trun)==null?void 0:U.sampleDurations.slice(0,A).reduce((G,AA)=>G+AA,0))||0,o=g+Q,a=((H=s(this,XA).init().moov.traks[0])==null?void 0:H.mdia.mdhd.timescale)||1e3,c=((T=s(this,CA).moof.traf.trun)==null?void 0:T.sampleSizes[A])||s(this,CA).mdat.data.byteLength,h=((z=s(this,CA).moof.traf.trun)==null?void 0:z.sampleSizes.slice(0,A).reduce((G,AA)=>G+AA,0))||0,l=s(this,CA).mdat.data.subarray(h,h+c),m=((Y=s(this,CA).moof.traf.trun)==null?void 0:Y.is_sync_sample(A))||!1;if(this.mediaType()==="video"){const G=((FA=s(this,XA).init().moov.traks[0])==null?void 0:FA.tkhd.width)||0,AA=((nA=s(this,XA).init().moov.traks[0])==null?void 0:nA.tkhd.height)||0;return{type:"video",codec:t,width:G,height:AA,duration:C,isSync:m,timescale:a,timestamp:o,compositionTimeOffset:B,data:l}}return{type:"audio",codec:t,channels:((tt=(mA=s(this,XA).init().moov.traks[0])==null?void 0:mA.mdia.minf.stbl.stsd.opus)==null?void 0:tt.channelCount)||0,sampleRate:((w=(JA=s(this,XA).init().moov.traks[0])==null?void 0:JA.mdia.minf.stbl.stsd.opus)==null?void 0:w.sampleRate)||0,duration:C,isSync:m,timestamp:o,compositionTimeOffset:B,data:l,timescale:a}}rawBytes(){return s(this,YA)}};YA=new WeakMap,XA=new WeakMap,CA=new WeakMap;let HQ=Wo;class ia{constructor(A){n(this,QI);E(this,QI,new th(A))}header(){return s(this,QI)}createFragment(A){return new HQ(s(this,QI),A)}}QI=new WeakMap;function M(i){const A=new ArrayBuffer(i.length),t=new Uint8Array(A);for(let e=0,g=i.length;e<g;e++)t[e]=i.charCodeAt(e);return new Uint8Array(A)}const gA={ftyp:M("ftyp"),mvhd:M("mvhd"),moov:M("moov"),trak:M("trak"),tkhd:M("tkhd"),mdia:M("mdia"),mdhd:M("mdhd"),hdlr:M("hdlr"),minf:M("minf"),vmhd:M("vmhd"),smhd:M("smhd"),dinf:M("dinf"),dref:M("dref"),stbl:M("stbl"),stsd:M("stsd"),avc1:M("avc1"),av01:M("av01"),av1C:M("av1C"),avcC:M("avcC"),esds:M("esds"),colr:M("colr"),nclx:M("nclx"),mvex:M("mvex"),trex:M("trex"),udta:M("udta"),meta:M("meta"),ilst:M("ilst"),moof:M("moof"),mfhd:M("mfhd"),traf:M("traf"),tfhd:M("tfhd"),tfdt:M("tfdt"),trun:M("trun"),mdat:M("mdat"),mp4a:M("mp4a"),Opus:M("Opus"),prft:M("prft"),dOps:M("dOps"),emsg:M("emsg")},eh=1e3,pg=M("iso6"),Ia=new Uint8Array([0,0,2,0]),ih=[pg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([97,118,99,49]),new Uint8Array([109,112,52,49])],Ih=[pg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([97,118,48,49]),new Uint8Array([109,112,52,49])],gh=[pg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([109,112,52,49])];class ga{constructor(){I(this,"writer",new mg);I(this,"moofOffset",0)}}const uA=(i,A,t)=>{i.writer.writeUint32(t+8),i.writer.writeBytes(A)},yA=(i,A,t,e,g)=>{uA(i,A,t+4),i.writer.writeUint8(e),i.writer.writeUint24(g)},qQ=(i,A)=>{uA(i,gA.ftyp,pg.byteLength+Ia.byteLength+A.reduce((t,e)=>t+e.byteLength,0)),i.writer.writeBytes(pg),i.writer.writeBytes(Ia),A.forEach(t=>i.writer.writeBytes(t))},sh=2**32,Bh=2208988800,Ch=(i,A,t,e)=>{yA(i,gA.prft,20,1,0);const B=t/1e3,C=Math.floor(B),o=(B-C)*1e3*1e3*sh/1e6;i.writer.writeUint32(A),i.writer.writeUint32(C+Bh),i.writer.writeUint32(o),i.writer.writeUint64(e)},Qh=(i,A,t)=>{yA(i,gA.mvhd,96,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(t),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)},sa=i=>"sequenceParameterSets"in i,vQ=i=>"sequenceHeader"in i,_e=i=>i.type=="video",Fg=i=>i.type=="audio",oh=(i,A,t)=>{const e=i.writer.position();yA(i,gA.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*t/A.timescale),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint16(0),i.writer.writeUint16(Fg(A)?1:0),i.writer.writeUint16(Fg(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])),_e(A)?(i.writer.writeUint32(A.width*65536),i.writer.writeUint32(A.height*65536)):Fg(A)&&(i.writer.writeUint32(0),i.writer.writeUint32(0)),i.writer.writeUint32At(e,i.writer.position()-e)},nh=(i,A)=>{yA(i,gA.mdhd,20,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(A.timescale),i.writer.writeUint32(A.duration);const t=A.lang||"und",e=(t.charCodeAt(0)&31)<<10|(t.charCodeAt(1)&31)<<5|t.charCodeAt(2)&31;i.writer.writeUint16(e),i.writer.writeUint16(0)},ah=(i,A)=>{const t=i.writer.position();yA(i,gA.hdlr,0,0,0),i.writer.writeUint32(0),i.writer.writeBytes(M(_e(A)?"vide":"soun")),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeBytes(M(_e(A)?"VideoHandler\0":"SoundHandler\0")),i.writer.writeUint32At(t,i.writer.position()-t)},Eh=i=>{const A=i.writer.position();uA(i,gA.dinf,0),yA(i,gA.dref,16,0,0),i.writer.writeUint32(1),yA(i,M("url "),0,0,1),i.writer.writeUint32At(A,i.writer.position()-A)},rh=(i,A)=>{const t=i.writer.position();uA(i,gA.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(e=>{i.writer.writeUint16(e.byteLength),i.writer.writeBytes(e)}),i.writer.writeUint8(A.pictureParameterSets.length),A.pictureParameterSets.forEach(e=>{i.writer.writeUint16(e.byteLength),i.writer.writeBytes(e)}),i.writer.writeUint32At(t,i.writer.position()-t)},ch=(i,A)=>{var Q,o;const t=i.writer.position();uA(i,gA.av1C,0);const{seqProfile:e,operatingPoints:g,colorConfig:B}=A.parsedSequenceHeader,C=g[0];i.writer.writeUint8(129),i.writer.writeUint8(e<<5|((Q=C==null?void 0:C.seqLevelIdx)!=null?Q:0)),i.writer.writeUint8(((o=C==null?void 0:C.tier)!=null?o:0)|(B.highBitDepth?1:0)|(B.bitDepth===12?1:0)<<5|(B.monoChrome?1:0)<<4|B.subsamplingX<<3|B.subsamplingY<<2|B.chromaSamplePosition&65535),i.writer.writeUint8(0),i.writer.writeBytes(A.sequenceHeader),i.writer.writeUint32At(t,i.writer.position()-t)},hh=(i,A)=>{const t=i.writer.position(),e=vQ(A)?gA.av01:gA.avc1;uA(i,e,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),sa(A)?rh(i,A):vQ(A)&&(ch(i,A),A.parsedSequenceHeader.colorConfig&&(uA(i,M("colr"),11),i.writer.writeBytes(gA.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,M("pasp"),8),i.writer.writeUint32(A.pixelAspectRatio.numerator),i.writer.writeUint32(A.pixelAspectRatio.denumerator)),A.bitrate&&(uA(i,M("btrt"),12),i.writer.writeUint32(0),i.writer.writeUint32(A.bitrate),i.writer.writeUint32(A.bitrate)),i.writer.writeUint32At(t,i.writer.position()-t)},jB=(i,A,t)=>{let e=3;for(i.writer.writeUint8(A);e>0;e--)i.writer.writeUint8(t>>7*e|128);i.writer.writeUint8(t&127)},dh=(i,A)=>{const t=A.decoderConfig.byteLength>0?A.decoderConfig.byteLength+5:0,e=i.writer.position();yA(i,gA.esds,0,0,0),jB(i,3,21+t+5+1),i.writer.writeUint16(A.trackId),i.writer.writeUint8(0),jB(i,4,13+t);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&&(jB(i,5,A.decoderConfig.byteLength),i.writer.writeBytes(A.decoderConfig)),jB(i,6,1),i.writer.writeUint8(2),i.writer.writeUint32At(e,i.writer.position()-e)},lh=i=>{switch(i){case"aac":case"mp3":return"mp4a";case"opus":return"Opus"}},uh=(i,A)=>{const t=i.writer.position();uA(i,M("dOps"),0),i.writer.writeUint8(0);const e=A.decoderConfig,g=new DataView(e.buffer,e.byteOffset,e.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(t,i.writer.position()-t)},wh=(i,A)=>{const t=i.writer.position();switch(uA(i,M(lh(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":dh(i,A);break;case"opus":uh(i,A);break}A.bitrate&&(uA(i,M("btrt"),12),i.writer.writeUint32(0),i.writer.writeUint32(A.bitrate),i.writer.writeUint32(A.bitrate)),i.writer.writeUint32At(t,i.writer.position()-t)},Dh=(i,A)=>{const t=i.writer.position();uA(i,gA.stbl,0);const e=i.writer.position();yA(i,gA.stsd,0,0,0),i.writer.writeUint32(1),_e(A)?hh(i,A):Fg(A)&&wh(i,A),i.writer.writeUint32At(e,i.writer.position()-e),yA(i,M("stts"),4,0,0),i.writer.writeUint32(0),yA(i,M("stsc"),4,0,0),i.writer.writeUint32(0),yA(i,M("stsz"),8,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),yA(i,M("stco"),4,0,0),i.writer.writeUint32(0),i.writer.writeUint32At(t,i.writer.position()-t)},mh=(i,A)=>{const t=i.writer.position();uA(i,gA.minf,0),_e(A)?(yA(i,gA.vmhd,8,0,1),i.writer.writeUint32(0),i.writer.writeUint32(0)):Fg(A)&&(yA(i,gA.smhd,4,0,0),i.writer.writeUint16(0),i.writer.writeUint16(0)),Eh(i),Dh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Sh=(i,A)=>{const t=i.writer.position();uA(i,gA.mdia,0),nh(i,A),ah(i,A),mh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},yh=(i,A,t)=>{const e=i.writer.position();uA(i,gA.trak,0),oh(i,A,t),Sh(i,A),i.writer.writeUint32At(e,i.writer.position()-e)},fh=(i,A)=>{yA(i,gA.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)},ph=(i,A)=>{const t=i.writer.position();uA(i,gA.mvex,0),A.forEach(e=>fh(i,e)),i.writer.writeUint32At(t,i.writer.position()-t)},Fh=(i,A,t,e)=>{const g=i.writer.position();uA(i,gA.moov,0),Qh(i,0,t),A.forEach(B=>yh(i,B,t)),ph(i,A),i.writer.writeUint32At(g,i.writer.position()-g)},Gh=(i,A)=>{const t=i.writer.position();yA(i,gA.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(t,i.writer.position()-t)},kh=(i,A)=>{const t=i.writer.position();yA(i,gA.tfdt,8,1,0);const e=Math.floor(A.timestamp/4294967296),g=(A.timestamp&4294967295)>>>0;i.writer.writeUint32(e),i.writer.writeUint32(g),i.writer.writeUint32At(t,i.writer.position()-t)},Rh=(i,A)=>{if(!A.samples[0])throw new Error("At least one sample must be provided");const t=A.samples.some(o=>!!o.compositionTimeOffset),e=KQ(A.samples[0])!==A.defaultFlags,g=A.samples.length>1;let B=1;e&&(B|=4),t&&(B|=2048),g&&(B|=512,B|=256,B|=1024);const C=i.writer.position();yA(i,gA.trun,16,1,B),i.writer.writeUint32(A.samples.length);const Q=i.writer.position();i.writer.writeUint32(0),e&&i.writer.writeUint32(KQ(A.samples[0]));for(const o of A.samples)g&&(i.writer.writeUint32(o.duration),i.writer.writeUint32(o.data.byteLength),i.writer.writeUint32(KQ(o))),t&&i.writer.writeUint32(o.compositionTimeOffset||0);i.writer.writeUint32At(Q,i.writer.position()-i.moofOffset+8),i.writer.writeUint32At(C,i.writer.position()-C)},KQ=i=>i.isSync?33554432:16842752,Uh=(i,A)=>{const t=i.writer.position();uA(i,gA.traf,0),Gh(i,A),kh(i,A),Rh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Nh=(i,A)=>{yA(i,gA.mfhd,4,0,0),i.writer.writeUint32(A)},bh=(i,A)=>{const t=i.writer.position();uA(i,gA.moof,0),Nh(i,A.sequenceNumber),Uh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Lh=(i,A)=>{const t=A.samples.reduce((e,g)=>e+g.data.byteLength,0);uA(i,gA.mdat,t),A.samples.forEach(e=>i.writer.writeBytes(e.data))},zB=(i,A)=>{const t=new ga,e=i.filter(B=>_e(B)&&sa(B)).length>0;return i.filter(B=>_e(B)&&vQ(B)).length>0?qQ(t,Ih):e?qQ(t,ih):qQ(t,gh),Fh(t,i,eh),t.writer.buffer()},_B=i=>{var t;const A=new ga;return((t=i.samples[0])==null?void 0:t.producerReferenceTime)!==void 0&&Ch(A,i.trackId,i.samples[0].producerReferenceTime,i.timestamp),A.moofOffset=A.writer.position(),bh(A,i),Lh(A,i),A.writer.buffer()},Jh=(i,A)=>{const t=i.map(C=>V(D({},C),{data:new Uint8Array(C.data)}));if(!t[0])throw new Error("At least one sample must be provided");const{timestamp:e,data:g,duration:B}=t[0];return _B({trackId:1,timestamp:e,sequenceNumber:A,defaultSize:g.byteLength,defaultFlags:33554432,defaultDuration:B,samples:t})},Mh=(i,A,t,e)=>zB([{type:"audio",codec:"aac",decoderConfig:i,channelCount:A,sampleRate:t,timescale:e,duration:0,trackId:1}]),Ba=i=>{const{sequenceParameterSets:A,pictureParameterSets:t}=ta(i),e=A[0],g=t[0];if(!e||!g)throw new Error("No sps or pps provided");return Hc(e)},Hh=(i,A)=>{const t=i.map(Q=>V(D({},Q),{data:new Uint8Array(Q.data)}));if(!t[0])throw new Error("At least one sample must be provided");const{isSync:e,timestamp:g,data:B,duration:C}=t[0];return _B({trackId:1,timestamp:g,sequenceNumber:A,defaultSize:B.byteLength,defaultFlags:e?33554432:16842752,defaultDuration:C,samples:t})},qh=(i,A)=>{const{sequenceParameterSets:t,pictureParameterSets:e}=ta(i),g=Ba(i);return zB([{type:"video",sequenceParameterSets:t.map(B=>new Uint8Array(B)),pictureParameterSets:e.map(B=>new Uint8Array(B)),width:g.width,height:g.height,timescale:A,duration:0,trackId:1}])},vh=(i,A,t)=>zB([{type:"audio",trackId:1,channelCount:A,timescale:t,codec:"opus",decoderConfig:i,duration:0,sampleRate:48e3}]),Kh=(i,A)=>{const t=i.map(C=>V(D({},C),{data:new Uint8Array(C.data)}));if(!t[0])throw new Error("At least one sample must be provided");const{timestamp:e,data:g,duration:B}=t[0];return _B({trackId:1,timestamp:e,sequenceNumber:A,defaultSize:g.byteLength,defaultFlags:33554432,defaultDuration:B,samples:t})},Ca=i=>{const A=new VA(i);return A.peekBit()===1&&A.readBits(32),Ph(A),zh(A)},Yh=i=>{let A=0,t=0;for(let e=0;e<8;e++){const g=i.readBits(8);if(A|=(g&127)<<e*7,t+=1,(g&128)!==128)break}return[t,A]},Th=i=>{let A=0;for(;A<100&&i.readBit()===0;)A++;return A>=32?0:i.readBits(A)+(1<<A)-1},Ph=i=>{const A=i.remainingBits()/8,t=i.readBits(8);if((t>>7&1)!==0)return;const g=t>>3&15,B=t>>2&1,C=t>>1&1;B==1&&i.readBits(8);const[Q,o]=C?Yh(i):[0,A];return{headerLength:1+B+Q,type:g,obuSize:o}},xh=i=>{const A=i.readBits(32),t=i.readBits(32),e=i.readBit()!==0;let g=0;return e&&(g=Th(i)+1),{timescale:t,equalPictureInterval:e,numUnitsInDisplayTick:A,numTicksPerPicture:g}},Qa=2,YQ=2,Wh=1,Oh=2,Vh=2,Zh=13,Xh=0,jh=2,oa=0,zh=i=>{const A=i.readBits(3),e=i.readBit()!==0,g=i.readBit()!==0;let B,C=!1,Q=!1,o=!1,a=0,c=0;const h=[];if(g)i.readBits(5);else{if(Q=i.readBit()!==0,Q&&(B=xh(i),C=i.readBit()!==0,C))throw new Error("Not implemented");o=i.readBit()!==0;const QA=i.readBits(5)+1;for(let R=0;R<QA;R++){const L=i.readBits(12),Z=i.readBits(5);let aA=0;if(Z>7&&(aA=i.readBit()),C)throw new Error("decoderModelInfoPresentFlag==1");o&&i.readBit()!==0&&i.readBits(4),h.push({tier:aA,operatingPointIdc:L,seqLevelIdx:Z})}}const l=i.readBits(4)+1,m=i.readBits(4)+1,y=i.readBits(l)+1,f=i.readBits(m)+1;let k=!1;g?k=!1:k=i.readBit()!==0,k&&(a=i.readBits(4)+2,c=i.readBits(3)+1);const q=i.readBit()!==0,U=i.readBit()!==0,H=i.readBit()!==0;let T=!1,z=!1,Y=!1,FA=!1,nA=!1,mA=!1,tt=!1,JA=Qa,w=YQ,G=0;g||(T=i.readBit()!==0,z=i.readBit()!==0,Y=i.readBit()!==0,FA=i.readBit()!==0,nA=i.readBit()!==0,nA&&(mA=i.readBit()!==0,tt=i.readBit()!==0),i.readBit()!==0?JA=Qa:JA=i.readBit(),JA>0?i.readBit()>0?w=YQ:w=i.readBit():w=YQ,nA?G=i.readBits(3):G=0);const AA=i.readBit()!==0,iA=i.readBit()!==0,O=i.readBit()!==0;return{seqProfile:A,stillPicture:e,reducedStillPictureHeader:g,timingInfoPresentFlag:Q,timingInfo:B!=null?B:{equalPictureInterval:!1,numUnitsInDisplayTick:0,timescale:0,numTicksPerPicture:0},decoderModelInfoPresentFlag:C,initialDisplayDelayPresentFlag:o,operatingPoints:h,frameWidthBits:l,frameHeightBits:m,maxFrameWidth:y,maxFrameHeight:f,frameIdNumbersPresentFlag:k,deltaFrameIdLength:a,additionalFrameIdLength:c,use_128x128Superblock:q,enableFilterIntra:U,enableIntraEdgeFilter:H,enableInterintraCompound:T,enableMaskedCompound:z,enableWarpedMotion:Y,enableDualFilter:FA,enableOrderHint:nA,enableJntComp:mA,enableRefFrameMvs:tt,seqForceScreenContentTools:JA,seqForceIntegerMv:w,orderHintBits:G,enableSuperres:AA,enableCdef:iA,enableRestoration:O,colorConfig:_h(i,A),filmGrainParamsPresent:i.readBit()!==0}},_h=(i,A)=>{const t=i.readBit()!==0;let e=8,g=!1;A===2&&t?e=i.readBit()!==0?12:10:A<=2&&(e=t?10:8),A===1?g=!1:g=i.readBit()!==0;const B=g?1:3,C=i.readBit()!==0;let Q=Oh,o=Vh,a=jh,c=!1,h=0,l=0,m=oa,y=!1;return C&&(Q=i.readBits(8),o=i.readBits(8),a=i.readBits(8)),g?(c=i.readBit()!==0,h=1,l=1,m=oa,y=!1,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:a,numPlanes:B,separateUvDeltaQ:y,subsamplingX:h,subsamplingY:l,transferCharacteristics:o}):Q===Wh&&o==Zh&&a==Xh?(c=!0,h=0,l=0,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:a,numPlanes:B,separateUvDeltaQ:y,subsamplingX:h,subsamplingY:l,transferCharacteristics:o}):(c=i.readBit()!==0,A===0?(h=1,l=1):A===1?(h=0,l=0):e===12?(h=i.readBit(),h!==0?l=i.readBit():l=0):(h=1,l=0),h!==0&&l!==0&&(m=i.readBits(2)),y=i.readBit()!==0,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:a,numPlanes:B,separateUvDeltaQ:y,subsamplingX:h,subsamplingY:l,transferCharacteristics:o})},$h=i=>{const A=Ca(i);if(A)return{width:A.maxFrameWidth,height:A.maxFrameHeight}},Ad=(i,A)=>{const t=i.map(Q=>V(D({},Q),{data:new Uint8Array(Q.data)}));if(!t[0])throw new Error("At least one sample must be provided");const{isSync:e,timestamp:g,data:B,duration:C}=t[0];return _B({trackId:1,timestamp:g,sequenceNumber:A,defaultSize:B.byteLength,defaultFlags:e?33554432:16842752,defaultDuration:C,samples:t})},td=(i,A)=>{const t=Ca(i);if(!t)throw new Error("Failed to parse sequence header");return zB([{type:"video",parsedSequenceHeader:t,sequenceHeader:new Uint8Array(i),width:t.maxFrameWidth,height:t.maxFrameHeight,timescale:A,duration:0,trackId:1}])},ed=i=>{const{codec:A,initData:t,timescale:e}=i;switch(A){case"h264":return Id(t,e);case"av1":return gd(t,e);case"opus":return sd(t,e,i.channelCount||2);case"aac":return Bd(t,e,i.channelCount||2);default:throw new Error(`Failed to initialize ${A} segment`)}},id=(i,A)=>{switch(i){case"h264":return Ba(A);case"av1":return $h(A)}},Id=(i,A)=>qh(i,A),gd=(i,A)=>td(i,A),sd=(i,A,t)=>vh(new Uint8Array(i),t,A),Bd=(i,A,t)=>Mh(new Uint8Array(i),t,A,A),Cd=(i,A)=>{if(!i[0])throw new Error("At least one sample must be provided");switch(i[0].codec){case"h264":return Hh(i,A);case"opus":return Kh(i,A);case"aac":return Jh(i,A);case"av1":return Ad(i,A);default:throw new Error(`Unsupported codec ${i[0].codec}`)}},Gg=i=>!!(i&1),Qd=i=>!!(i&2),od=i=>!!(i&4),nd=i=>!!(i&8),ad=i=>!!(i&16),Ed=i=>{const A=new DataView(i,0),t=A.getUint8(0),e=A.getUint16(1),g=A.getUint8(3),B=A.getUint8(4),C=Oe(new Uint8Array(i),5,12),Q=A.getUint32(13),o=ad(g)?A.getInt16(17):void 0,a=i.slice(e);return{version:t,renditionId:B,flags:g,timestamp:C,timescale:Q,payload:a,compositionTimeOffset:o}},rd="data:video/mp4;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAGF21kYXTeBAAAbGliZmFhYyAxLjI4AABCAJMgBDIARwAAArEGBf//rdxF6b3m2Ui3lizYINkj7u94MjY0IC0gY29yZSAxNDIgcjIgOTU2YzhkOCAtIEguMjY0L01QRUctNCBBVkMgY29kZWMgLSBDb3B5bGVmdCAyMDAzLTIwMTQgLSBodHRwOi8vd3d3LnZpZGVvbGFuLm9yZy94MjY0Lmh0bWwgLSBvcHRpb25zOiBjYWJhYz0wIHJlZj0zIGRlYmxvY2s9MTowOjAgYW5hbHlzZT0weDE6MHgxMTEgbWU9aGV4IHN1Ym1lPTcgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0xNiBjaHJvbWFfbWU9MSB0cmVsbGlzPTEgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz02IGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTI1MCBrZXlpbnRfbWluPTI1IHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NDAgcmM9Y3JmIG1idHJlZT0xIGNyZj0yMy4wIHFjb21wPTAuNjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCB2YnZfbWF4cmF0ZT03NjggdmJ2X2J1ZnNpemU9MzAwMCBjcmZfbWF4PTAuMCBuYWxfaHJkPW5vbmUgZmlsbGVyPTAgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAAAFZliIQL8mKAAKvMnJycnJycnJycnXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXiEASZACGQAjgCEASZACGQAjgAAAAAdBmjgX4GSAIQBJkAIZACOAAAAAB0GaVAX4GSAhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGagC/AySEASZACGQAjgAAAAAZBmqAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZrAL8DJIQBJkAIZACOAAAAABkGa4C/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmwAvwMkhAEmQAhkAI4AAAAAGQZsgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGbQC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm2AvwMkhAEmQAhkAI4AAAAAGQZuAL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGboC/AySEASZACGQAjgAAAAAZBm8AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZvgL8DJIQBJkAIZACOAAAAABkGaAC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmiAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpAL8DJIQBJkAIZACOAAAAABkGaYC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmoAvwMkhAEmQAhkAI4AAAAAGQZqgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGawC/AySEASZACGQAjgAAAAAZBmuAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZsAL8DJIQBJkAIZACOAAAAABkGbIC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm0AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZtgL8DJIQBJkAIZACOAAAAABkGbgCvAySEASZACGQAjgCEASZACGQAjgAAAAAZBm6AnwMkhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AAAAhubW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAABDcAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAzB0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAA+kAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAALAAAACQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAPpAAAAAAABAAAAAAKobWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAB1MAAAdU5VxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACU21pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAhNzdGJsAAAAr3N0c2QAAAAAAAAAAQAAAJ9hdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAALAAkABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAALWF2Y0MBQsAN/+EAFWdCwA3ZAsTsBEAAAPpAADqYA8UKkgEABWjLg8sgAAAAHHV1aWRraEDyXyRPxbo5pRvPAyPzAAAAAAAAABhzdHRzAAAAAAAAAAEAAAAeAAAD6QAAABRzdHNzAAAAAAAAAAEAAAABAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAAIxzdHN6AAAAAAAAAAAAAAAeAAADDwAAAAsAAAALAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAAiHN0Y28AAAAAAAAAHgAAAEYAAANnAAADewAAA5gAAAO0AAADxwAAA+MAAAP2AAAEEgAABCUAAARBAAAEXQAABHAAAASMAAAEnwAABLsAAATOAAAE6gAABQYAAAUZAAAFNQAABUgAAAVkAAAFdwAABZMAAAWmAAAFwgAABd4AAAXxAAAGDQAABGh0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAACAAAAAAAABDcAAAAAAAAAAAAAAAEBAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAQkAAADcAABAAAAAAPgbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAC7gAAAykBVxAAAAAAALWhkbHIAAAAAAAAAAHNvdW4AAAAAAAAAAAAAAABTb3VuZEhhbmRsZXIAAAADi21pbmYAAAAQc21oZAAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAADT3N0YmwAAABnc3RzZAAAAAAAAAABAAAAV21wNGEAAAAAAAAAAQAAAAAAAAAAAAIAEAAAAAC7gAAAAAAAM2VzZHMAAAAAA4CAgCIAAgAEgICAFEAVBbjYAAu4AAAADcoFgICAAhGQBoCAgAECAAAAIHN0dHMAAAAAAAAAAgAAADIAAAQAAAAAAQAAAkAAAAFUc3RzYwAAAAAAAAAbAAAAAQAAAAEAAAABAAAAAgAAAAIAAAABAAAAAwAAAAEAAAABAAAABAAAAAIAAAABAAAABgAAAAEAAAABAAAABwAAAAIAAAABAAAACAAAAAEAAAABAAAACQAAAAIAAAABAAAACgAAAAEAAAABAAAACwAAAAIAAAABAAAADQAAAAEAAAABAAAADgAAAAIAAAABAAAADwAAAAEAAAABAAAAEAAAAAIAAAABAAAAEQAAAAEAAAABAAAAEgAAAAIAAAABAAAAFAAAAAEAAAABAAAAFQAAAAIAAAABAAAAFgAAAAEAAAABAAAAFwAAAAIAAAABAAAAGAAAAAEAAAABAAAAGQAAAAIAAAABAAAAGgAAAAEAAAABAAAAGwAAAAIAAAABAAAAHQAAAAEAAAABAAAAHgAAAAIAAAABAAAAHwAAAAQAAAABAAAA4HN0c3oAAAAAAAAAAAAAADMAAAAaAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAACMc3RjbwAAAAAAAAAfAAAALAAAA1UAAANyAAADhgAAA6IAAAO+AAAD0QAAA+0AAAQAAAAEHAAABC8AAARLAAAEZwAABHoAAASWAAAEqQAABMUAAATYAAAE9AAABRAAAAUjAAAFPwAABVIAAAVuAAAFgQAABZ0AAAWwAAAFzAAABegAAAX7AAAGFwAAAGJ1ZHRhAAAAWm1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALWlsc3QAAAAlqXRvbwAAAB1kYXRhAAAAAQAAAABMYXZmNTUuMzMuMTAw",$B=()=>"wakeLock"in navigator&&window.navigator.userAgent.indexOf("Samsung")===-1;class cd{constructor(){I(this,"enabled",!1);I(this,"wakeLockVideo");I(this,"_wakeLock",null);I(this,"handleVisibilityChange",()=>{this._wakeLock!==null&&document.visibilityState==="visible"&&this.enable()});$B()&&(this._wakeLock=null,document.addEventListener("visibilitychange",this.handleVisibilityChange),document.addEventListener("fullscreenchange",this.handleVisibilityChange))}_addSourceToVideo(A,t,e){const g=document.createElement("source");g.src=e,g.type=`video/${t}`,A.appendChild(g)}get isEnabled(){return this.enabled}attach(A){if(!$B()){if(!this.wakeLockVideo){const t=document.createElement("video");this.wakeLockVideo=t,this.wakeLockVideo.setAttribute("title","Live Stream"),this.wakeLockVideo.setAttribute("playsinline",""),this._addSourceToVideo(this.wakeLockVideo,"mp4",rd),Object.assign(this.wakeLockVideo.style,{position:"absolute",left:"-100%",top:"-100%"}),this.wakeLockVideo.addEventListener("loadedmetadata",()=>{t.addEventListener("timeupdate",()=>{t.currentTime>.5&&(t.currentTime=Math.random())})})}A&&A.appendChild(this.wakeLockVideo)}}enable(){return r(this,null,function*(){var A,t;return $B()?navigator.wakeLock.request("screen").then(e=>{this._wakeLock=e,this.enabled=!0,this._wakeLock.addEventListener("release",()=>{})}).catch(()=>{this.enabled=!1}):((t=(A=this.wakeLockVideo)==null?void 0:A.play())!=null?t:Promise.resolve()).then(g=>(this.enabled=!0,g)).catch(()=>{this.enabled=!1})})}disable(){var A,t;$B()?(this._wakeLock&&this._wakeLock.release(),this._wakeLock=null):((A=this.wakeLockVideo)==null||A.pause(),(t=this.wakeLockVideo)==null||t.remove()),this.enabled=!1}unload(){document.removeEventListener("visibilitychange",this.handleVisibilityChange),document.removeEventListener("fullscreenchange",this.handleVisibilityChange),this.disable()}}const hd=/\r\n|\r|\n/;class na{constructor(A){n(this,me);n(this,zt);E(this,me,A),E(this,zt,0)}skipEmptyLines(){let A=0;for(;s(this,me)[s(this,zt)]==="";)ft(this,zt)._++,A++;return A}readLine(){return s(this,me)[ft(this,zt)._++]}takeUntilEmptyLine(){const A=[];for(;s(this,me)[s(this,zt)]!=="";){const t=this.readLine();if(t===void 0)break;A.push(t)}return A}linesLeft(){return s(this,me).length-s(this,zt)}}me=new WeakMap,zt=new WeakMap;class aa{constructor(){n(this,oi)}parse(A){const t=[],e=A.split(hd),g=new na(e),B=g.readLine();if(!B||!B.startsWith("WEBVTT"))throw new Error("missing 'WEBVTT' signature");for(;g.readLine()!=="";);for(;g.linesLeft()>0;){const C=d(this,oi,zE).call(this,g);C&&t.push(C),g.skipEmptyLines()}return t}}oi=new WeakSet,zE=function(A){A.skipEmptyLines();const t=A.takeUntilEmptyLine(),e=new na(t);let g=e.readLine(),B;if(g!=null&&g.startsWith("NOTE"))return;if(g!=null&&g.includes("-->")||(B=g,g=e.readLine()),g===void 0)throw new Error("expected cue line");const[C,Q]=g.split("-->").map(m=>m.trim());if(!C||!Q)throw new Error(`a cue needs both start and end time start: ${C} end: ${Q}`);const[o,a]=Q.split(" ",1).map(m=>m.trim());if(!o)throw new Error(`missing end time: ${o}`);const c=e.readLine();if(!c)throw new Error("missing text");const h=d(this,oi,Qn).call(this,C),l=d(this,oi,Qn).call(this,o);return{id:B,startTime:h,endTime:l,text:c}},Qn=function(A){const t=A.split(":");if(t.length==2){const[Q=0,o=0]=t.map(c=>parseFloat(c));return Q*60+o}const[e=0,g=0,B=0]=t.map(Q=>parseFloat(Q));return e*60*60+g*60+B};const dd=i=>{const A=window;A.vindralInstances=A.vindralInstances||{},A.vindralInstances[i.getStatistics().clientId.substring(0,8)]=i};class TQ extends it{constructor({type:t,autoplay:e,muted:g,volume:B,logger:C,poster:Q}){super();I(this,"element");I(this,"logger");I(this,"seekTimes",new W(10));I(this,"seekStartTime");I(this,"_userProvidedMuted");I(this,"timers",new NA);I(this,"_userHasProvidedInput",!1);I(this,"_isPaused",!0);I(this,"isActivated",!1);I(this,"dummy");I(this,"_iosHackEnterPiPMode",()=>{const t=this.element.parentElement,e=this.element.clientWidth/this.element.clientHeight;this.element.style.position="fixed",this.element.style.opacity="0",this.element.style.pointerEvents="none",t&&(this.dummy=document.createElement("video"),this.dummy.style.paddingBottom="calc(100% / "+e+")",this.dummy.style.width="100%",this.dummy.style.height="0px",t.appendChild(this.dummy))});I(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)});I(this,"attach",t=>{this.element.remove(),t.appendChild(this.element)});I(this,"load",()=>{this.timers.setInterval(this.onPlayPause,500),this.timers.setTimeout(()=>{this.timers.setInterval(this.onBufferStateChange,500)},1e4)});I(this,"unload",()=>{this.timers.unload()});I(this,"getPlaybackRate",()=>this.element.playbackRate);I(this,"getPlaybackState",()=>this.element.readyState>=this.element.HAVE_FUTURE_DATA?"playing":"buffering");I(this,"setPlaybackRate",t=>void(this.element.playbackRate=t));I(this,"getBuffer",()=>{const t=[],e=this.element.buffered;if(!e)return[];for(let g=0;g<e.length;g++)t.push({start:e.start(g)*1e3,end:e.end(g)*1e3});return t});I(this,"pause",()=>{this._isPaused=!1,this.element.pause()});I(this,"tryPlay",()=>{this.element.muted=this._userProvidedMuted,this._play().catch(F)});I(this,"play",()=>{this.element.muted=this._userProvidedMuted,this._play().catch(t=>{if(t instanceof Error){const e=new x("Media Play Error",{source:t,isFatal:!1,code:"media_play_error"});this.emit("error",e)}})});I(this,"_play",()=>r(this,null,function*(){try{yield this.element.play(),this._userHasProvidedInput=!this.muted||this._userProvidedMuted}catch(t){if(t instanceof Error&&t.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 t}}));I(this,"onEvent",t=>{this.logger.trace(t.type,{state:this.element.readyState,event:t,playbackState:this.getPlaybackState()})});I(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})});I(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"))});I(this,"onBufferStateChange",()=>{this.emit("buffer state",{isPaused:this.element.paused,buffered:this.getBuffer(),currentTime:this.currentTime,playbackState:this.getPlaybackState()})});I(this,"onSeekStart",()=>{this.seekStartTime=Date.now()});I(this,"onSeekEnd",()=>{this.seekStartTime&&(this.seekTimes.push(Date.now()-this.seekStartTime),this.seekStartTime=void 0)});this.logger=C,this._userProvidedMuted=g,this.element=document.createElement(t),this.element instanceof HTMLVideoElement&&(this.element.playsInline=!0),this.element.controls=!1,this.element.autoplay=e,this.element.muted=g,B!==void 0&&(this.element.volume=B),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||!Q||this.element.setAttribute("poster",Q)},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:Wt(this.seekTimes.items())}get isSeeking(){return this.element.seeking}get currentTime(){return isNaN(this.element.currentTime)?0:this.element.currentTime*1e3}set currentTime(t){Number.isFinite(t)&&(this.element.currentTime=t/1e3)}get playbackRate(){return this.element.playbackRate}set playbackRate(t){this.element.playbackRate=t}get volume(){return this.element.volume}set volume(t){this.element.volume=t}get muted(){return this.element.muted}set muted(t){this._userProvidedMuted=t,this.element.muted=t}get userHasProvidedInput(){return this._userHasProvidedInput}get isPaused(){return this._isPaused}}const ld=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 je(i)?A={type:"media-source",audio:{contentType:ze(i),bitrate:i.bitRate,channels:i.channels.toString(),samplerate:i.sampleRate}}:A={type:"media-source",video:{contentType:ze(i),bitrate:i.bitRate,width:i.width,height:i.height,framerate:i.frameRate[0]/i.frameRate[1]}},navigator.mediaCapabilities.decodingInfo(A)},ud=.15,wd=.2,Ea=.4,Dd=.5,md=.6,PQ=15,Sd={cooldownTime:3e3,maxBufferingEvents:{last10Seconds:0},maxBufferingRatio:{last10Seconds:0},maxRecentDowngradesCount:3,maxDowngradeLookbackMs:60*1e3,minTimeSpentPlaying:{factor:.5,ratio:.1},maxCooldownRatio:2},xQ=i=>A=>A>i,pC=class pC{constructor(A,t,e,g){I(this,"qualityOfServiceSource");I(this,"config");I(this,"emitter");I(this,"logger");I(this,"isSuspended",!1);I(this,"lastAdaptTime",Date.now());I(this,"isEnabled",!0);I(this,"load",()=>{this.emitter.on("buffer state",this.onBufferState),this.emitter.on("adapted level",this.onAdaptedLevel)});I(this,"unload",()=>{this.emitter.off("buffer state",this.onBufferState),this.emitter.off("adapted level",this.onAdaptedLevel)});I(this,"suspend",()=>{this.isSuspended=!0});I(this,"unsuspend",()=>{this.reset(),this.isSuspended=!1});I(this,"reset",(A=0)=>{this.lastAdaptTime=Date.now()+A});I(this,"getStatistics",()=>({isAbrEnabled:this.isEnabled}));I(this,"isQoSOk",A=>{const t=this.qualityOfServiceSource.getLevelStats(A),{upgradesFromLevel:e,downgradesFromLevel:g}=t!=null?t:{upgradesFromLevel:[],downgradesFromLevel:[]},B=Date.now()-this.config.maxDowngradeLookbackMs,C=g.filter(xQ(B)).length,Q=e.filter(xQ(B)).length;if(C-Q>this.config.maxRecentDowngradesCount)return this.logger.debug("Recent downgrades count is over maximum",{downgrades:C-Q,maxRecentDowngradesCount:this.config.maxRecentDowngradesCount}),!1;const o=this.qualityOfServiceSource.timeSpentPlayingInAtLeastLevelRatio(A),a=this.qualityOfServiceSource.timeActive()-this.qualityOfServiceSource.timeSpentBuffering(),c=o*a/this.config.maxDowngradeLookbackMs;if(C>1&&c<this.config.minTimeSpentPlaying.factor)return this.logger.debug("Time spent playing is too low",{recentDowngrades:C,timeSpentPlayingInAtLeastLevelRatio:o}),!1;if(C>1&&o<this.config.minTimeSpentPlaying.ratio)return this.logger.debug("Time spent playing in at least this level is too low",{recentDowngrades:C,timeSpentPlayingInAtLeastLevelRatio:o}),!1;const h=Math.max(0,g.length-e.length-c),l=Date.now()-this.config.maxDowngradeLookbackMs*h,m=g.filter(xQ(l)).length;return m&&h>this.config.maxCooldownRatio?(this.logger.debug("Too many downgrades compared to time spent playing",{downgradesWithinCooldownTime:m,cooldownRatio:h}),!1):!0});I(this,"onBufferState",A=>{if(!this.isEnabled||this.isSuspended||this.lastAdaptTime+this.config.cooldownTime>Date.now())return;const{bufferFullness:t,general:e}=this.qualityOfServiceSource.getMetrics(),g=this.qualityOfServiceSource.getBufferFullnessRegression();if(!g)return;const B=10*1e3,C=30*1e3,{slope:Q}=g,o=g.predict(PQ),a=Q<0,c=g.predict(PQ)<Ea&&g.slope<0,h=g.predict(PQ)>md,l=this.qualityOfServiceSource.timeSpentBufferingLast(C),m=this.qualityOfServiceSource.timeSpentActiveLast(C),y=this.qualityOfServiceSource.bufferingEventsLast(C),f=m>0?l/m:0,k=this.qualityOfServiceSource.getTargetBufferTime();if(t<.15&&f>.8){this.adaptLevel("reconnect");return}if(e.decodeRate<=1){this.adaptLevel("downgrade");return}if(t>Dd&&h&&!this.tooMuchTimeBuffering(B)&&!this.tooManyBufferingEvents(B)){this.adaptLevel("upgrade");return}if(k<1e3){A.playbackState==="buffering"&&(y>5||f>.3)&&this.adaptLevel("downgrade");return}(c||t<ud)&&a&&t<Ea&&o<wd&&this.adaptLevel(A.playbackState==="buffering"?"double downgrade":"downgrade")});I(this,"onAdaptedLevel",()=>{this.reset()});I(this,"adaptLevel",A=>this.emitter.emit("adapt level",A));this.qualityOfServiceSource=e,this.config=D(D({},Sd),g),this.emitter=A,this.logger=t}tooMuchTimeBuffering(A){const t=this.qualityOfServiceSource.timeSpentActiveLast(A);return(t?this.qualityOfServiceSource.timeSpentBufferingLast(A)/t:0)>this.config.maxBufferingRatio.last10Seconds}tooManyBufferingEvents(A){return this.qualityOfServiceSource.timeSpentBufferingLast(A)>this.config.maxBufferingEvents.last10Seconds}};I(pC,"create",(A,t,e,g={})=>new pC(A,t,e,g));let WQ=pC;const yd={minBufferTime:1500,maxBufferTime:1500,cooldownTime:3e4,maxBufferingEvents:{last30Seconds:3},maxBufferingRatio:{last30Seconds:.15}},Se=class Se{constructor(A,t,e,g,B){I(this,"qualityOfServiceSource");I(this,"targetBufferTimeTarget");I(this,"config");I(this,"emitter");I(this,"logger");I(this,"isSuspended",!1);I(this,"lastIncreaseTime",Date.now());I(this,"bufferTimeAdjustmentCount",0);I(this,"load",()=>{this.emitter.on("buffer state",this.onBufferState)});I(this,"unload",()=>{this.emitter.off("buffer state",this.onBufferState)});I(this,"suspend",()=>{this.isSuspended=!0});I(this,"unsuspend",()=>{this.reset(),this.isSuspended=!1});I(this,"reset",()=>{this.lastIncreaseTime=Date.now()});I(this,"getStatistics",()=>({bufferTimeAdjustmentCount:this.bufferTimeAdjustmentCount}));I(this,"onBufferState",A=>{const{minBufferTime:t,maxBufferTime:e,cooldownTime:g}=this.config;if(this.isSuspended||this.lastIncreaseTime+g>Date.now()||this.targetBufferTimeTarget.targetBufferTime>=e)return;const B=this.qualityOfServiceSource.timeSpentBufferingLast(30*1e3),C=this.qualityOfServiceSource.bufferingEventsLast(30*1e3),Q=this.qualityOfServiceSource.timeSpentActiveLast(30*1e3),o=B/Q,a=Math.ceil(Math.max((e-t)/(Se.BUFFER_TIME_MAX_STEPS-1),Se.BUFFER_TIME_STEP_SIZE));(o>this.config.maxBufferingRatio.last30Seconds||C>this.config.maxBufferingEvents.last30Seconds)&&(this.targetBufferTimeTarget.targetBufferTime=Math.min(e,this.targetBufferTimeTarget.targetBufferTime+a),this.bufferTimeAdjustmentCount++,this.reset())});this.qualityOfServiceSource=e,this.targetBufferTimeTarget=g,this.config=D(D({},yd),B),this.emitter=A,this.logger=t}updateConfig(A){this.config=D(D({},this.config),A)}};I(Se,"BUFFER_TIME_STEP_SIZE",500),I(Se,"BUFFER_TIME_MAX_STEPS",3),I(Se,"create",(A,t,e,g,B={})=>new Se(A,t,e,g,B));let OQ=Se;const fd=i=>i?{Authorization:`Bearer ${i}`}:void 0,pd=(i,A)=>{try{const t=i.ancestorOrigins;if(t&&t.length>0)return Array.from(t).join(",")||void 0}catch(t){}try{if(A.referrer)return new URL(A.referrer).origin||void 0}catch(t){}},Fd=i=>typeof i=="object"&&i!==null&&"message"in i;class Gd extends Error{constructor({status:t,url:e,body:g}){const B=pn(g),C=Fd(B)?B.message:`Url ${e.toString()}, Status code: ${t}, Body: ${g}`;super(C);I(this,"status");I(this,"body");I(this,"url");this.status=t,this.body=g,this.url=e,Object.setPrototypeOf(this,new.target.prototype)}}const kd=i=>typeof i.status=="number",Rd=()=>{if(!(typeof window=="undefined"||typeof document=="undefined"))return pd(window.location,document)},Ud=i=>{const A=Rd();if(!A||i.searchParams.has("parentOrigin"))return i;const t=new URL(i.toString());return t.searchParams.append("parentOrigin",A),t},ra=(i,A)=>r(null,null,function*(){const t=Ud(i),e=yield fetch(t.toString(),D({mode:"cors"},A));if(!e.ok)throw new Gd({status:e.status,url:t,body:yield e.text()});return e}),VQ=(i,A)=>r(null,null,function*(){return yield(yield ra(i,D({},A))).json()}),ca=(i,A)=>r(null,null,function*(){return ra(i,D({method:"POST"},A))});function Nd(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 ha={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 da{constructor(A){I(this,"baseUrl");I(this,"tokenFactory");this.baseUrl=new URL("/api/v4/",A.publicEndpoint).toString(),this.tokenFactory=A.tokenFactory}connect(A){return r(this,null,function*(){const{channelId:t,channelGroupId:e}=A,g={channelId:t,channelGroupId:e},B=new URL(ha.lbConnect(A),this.baseUrl),C=this.getAuthToken(g),Q=yield VQ(B,{headers:this.getHeaders(C)});if(Nd(Q)){const o=Q.channels.map(a=>{const c=this.toChannel(a,g),h=Un(a.catalog);return V(D(D({},a),c),{renditions:h})});return V(D({},Q),{channels:o})}else{const o=Q.channels.map(a=>{const c=this.toChannel(a,g);return D(D({},a),c)});return V(D({},Q),{channels:o})}})}getChannel(A){return r(this,null,function*(){const t={channelId:A},e=new URL(`channel/${A}`,this.baseUrl),g=this.getAuthToken(t),B=yield VQ(e,{headers:this.getHeaders(g)});return this.toChannel(B,t,g)})}getChannels(A){return r(this,null,function*(){const t={channelGroupId:A},e=new URL(`channels/${A}`,this.baseUrl),g=this.getAuthToken(t),B=yield VQ(e,{headers:this.getHeaders(g)}),C=Array.isArray(B)?B:B.channels;return this.toChannels(C,t,g)})}getHeaders(A){var e;return(e=fd(A))!=null?e:{}}getAuthToken(A){return this.tokenFactory?this.tokenFactory(A):void 0}toChannels(A,t,e){return A.map(g=>this.toChannel(g,t,e))}toChannel(A,t,e){const{baseUrl:g,sizes:B}=A.thumbnail,C=g||new URL(ha.thumbnails(t,e),this.baseUrl),Q=B.map(o=>new URL(`?channelId=${A.channelId}&width=${o.width}&height=${o.height}${bd(t,e)}`,C).toString());return{channelId:A.channelId,name:A.name,isLive:A.isLive,thumbnailUrls:Q}}}const bd=(i,A)=>A?i.channelGroupId?`&channelGroupId=${i.channelGroupId}&auth.token=${A}&auth.type=jwt`:`&auth.token=${A}&auth.type=jwt`:"";var AC=(i=>(i[i.StreamHeaderGroup=4]="StreamHeaderGroup",i[i.FetchHeader=5]="FetchHeader",i[i.StreamHeaderTrack=60]="StreamHeaderTrack",i))(AC||{});const KA={Normal:0,ObjectDoesNotExist:1,GroupDoesNotExist:2,EndOfGroup:3,EndOfTrackAndGroup:4};function la(i){switch(i){case KA.Normal:case KA.ObjectDoesNotExist:case KA.GroupDoesNotExist:case KA.EndOfGroup:case KA.EndOfTrackAndGroup:return}throw new Error("Unknown object status "+i)}class Ld{constructor(A,t,e,g,B,C){n(this,kt);n(this,oI);n(this,nI);n(this,os);n(this,ns);n(this,aI,new $);n(this,as,0);n(this,Es);E(this,kt,A),E(this,oI,t),E(this,nI,e),E(this,os,g),E(this,ns,B),E(this,Es,C)}endStatus(){return s(this,aI).promise}groupId(){return s(this,oI)}subscribeId(){return s(this,nI)}next(){return r(this,null,function*(){if(!s(this,aI).pending)return{done:!0,value:void 0};if(yield s(this,kt).isDone())return{done:!0,value:void 0};const A=s(this,as)===0?s(this,oI):yield s(this,kt).readBigVarInt(),t=yield s(this,kt).readBigVarInt(),e=yield s(this,kt).readVarInt();let g=0,B=new Uint8Array;return e>0?B=yield s(this,kt).read(e):g=yield s(this,kt).readVarInt(),la(g),(g===KA.EndOfTrackAndGroup||g===KA.EndOfGroup)&&s(this,aI).resolve(g),ft(this,as)._++,{done:!1,value:{subscribeId:s(this,nI),trackAlias:s(this,os),groupId:A,subGroupId:v(0),objectId:t,subscriberPriority:s(this,ns),streamId:s(this,Es),objectStatus:g,payload:B}}})}return(){return r(this,null,function*(){for(;!(yield this.next()).done;);return{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[pt()](){return Promise.resolve()}[Symbol.asyncDispose](){return Promise.resolve()}}kt=new WeakMap,oI=new WeakMap,nI=new WeakMap,os=new WeakMap,ns=new WeakMap,aI=new WeakMap,as=new WeakMap,Es=new WeakMap;class Jd{constructor(A,t,e,g,B){n(this,ni);n(this,Rt);n(this,EI);n(this,rs);n(this,cs);n(this,rI);E(this,Rt,A),E(this,EI,t),E(this,rs,e),E(this,cs,g),E(this,rI,B)}streamId(){return s(this,rI)}groups(){return d(this,ni,_E).call(this)}subscribeId(){return s(this,EI)}return(){return r(this,null,function*(){return yield s(this,Rt).close(),{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[pt()](){return d(this,ni,on).call(this)}[Symbol.asyncDispose](){return d(this,ni,on).call(this)}}Rt=new WeakMap,EI=new WeakMap,rs=new WeakMap,cs=new WeakMap,rI=new WeakMap,ni=new WeakSet,_E=function(){return Ee(this,null,function*(){for(;!(yield new EA(s(this,Rt).isDone()));){const A=yield new EA(s(this,Rt).readBigVarInt()),t=new Ld(s(this,Rt),A,s(this,EI),s(this,rs),s(this,cs),s(this,rI));if(yield t,(yield new EA(Promise.race([t.endStatus(),s(this,Rt).closed()])))===KA.EndOfTrackAndGroup)return}})},on=function(){return s(this,Rt).close().catch(()=>{})};class Md{constructor(A,t,e,g,B,C,Q){n(this,ai);n(this,dt);n(this,cI);n(this,hs);n(this,hI);n(this,ds);n(this,ls);n(this,us,!1);n(this,dI);n(this,FC,UA.get().createContext("GroupReader"));E(this,dt,A),E(this,cI,t),E(this,hs,e),E(this,hI,g),E(this,ds,B),E(this,ls,C),E(this,dI,Q)}streamId(){return s(this,dI)}groupId(){return s(this,hI)}subscribeId(){return s(this,cI)}next(){return r(this,null,function*(){try{if((yield s(this,dt).isDone())||s(this,us))return{done:!0,value:void 0};const A=yield s(this,dt).readBigVarInt(),t=yield s(this,dt).readVarInt();let e=0,g=new Uint8Array;return t>0?g=yield s(this,dt).read(t):e=yield s(this,dt).readVarInt(),la(e),e===KA.EndOfGroup&&E(this,us,!0),{done:!1,value:{subscribeId:s(this,cI),trackAlias:s(this,hs),groupId:s(this,hI),subGroupId:s(this,ds),subscriberPriority:s(this,ls),streamId:s(this,dI),objectId:A,objectStatus:e,payload:g}}}catch(A){return s(this,FC).info("Error reading object",{error:A}),{done:!0,value:void 0}}})}return(){return r(this,null,function*(){return yield s(this,dt).close().catch(()=>{}),{done:!0,value:void 0}})}groups(){return d(this,ai,$E).call(this)}[Symbol.asyncIterator](){return this}[pt()](){return d(this,ai,nn).call(this)}[Symbol.asyncDispose](){return d(this,ai,nn).call(this)}}dt=new WeakMap,cI=new WeakMap,hs=new WeakMap,hI=new WeakMap,ds=new WeakMap,ls=new WeakMap,us=new WeakMap,dI=new WeakMap,FC=new WeakMap,ai=new WeakSet,$E=function(){return Ee(this,null,function*(){yield this})},nn=function(){return s(this,dt).close().catch(()=>{})};function ua(i,A){return r(this,null,function*(){const t=yield i.readVarInt();switch(t){case AC.StreamHeaderGroup:{const e=yield i.readBigVarInt(),g=yield i.readBigVarInt(),B=yield i.readBigVarInt(),C=yield i.readBigVarInt(),Q=yield i.readUnsigned8();return new Md(i,e,g,B,C,Q,A)}case AC.StreamHeaderTrack:{const e=yield i.readBigVarInt(),g=yield i.readBigVarInt(),B=yield i.readUnsigned8();return new Jd(i,e,g,B,A)}default:throw new Error("Unexpected message type "+t)}})}class Hd{constructor(A,t){n(this,ye);n(this,ws);E(this,ye,A),E(this,ws,t)}start(A){s(this,ye).addEventListener("message",t=>{if(typeof t.data=="object"&&t.data instanceof ArrayBuffer){const e=new Uint8Array(t.data);e[0]==s(this,ws)&&A.enqueue(e.subarray(1))}}),s(this,ye).addEventListener("error",()=>A.error(new Error("WebSocket error"))),s(this,ye).addEventListener("close",()=>fn(()=>A.close()))}cancel(A){s(this,ye).close(void 0,A)}}ye=new WeakMap,ws=new WeakMap;class qd{constructor(A){n(this,Ut);n(this,Ei,null);n(this,ri,null);n(this,ci,null);E(this,Ut,A)}start(A){E(this,Ei,t=>{if(typeof t.data=="object"&&t.data instanceof ArrayBuffer){const e=new Uint8Array(t.data),g=e[0]||0,B=g&127,C=(g>>7&1)>0;if(B&&B!==0){const Q=e.subarray(1);A.enqueue([C,B,Q])}}}),E(this,ri,()=>fn(()=>A.close())),E(this,ci,()=>A.error(new Error("WebSocket error"))),s(this,Ut).addEventListener("message",s(this,Ei)),s(this,Ut).addEventListener("error",s(this,ci)),s(this,Ut).addEventListener("close",s(this,ri))}cancel(A){s(this,Ei)&&s(this,Ut).removeEventListener("message",s(this,Ei)),s(this,ci)&&s(this,Ut).removeEventListener("error",s(this,ci)),s(this,ri)&&s(this,Ut).removeEventListener("close",s(this,ri))}}Ut=new WeakMap,Ei=new WeakMap,ri=new WeakMap,ci=new WeakMap;class tC{constructor(A,t){n(this,BA);n(this,Nt);n(this,Ds);n(this,hi);n(this,bt,0);n(this,GC,new TextDecoder);E(this,Nt,A),E(this,Ds,t),E(this,hi,t.getReader())}readUnsigned8(){return r(this,null,function*(){return yield d(this,BA,Vi).call(this,1),d(this,BA,Pe).call(this,1)[0]})}readString(){return r(this,null,function*(){const A=yield this.readVarInt(),t=yield this.read(A);return s(this,GC).decode(t)})}readVarInt(){return r(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 r(this,null,function*(){yield d(this,BA,Vi).call(this,1);const A=(d(this,BA,lQ).call(this,1)[0]&192)>>6;switch(s(this,Nt)[s(this,bt)]=d(this,BA,lQ).call(this,1)[0]&63,A){case 0:return v(d(this,BA,Pe).call(this,1)[0]);case 1:{yield d(this,BA,Vi).call(this,2);const t=d(this,BA,Pe).call(this,2),e=new DataView(t.buffer,t.byteOffset,t.byteLength);return v(e.getUint16(0))}case 2:{yield d(this,BA,Vi).call(this,4);const t=d(this,BA,Pe).call(this,4),e=new DataView(t.buffer,t.byteOffset,t.byteLength);return v(e.getUint32(0))}case 3:{yield d(this,BA,Vi).call(this,8);const t=d(this,BA,Pe).call(this,8),e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(typeof e.getBigUint64!="undefined")return v(e.getBigUint64(0));const g=Oe(t,0,7);return v(g)}default:throw new Error("Invalid VarInt size")}})}read(A){return r(this,null,function*(){return yield d(this,BA,Vi).call(this,A),d(this,BA,Pe).call(this,A)})}readAll(){return r(this,null,function*(){for(;yield d(this,BA,dQ).call(this););return d(this,BA,Pe).call(this,d(this,BA,yB).call(this))})}isDone(){return r(this,null,function*(){return d(this,BA,yB).call(this)>0?!1:(yield d(this,BA,dQ).call(this))==0})}closed(){return r(this,null,function*(){return s(this,hi).closed})}close(){return r(this,null,function*(){return s(this,hi).releaseLock(),s(this,Ds).cancel()})}}Nt=new WeakMap,Ds=new WeakMap,hi=new WeakMap,bt=new WeakMap,GC=new WeakMap,BA=new WeakSet,yB=function(){return s(this,Nt).length-s(this,bt)},dQ=function(){return r(this,null,function*(){const{value:A,done:t}=yield s(this,hi).read();if(t)return Promise.resolve(0);if(d(this,BA,yB).call(this)===0)E(this,Nt,A);else{const g=s(this,Nt).subarray(s(this,bt)),B=new Uint8Array(g.length+A.length);B.set(g),B.set(A,g.byteLength),E(this,Nt,B)}return E(this,bt,0),Promise.resolve(A.length)})},Vi=function(A){return r(this,null,function*(){for(;d(this,BA,yB).call(this)<A;)if((yield d(this,BA,dQ).call(this))===0)throw new Error("Read failed")})},lQ=function(A){return s(this,Nt).subarray(s(this,bt),s(this,bt)+A)},Pe=function(A){const t=d(this,BA,lQ).call(this,A);return E(this,bt,s(this,bt)+t.length),t};class wa{constructor(A){n(this,lI,new Uint8Array(8));n(this,uI);n(this,_t);n(this,kC,new TextEncoder);E(this,uI,A),E(this,_t,s(this,uI).getWriter())}writeString(A){return r(this,null,function*(){const t=s(this,kC).encode(A);return yield this.writeVarInt(t.length),this.write(t)})}write(A){return s(this,_t).write(A)}writeUnsigned8(A){return s(this,_t).write(eC(A,s(this,lI)))}writeVarInt(A){return s(this,_t).write(ka(A,s(this,lI)))}writeBigVarInt(A){return s(this,_t).write(Ra(A,s(this,lI)))}flush(){return r(this,null,function*(){})}close(){return r(this,null,function*(){s(this,_t).releaseLock(),yield s(this,uI).close()})}}lI=new WeakMap,uI=new WeakMap,_t=new WeakMap,kC=new WeakMap;const Da={OPEN:1},ms=class ms{constructor(A){n(this,jA,0);n(this,zA,new Uint8Array(ms.DEFAULT_BUFFER_SIZE));n(this,di);n(this,RC,new TextEncoder);E(this,di,A)}writeString(A){return r(this,null,function*(){const t=s(this,RC).encode(A);return yield this.writeVarInt(t.length),this.write(t)})}ensureBufferSpace(A){if(s(this,zA).length-s(this,jA)>=A)return;const t=new Uint8Array(s(this,zA).length+A);t.set(s(this,zA)),E(this,zA,t)}write(A){return this.ensureBufferSpace(A.length),s(this,zA).set(A,s(this,jA)),E(this,jA,s(this,jA)+A.byteLength),Promise.resolve()}writeUnsigned8(A){return this.ensureBufferSpace(1),eC(A,s(this,zA).subarray(s(this,jA))),E(this,jA,s(this,jA)+1),Promise.resolve()}writeVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return this.ensureBufferSpace(8),E(this,jA,s(this,jA)+ka(A,s(this,zA).subarray(s(this,jA))).byteLength),Promise.resolve()}writeBigVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return this.ensureBufferSpace(8),E(this,jA,s(this,jA)+Ra(A,s(this,zA).subarray(s(this,jA))).byteLength),Promise.resolve()}flush(){if(s(this,di).readyState!==Da.OPEN)throw new Error("Writer is not open");return s(this,di).send(s(this,zA).subarray(0,s(this,jA))),E(this,jA,0),E(this,zA,new Uint8Array(ms.DEFAULT_BUFFER_SIZE)),Promise.resolve()}close(){return s(this,di).close(),Promise.resolve()}};jA=new WeakMap,zA=new WeakMap,di=new WeakMap,RC=new WeakMap,I(ms,"DEFAULT_BUFFER_SIZE",1024);let kg=ms;const ma=2**6-1,Sa=2**14-1,ya=2**30-1,vd=Number.MAX_SAFE_INTEGER,Kd=typeof BigInt=="function"?v(2)**v(62)-v(1):v(Number.MAX_SAFE_INTEGER);function eC(i,A){return A[0]=i,A.subarray(0,1)}function fa(i,A){const t=new DataView(A.buffer,A.byteOffset,2);return t.setUint16(0,i),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function pa(i,A){const t=new DataView(A.buffer,A.byteOffset,4);return t.setUint32(0,i),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function Fa(i,A){const t=new DataView(A.buffer,A.byteOffset,8);return t.setBigUint64(0,i),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function Ga(i,A){const t=new DataView(A.buffer,A.byteOffset,8);return t.setUint32(0,i/4294967296),t.setUint32(4,i&4294967295),A.set([192],0),new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function ka(i,A){if(i<=ma)return eC(i,A);if(i<=Sa)return fa(i|16384,A);if(i<=ya)return pa(i|2147483648,A);if(i<=vd)return typeof BigInt=="function"?Fa(BigInt(i)|BigInt(3221225472)<<BigInt(32),A):Ga(Number(i),A);throw new Error(`overflow, value larger than 53-bits: ${i}`)}function Ra(i,A){if(i<ma)return eC(Number(i),A);if(i<Sa)return fa(Number(i)|16384,A);if(i<=ya)return pa(Number(i)|2147483648,A);if(i<=Kd)return typeof BigInt=="function"?Fa(BigInt(i)|BigInt(3221225472)<<BigInt(32),A):Ga(Number(i),A);throw new Error(`overflow, value larger than 62-bits: ${i}`)}var b=(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))(b||{});function iC(i){return r(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 t=[];for(let e=0;e<A;e++)t.push(yield i.readString());return t})}function ZQ(i,A){return r(this,null,function*(){yield i.writeVarInt(A.length);for(const t of A)yield i.writeString(t)})}const IC=v(2);function $i(i){return r(this,null,function*(){const A=yield i.readVarInt(),t=new Map;for(let e=0;e<A;e++){const g=yield i.readBigVarInt(),B=yield i.read(yield i.readVarInt());t.set(g,{type:g,payload:B})}return t})}function AI(i,A){return r(this,null,function*(){yield i.writeVarInt(A.size);for(const[t,e]of A)yield i.writeBigVarInt(t),yield i.writeVarInt(e.payload.length),yield i.write(e.payload)})}function Yd(i){return r(this,null,function*(){return{type:b.Announce,namespace:yield iC(i),params:yield $i(i)}})}function Td(i,A){return r(this,null,function*(){yield ZQ(i,A.namespace),yield AI(i,A.params)})}function Pd(i){return r(this,null,function*(){return{type:b.AnnounceOk,namespace:yield iC(i)}})}function xd(i,A){return r(this,null,function*(){yield ZQ(i,A.namespace)})}const Wd={"latest-group":1,"latest-object":2,"absolute-start":3,"absolute-range":4};function Od(i){return r(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 Vd(i,A){return r(this,null,function*(){const t=Wd[A.type];switch(yield i.writeVarInt(t),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 ${t}`)}})}function Ua(i){return r(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 Na(i,A){return r(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 Zd(i){return r(this,null,function*(){const A=yield i.readBigVarInt(),t=yield i.readBigVarInt(),e=yield iC(i),g=yield i.readString(),B=yield i.readUnsigned8(),C=yield Ua(i),Q=yield Od(i),o=yield $i(i);if(Q.type==="absolute-range"){const a=Q.start.group>Q.end.group,c=Q.start.group===Q.end.group&&Q.start.object>Q.end.object;if(a||c)throw new Error("Invalid filter range")}return{type:b.Subscribe,id:A,trackAlias:t,namespace:e,name:g,subscriberPriority:B,groupOrder:C,filterType:Q,params:o}})}function Xd(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.trackAlias),yield ZQ(i,A.namespace),yield i.writeString(A.name),yield i.writeUnsigned8(A.subscriberPriority),yield Na(i,A.groupOrder),yield Vd(i,A.filterType),yield AI(i,A.params)})}const XQ={TrackEnded:3,Expired:6};function jd(i){return r(this,null,function*(){const A=yield i.readBigVarInt(),t=yield i.readVarInt(),e=yield i.readString(),g=(yield i.readUnsigned8())==1;let B;return g&&(B={group:yield i.readBigVarInt(),object:yield i.readBigVarInt()}),{type:b.SubscribeDone,id:A,errorCode:t,reason:e,finalInfo:B}})}function zd(i,A){return r(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 _d(i){return r(this,null,function*(){return{type:b.SubscribeError,id:yield i.readBigVarInt(),errorCode:yield i.readBigVarInt(),reason:yield i.readString(),trackAlias:yield i.readBigVarInt()}})}function $d(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.errorCode),yield i.writeString(A.reason),yield i.writeBigVarInt(A.trackAlias)})}function Al(i){return r(this,null,function*(){const A=yield i.readBigVarInt(),t=yield i.readBigVarInt(),e=yield Ua(i),g=(yield i.readUnsigned8())==1;let B;if(e=="inherit-publisher")throw new Error("SusbcribeOk cannot have inherit publisher group order");g&&(B={group:yield i.readBigVarInt(),object:yield i.readBigVarInt()});const C=yield $i(i);return{type:b.SubscribeOk,id:A,groupOrder:e,expires:t,largestInfo:B,params:C}})}function tl(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.expires),yield Na(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 AI(i,A.params)})}function el(i){return r(this,null,function*(){const A=yield i.readBigVarInt(),t=yield i.readBigVarInt(),e=yield i.readBigVarInt(),g=yield i.readBigVarInt(),B=yield i.readBigVarInt(),C=yield i.readUnsigned8(),Q=yield $i(i),o=t>g,a=t===g&&e>B;if(o||a)throw new Error("Invalid filter range");return{type:b.SubscribeUpdate,id:A,start:{group:t,object:e},end:{group:g,object:B},subscriberPriority:C,params:Q}})}function il(i,A){return r(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 AI(i,A.params)})}const Il={Subscriber:2},gC={Role:v(0)},ba={Draft07:4278190087};function La(i){return r(this,null,function*(){const A=yield i.readVarInt();switch(A){case ba.Draft07:return{type:"known",value:A};default:return{type:"unknown",value:A}}})}function gl(i,A){return r(this,null,function*(){yield i.writeVarInt(A.supportedVersions.length);for(const t of A.supportedVersions)yield i.writeVarInt(t.value);yield AI(i,A.parameters)})}function sl(i){return r(this,null,function*(){const A=[],t=yield i.readVarInt();for(let g=0;g<t;g++)A.push(yield La(i));const e=yield $i(i);if(!e.has(gC.Role))throw new Error("Role parameter is required");return{type:b.ClientSetup,supportedVersions:A,parameters:e}})}function Bl(i,A){return r(this,null,function*(){yield i.writeVarInt(A.selectedVersion.value),yield AI(i,A.parameters)})}function Cl(i){return r(this,null,function*(){const A=yield La(i);if(A.type!=="known")throw new Error("Expected known version");const t=yield $i(i);if(!t.has(gC.Role))throw new Error("Role parameter is required");return{type:b.ServerSetup,selectedVersion:A,parameters:t}})}function Ql(i){return r(this,null,function*(){return{type:b.Unsubscribe,id:yield i.readBigVarInt()}})}function ol(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id)})}class Ja{constructor(A){n(this,hA);n(this,$t);n(this,wI,new Uint8Array);E(this,$t,A)}write(A){return r(this,null,function*(){yield s(this,$t).writeVarInt(A.type);const t=new kg({close:()=>{},readyState:Da.OPEN,send:e=>{E(this,wI,new Uint8Array(e))}});switch(A.type){case b.Subscribe:yield d(this,hA,er).call(this,t,A);break;case b.Announce:yield d(this,hA,Cr).call(this,t,A);break;case b.SubscribeOk:yield d(this,hA,ir).call(this,t,A);break;case b.SubscribeUpdate:yield d(this,hA,gr).call(this,t,A);break;case b.SubscribeError:yield d(this,hA,Ir).call(this,t,A);break;case b.SubscribeDone:yield d(this,hA,sr).call(this,t,A);break;case b.Unsubscribe:yield d(this,hA,Br).call(this,t,A);break;case b.ClientSetup:yield d(this,hA,Ar).call(this,t,A);break;case b.ServerSetup:yield d(this,hA,tr).call(this,t,A);break;case b.AnnounceOk:yield d(this,hA,Qr).call(this,t,A);break;default:throw new Error(`Unknown message type: ${A.type}`)}yield t.flush(),yield s(this,$t).writeVarInt(s(this,wI).byteLength),yield s(this,$t).write(s(this,wI)),yield s(this,$t).flush()})}close(){return r(this,null,function*(){return s(this,$t).close()})}}$t=new WeakMap,wI=new WeakMap,hA=new WeakSet,Ar=function(A,t){return r(this,null,function*(){yield gl(A,t)})},tr=function(A,t){return r(this,null,function*(){yield Bl(A,t)})},er=function(A,t){return r(this,null,function*(){yield Xd(A,t)})},ir=function(A,t){return r(this,null,function*(){yield tl(A,t)})},Ir=function(A,t){return r(this,null,function*(){yield $d(A,t)})},gr=function(A,t){return r(this,null,function*(){yield il(A,t)})},sr=function(A,t){return r(this,null,function*(){yield zd(A,t)})},Br=function(A,t){return r(this,null,function*(){yield ol(A,t)})},Cr=function(A,t){return r(this,null,function*(){yield Td(A,t)})},Qr=function(A,t){return r(this,null,function*(){yield xd(A,t)})};class nl{constructor(A,t){n(this,DI);n(this,Ss);n(this,ys);E(this,DI,A),E(this,Ss,new Ja(A)),E(this,ys,t)}write(A){return r(this,null,function*(){yield s(this,DI).write(s(this,ys)),yield s(this,Ss).write(A)})}close(){return s(this,DI).close()}}DI=new WeakMap,Ss=new WeakMap,ys=new WeakMap;function al(i){return r(this,null,function*(){return{type:b.AnnounceError,namespace:yield iC(i),errorCode:yield i.readBigVarInt(),reason:yield i.readString()}})}function El(i,A,t){return r(this,null,function*(){return{type:b.Unknown,messageType:A,payload:yield i.read(t)}})}class Ma{constructor(A){n(this,fA);E(this,fA,A)}cancel(){return s(this,fA).close()}read(){return r(this,null,function*(){const A=yield s(this,fA).readVarInt(),t=yield s(this,fA).readVarInt();switch(A){case b.ServerSetup:return Cl(s(this,fA));case b.ClientSetup:return sl(s(this,fA));case b.Subscribe:return Zd(s(this,fA));case b.SubscribeOk:return Al(s(this,fA));case b.SubscribeDone:return jd(s(this,fA));case b.SubscribeError:return _d(s(this,fA));case b.SubscribeUpdate:return el(s(this,fA));case b.Unsubscribe:return Ql(s(this,fA));case b.Announce:return Yd(s(this,fA));case b.AnnounceOk:return Pd(s(this,fA));case b.AnnounceError:return al(s(this,fA))}return El(s(this,fA),v(A),t)})}}fA=new WeakMap;const yI=class yI{constructor(A,t){n(this,UC);n(this,fs);n(this,mI);n(this,SI,new $);n(this,ps,new $);E(this,fs,A),E(this,mI,t),s(this,SI).resolve()}write(A){return r(this,null,function*(){const t=yield d(this,UC,or).call(this);try{yield s(this,fs).write(A)}finally{t.resolve()}})}markPostHandshake(){s(this,ps).resolve()}postHandshake(){return s(this,ps).promise}read(){return r(this,null,function*(){return s(this,mI).read()})}cancel(){return s(this,mI).cancel()}static wrapWebsocket(A){const t=new ReadableStream(new Hd(A,s(yI,NC))),e=new Ma(new tC(new Uint8Array([]),t)),g=new nl(new kg(A),new Uint8Array([0]));return new yI(g,e)}static wrapWebTransport(A){const t=A.writable,e=A.readable;return new yI(new Ja(new wa(t)),new Ma(new tC(new Uint8Array,e)))}};fs=new WeakMap,mI=new WeakMap,SI=new WeakMap,ps=new WeakMap,UC=new WeakSet,or=function(){const A=new $,t=s(this,SI).promise.then(()=>A);return E(this,SI,A),t},NC=new WeakMap,n(yI,NC,0);let sC=yI;function Ha(i,A){return r(this,null,function*(){yield i.write({type:b.ClientSetup,supportedVersions:[{type:"known",value:ba.Draft07}],parameters:new Map([[gC.Role,{type:gC.Role,payload:new Uint8Array([A])}]])});const t=yield i.read();if(i.markPostHandshake(),t.type!==b.ServerSetup)throw new Error("Expected server setup message");if(t.selectedVersion.type!=="known")throw new Error("Expected known version")})}class rl{constructor(A){I(this,"announce");n(this,fI,new $);this.announce=A}onOk(A){s(this,fI).resolve(A)}onError(A){const t=new Error(A.reason);return s(this,fI).reject(t),t}ok(){return s(this,fI).promise}}fI=new WeakMap;function cl(i){const A=new rl(i);return new hl(A)}class hl{constructor(A){I(this,"state");this.state=A}}const FI=class FI{constructor(A){I(this,"subscribe");n(this,pI,new $);n(this,fe,new $);n(this,li,new $);n(this,bC,Date.now());n(this,ui,new $);n(this,lt);switch(this.subscribe=A,A.filterType.type){case"absolute-start":E(this,lt,{startGroup:A.filterType.start.group});break;case"absolute-range":E(this,lt,{startGroup:A.filterType.start.group,endGroup:A.filterType.end.group});break}}onUpdate(A){E(this,lt,{startGroup:A.start.group}),A.end.group>v(0)&&(s(this,lt).endGroup=A.end.group-v(1))}onError(A){const t=new Error(A.reason);return s(this,pI).reject(t),s(this,fe).reject(t),t}onDone(A){A.finalInfo&&(s(this,lt)||E(this,lt,{startGroup:v(0)}),s(this,lt).endGroup=A.finalInfo.group),s(this,fe).resolve(A)}onUnsubscribe(A){s(this,li).resolve(A)}onOk(A){const t=Math.max(0,Date.now()-s(this,bC)),e=Number(A.expires);if(e>0){const g=Math.max(FI.minGraceTime,Math.min(e/10,FI.maxGraceTime));Promise.race([ce(e-g-t),this.done().catch(F)]).then(()=>s(this,ui).resolve(this.expiryState())).catch(F)}s(this,pI).resolve(A)}done(){return s(this,fe).promise}ok(){return s(this,pI).promise}range(){return s(this,lt)}close(){s(this,ui).promise.catch(F),s(this,ui).reject(new Error("Subscription closed"))}expiryState(){return s(this,fe).resolved&&s(this,fe).resolved.errorCode!==XQ.Expired?"done":s(this,li).pending?"active":"unsubscribed"}unsubscribed(){return s(this,li).promise}isUnsubscribed(){return s(this,li).resolved}expiryNotification(){return s(this,ui).promise}};pI=new WeakMap,fe=new WeakMap,li=new WeakMap,bC=new WeakMap,ui=new WeakMap,lt=new WeakMap,I(FI,"maxGraceTime",15e3),I(FI,"minGraceTime",3e3);let BC=FI;class dl{constructor(A){n(this,MA);n(this,Fs,!1);E(this,MA,A)}write(A){return r(this,null,function*(){s(this,Fs)||(yield s(this,MA).writeVarInt(AC.StreamHeaderGroup),yield s(this,MA).writeBigVarInt(A.subscribeId),yield s(this,MA).writeBigVarInt(A.trackAlias),yield s(this,MA).writeBigVarInt(A.groupId),yield s(this,MA).writeBigVarInt(A.subGroupId),yield s(this,MA).writeUnsigned8(A.subscriberPriority),E(this,Fs,!0)),yield s(this,MA).writeBigVarInt(A.objectId),yield s(this,MA).writeVarInt(A.payload.length),A.payload.length>0?yield s(this,MA).write(A.payload):yield s(this,MA).writeVarInt(A.objectStatus),yield s(this,MA).flush()})}close(){return r(this,null,function*(){yield s(this,MA).close()})}}MA=new WeakMap,Fs=new WeakMap;class ll{constructor(A,t,e,g){n(this,LC);n(this,Gs);n(this,gt);n(this,ks);n(this,Rs);n(this,GI);n(this,Us);E(this,Gs,t),E(this,gt,A),E(this,ks,e),E(this,Rs,g),E(this,Us,UA.get().createContext(`SubscriptionWriter:${A.subscribe.name}`))}finalInfo(){return s(this,GI)}run(){return r(this,null,function*(){yield Promise.race([d(this,LC,nr).call(this).catch(A=>s(this,Us).error("error writing subscription",A)),s(this,gt).unsubscribed(),s(this,gt).done(),s(this,gt).expiryNotification().catch(F)])})}done(A,t){return r(this,null,function*(){if(s(this,gt).isUnsubscribed())return;const e={type:b.SubscribeDone,id:s(this,gt).subscribe.id,errorCode:A,reason:t,finalInfo:s(this,GI)};s(this,gt).onDone(e),yield s(this,Rs).push(e)})}[pt()](){return this.done(XQ.TrackEnded,"Track ended")}[Symbol.asyncDispose](){return this.done(XQ.TrackEnded,"Track ended")}}Gs=new WeakMap,gt=new WeakMap,ks=new WeakMap,Rs=new WeakMap,GI=new WeakMap,Us=new WeakMap,LC=new WeakSet,nr=function(){return r(this,null,function*(){try{for(var C=rA(s(this,Gs)),Q,o,a;Q=!(o=yield C.next()).done;Q=!1){const c=o.value;var A=[];try{const h=s(this,gt).range();if(h&&(h.startGroup>c.id||h.endGroup&&h.endGroup<c.id))break;const l=yield s(this,ks).openSendStream();const m=new dl(l);const y=ot(A,new ul(m,c.consume(),s(this,gt)),!0);yield y.run();E(this,GI,y.finalGroup())}catch(t){var e=t,g=!0}finally{var B=nt(A,e,g);B&&(yield B)}}}catch(o){a=[o]}finally{try{Q&&(o=C.return)&&(yield o.call(C))}finally{if(a)throw a[0]}}})};class ul{constructor(A,t,e){n(this,wi);n(this,Ns);n(this,kI);n(this,bs);n(this,RI);E(this,wi,A),E(this,Ns,t),E(this,kI,e),E(this,RI,UA.get().createContext(`GroupSubscriptionWriter:${e.subscribe.name}`))}finalGroup(){return s(this,bs)}run(){return r(this,null,function*(){s(this,RI).debug("write group");try{for(var A=rA(s(this,Ns)),t,e,g;t=!(e=yield A.next()).done;t=!1){const B=e.value;yield s(this,wi).write({subscribeId:s(this,kI).subscribe.id,trackAlias:s(this,kI).subscribe.trackAlias,subGroupId:v(0),subscriberPriority:0,groupId:B.groupId,objectId:B.objectId,objectStatus:B.objectStatus,payload:B.payload}),E(this,bs,{group:B.groupId,object:B.objectId})}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}s(this,RI).debug("write group done")})}[pt()](){return s(this,wi).close().catch(F)}[Symbol.asyncDispose](){return s(this,wi).close().catch(F)}}wi=new WeakMap,Ns=new WeakMap,kI=new WeakMap,bs=new WeakMap,RI=new WeakMap;class wl{constructor(A,t,e){n(this,pe);I(this,"state");n(this,Ls);n(this,Di);this.state=A,E(this,Ls,t),E(this,Di,e)}ok(A){return r(this,null,function*(){var o,a,c;const t=(o=this.state.range())==null?void 0:o.startGroup,e=A.latest(),g=e==null?void 0:e.id,B=(c=(a=e==null?void 0:e.latest())==null?void 0:a.objectId)!=null?c:v(0),C=A.consume(t!=null?t:g),Q={type:b.SubscribeOk,id:this.state.subscribe.id,expires:v(0),groupOrder:"ascending",params:new Map,largestInfo:g?{group:g,object:B}:void 0};return yield s(this,Di).push(Q),new ll(this.state,C,s(this,Ls),s(this,Di))})}invalidRange(){return d(this,pe,ug).call(this,v(1),"Invalid range")}retryTrackAlias(){return d(this,pe,ug).call(this,v(2),"Retry track alias")}trackDoesNotExist(){return d(this,pe,ug).call(this,v(3),"Track does not exist")}unauthorized(){return d(this,pe,ug).call(this,v(4),"Unauthorized")}timeout(){return d(this,pe,ug).call(this,v(5),"Timeout")}[pt()](){return this.trackDoesNotExist()}[Symbol.asyncDispose](){return this.trackDoesNotExist()}}Ls=new WeakMap,Di=new WeakMap,pe=new WeakSet,ug=function(A,t){const e={type:b.SubscribeError,id:this.state.subscribe.id,errorCode:A,reason:t,trackAlias:this.state.subscribe.trackAlias};return s(this,Di).push(e)},yE=[ZA({context:"Session",enter:"info",error:"error"})];class jQ{constructor(A,t,e){Oi(Oo,5,this);n(this,UI);n(this,Js);n(this,NI);n(this,mi,UA.get().createContext("Publisher"));n(this,Fe,new vA(new Map));n(this,Ge,new vA(new Map));n(this,ke,new We(10));E(this,UI,A),E(this,Js,t),E(this,NI,e)}announce(A){return r(this,null,function*(){if(s(this,Fe).current().has(A.join("/")))throw new Error("Duplicate announcement");const t=new Map,e=s(this,UI).authToken();e&&t.set(IC,{type:IC,payload:new TextEncoder().encode(e)});const g={type:b.Announce,namespace:A,params:t},B=cl(g);if(s(this,Fe).update(Q=>Q.set(g.namespace.join("/"),B)),yield s(this,NI).push(g),!(yield Promise.race([B.state.ok(),s(this,UI).closed()])))throw new Error("Session closed")})}close(){s(this,Ge).current().forEach(A=>A.close()),s(this,Ge).close(),s(this,Fe).close(),s(this,ke).close()}incomingSubscriptions(){return s(this,ke)}onMessage(A){return r(this,null,function*(){switch(A.type){case b.Subscribe:{const t=new BC(A);if(s(this,Ge).update(e=>(e.set(A.id,t),e)),s(this,ke).isFull()){const e=yield s(this,ke).pop();yield e==null?void 0:e.timeout()}yield s(this,ke).push(new wl(t,s(this,Js),s(this,NI)))}break;case b.SubscribeUpdate:{const t=s(this,Ge).current().get(A.id);t||s(this,mi).debug("No subscription found",A),t==null||t.onUpdate(A)}break;case b.Unsubscribe:{const t=s(this,Ge).current().get(A.id);t||s(this,mi).debug("No subscription found",A),t==null||t.onUnsubscribe(A)}break;case b.AnnounceOk:{const t=s(this,Fe).current().get(A.namespace.join("/"));t||s(this,mi).debug("No announcement found",A),t==null||t.state.onOk(A)}break;case b.AnnounceError:{const t=s(this,Fe).current().get(A.namespace.join("/"));t||s(this,mi).debug("No announcement found",A),t==null||t.state.onError(A)}break}})}}Oo=Wi(null),UI=new WeakMap,Js=new WeakMap,NI=new WeakMap,mi=new WeakMap,Fe=new WeakMap,Ge=new WeakMap,ke=new WeakMap,OA(Oo,1,"announce",yE,jQ),Te(Oo,jQ);function Dl(i,A){const t=new BC(A),[e,g]=xe(100),B=new ml(t,e),C=new qa(i,t,g);return[B,C]}class ml{constructor(A,t){I(this,"state");n(this,Si);this.state=A,E(this,Si,t)}onDone(A){this.state.onDone(A)}onData(A){return s(this,Si).push(A)}onError(A){const t=this.state.onError(A);s(this,Si).abort(t)}close(){this.state.close(),s(this,Si).close()}}Si=new WeakMap;class qa{constructor(A,t,e){Oi(Vo,5,this);n(this,MI);n(this,bI);n(this,kA);n(this,LI);n(this,JI,new $);E(this,bI,A),E(this,kA,t),E(this,LI,e)}get id(){return s(this,kA).subscribe.id}get trackAlias(){return s(this,kA).subscribe.trackAlias}get name(){return s(this,kA).subscribe.name}range(){return s(this,kA).range()}expiryNotification(){return s(this,kA).expiryNotification()}update(A,t){return r(this,null,function*(){const e={type:b.SubscribeUpdate,id:s(this,kA).subscribe.id,start:{group:A,object:v(0)},end:{group:t+v(1),object:v(0)},params:new Map,subscriberPriority:0};s(this,kA).onUpdate(e),yield s(this,bI).push(e)})}unsubscribe(){return r(this,null,function*(){const A={type:b.Unsubscribe,id:s(this,kA).subscribe.id};s(this,kA).onUnsubscribe(A),yield s(this,bI).push(A)})}close(){var A,t;return s(this,JI).resolve(),(t=(A=s(this,LI)).return)==null?void 0:t.call(A)}closed(){return s(this,JI).promise}done(){return s(this,kA).done()}expiryState(){return s(this,kA).expiryState()}unsubscribed(){return s(this,kA).isUnsubscribed()}return(){return r(this,null,function*(){return s(this,JI).resolve(),yield this.unsubscribe(),{done:!0,value:void 0}})}groups(){return Ee(this,null,function*(){var A,t;try{for(var m=rA(s(this,LI)),y,f,k;y=!(f=yield new EA(m.next())).done;y=!1){var Q=f.value;var o=[];try{const q=ot(o,Q,!0);try{for(var e=rA(q.groups()),g,B,C;g=!(B=yield new EA(e.next())).done;g=!1){const U=B.value;const H=(A=s(this,kA).range())==null?void 0:A.startGroup,T=(t=s(this,kA).range())==null?void 0:t.endGroup;if(H&&U.groupId()<H)return{done:!0,value:void 0};if(T&&U.groupId()>T)return{done:!0,value:void 0};yield U}}catch(B){C=[B]}finally{try{g&&(B=e.return)&&(yield new EA(B.call(e)))}finally{if(C)throw C[0]}}}catch(a){var c=a,h=!0}finally{var l=nt(o,c,h);l&&(yield new EA(l))}}}catch(f){k=[f]}finally{try{y&&(f=m.return)&&(yield new EA(f.call(m)))}finally{if(k)throw k[0]}}})}[Symbol.asyncIterator](){return this.groups()}objects(){return Ee(this,null,function*(){try{for(var B=rA(this.groups()),C,Q,o;C=!(Q=yield new EA(B.next())).done;C=!1){const a=Q.value;try{for(var A=rA(a),t,e,g;t=!(e=yield new EA(A.next())).done;t=!1){const c=e.value;yield c}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield new EA(e.call(A)))}finally{if(g)throw g[0]}}}}catch(Q){o=[Q]}finally{try{C&&(Q=B.return)&&(yield new EA(Q.call(B)))}finally{if(o)throw o[0]}}})}[(fE=[ZA({context:"SubscriptionConsumer",enter:"info"})],pt())](){return d(this,MI,fB).call(this)}[Symbol.asyncDispose](){return d(this,MI,fB).call(this)}}Vo=Wi(null),bI=new WeakMap,kA=new WeakMap,LI=new WeakMap,JI=new WeakMap,MI=new WeakSet,fB=function(){return r(this,null,function*(){return yield this.close(),this.unsubscribe()})},fB=OA(Vo,17,"#dispose",fE,MI,fB),Te(Vo,qa);const Sl=2e3;kE=[ZA({context:"Session",return:"debug"})],GE=[ZA({context:"Session",enter:"info",error:"error"})],FE=[ZA({context:"Session",enter:"debug"})],pE=[ZA({context:"Session",enter:"debug"})];class CC{constructor(A,t){Oi(HI,5,this);n(this,Lt);n(this,Ae);I(this,"nextSubscribeId",v(0));n(this,_A,new vA(new Map));n(this,yi);n(this,fi,UA.get().createContext("Subscriber"));E(this,Ae,A),E(this,yi,t),d(this,Lt,uQ).call(this).catch(F)}subscribe(g,B){return r(this,arguments,function*(A,t,e=new Map){const C=this.nextSubscribeId++,Q=s(this,Ae).authToken();Q&&e.set(IC,{type:IC,payload:new TextEncoder().encode(Q)});const o={type:b.Subscribe,namespace:A,name:t.name,id:C,trackAlias:C,groupOrder:t.groupOrder,subscriberPriority:t.priority,filterType:t.filterType,params:e},[a,c]=Dl(s(this,yi),o);if(s(this,_A).update(l=>l.set(C,a)),yield s(this,yi).push(o),!(yield Promise.race([a.state.ok(),s(this,Ae).closed()])))throw new Error("Session closed");return c.closed().then(()=>Promise.race([ce(Sl),this.closed()])).then(()=>d(this,Lt,wg).call(this,c.id)).catch(()=>d(this,Lt,wg).call(this,c.id)),c})}closed(){return s(this,Ae).closed()}transportType(){return s(this,Ae).transportType()}url(){return s(this,Ae).url()}onMessage(A){return r(this,null,function*(){switch(A.type){case b.Announce:yield s(this,yi).push({type:b.AnnounceOk,namespace:A.namespace});break;case b.SubscribeOk:{const t=s(this,_A).current().get(A.id);t&&t.state.onOk(A)}break;case b.SubscribeError:{const t=s(this,_A).current().get(A.id);t||s(this,fi).debug("No subscription found",A),t==null||t.onError(A),d(this,Lt,wg).call(this,A.id)}break;case b.SubscribeDone:{const t=s(this,_A).current().get(A.id);t||s(this,fi).debug("No subscription found",A),t==null||t.onDone(A)}break}})}onObjectReader(A){return r(this,null,function*(){const t=s(this,_A).current().get(A.subscribeId());if(!t){s(this,fi).warn("No subscription found",A.subscribeId());return}yield t.onData(A)})}close(){s(this,_A).current().forEach(A=>A.close()),s(this,_A).close()}}HI=Wi(null),Ae=new WeakMap,_A=new WeakMap,yi=new WeakMap,fi=new WeakMap,Lt=new WeakSet,uQ=function(){return r(this,null,function*(){try{for(var A=rA(s(this,_A)),t,e,g;t=!(e=yield A.next()).done;t=!1){const B=e.value;const C=[...B.values()].map(Q=>Q.state.subscribe);s(this,fi).debug("current subscriptions",C)}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}})},wg=function(A){s(this,_A).isClosed()||s(this,_A).update(t=>(t.delete(A),t))},uQ=OA(HI,17,"#observeChanges",kE,Lt,uQ),OA(HI,1,"subscribe",GE,CC),OA(HI,1,"close",FE,CC),wg=OA(HI,17,"#deleteSubscription",pE,Lt,wg),Te(HI,CC);class zQ{constructor(A,t){Oi(KI,5,this);n(this,pA);n(this,ut);n(this,Ms);n(this,pi);n(this,qI,UA.get().createContext("Session"));I(this,"subscriber");I(this,"publisher");n(this,vI);const[e,g]=xe(100);E(this,ut,A),E(this,pi,g),this.subscriber=new CC(this,e),this.publisher=new jQ(this,A,e),E(this,Ms,d(this,pA,Er).call(this)),E(this,vI,new vA(t)),this.closed().then(()=>this.close()).catch(F)}updateAuthToken(A){s(this,vI).update(A)}authToken(){return s(this,vI).current()}transportType(){return s(this,ut).transportType()}url(){return s(this,ut).url()}closed(){return s(this,Ms)}close(){try{this.subscriber.close(),this.publisher.close(),s(this,pi).cancel("closing"),s(this,ut).close()}catch(A){s(this,qI).warn("Error closing session",A)}}[(bE=[ZA({context:"Session",return:"info",error:"error"})],NE=[ZA({context:"Session",return:"info",error:"error"})],UE=[ZA({context:"Session",return:"info",error:"error"})],RE=[ZA({context:"Session",enter:"debug"})],mn())](){d(this,pA,pB).call(this)}[Symbol.dispose](){d(this,pA,pB).call(this)}}KI=Wi(null),ut=new WeakMap,Ms=new WeakMap,pi=new WeakMap,qI=new WeakMap,vI=new WeakMap,pA=new WeakSet,ar=function(A){return r(this,null,function*(){var t,e;switch(s(this,qI).debug("received message",A),yield(t=this.subscriber)==null?void 0:t.onMessage(A),yield(e=this.publisher)==null?void 0:e.onMessage(A),A.type){case b.Goaway:break}})},Er=function(){return r(this,null,function*(){return(yield Promise.all([d(this,pA,DQ).call(this),d(this,pA,mQ).call(this),d(this,pA,wQ).call(this)])).find(t=>t instanceof Error)})},wQ=function(){return r(this,null,function*(){try{try{for(var A=rA(s(this,pi)),t,e,g;t=!(e=yield A.next()).done;t=!1){const B=e.value;s(this,qI).debug("sending message",B),yield s(this,ut).writeMessage(B)}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}}catch(B){return B}})},DQ=function(){return r(this,null,function*(){try{for(yield s(this,ut).afterHandshake();;){const A=yield s(this,ut).readMessage().catch(()=>{});if(!A)break;yield d(this,pA,ar).call(this,A)}}catch(A){return A}finally{s(this,pi).cancel("closing")}})},mQ=function(){return r(this,null,function*(){var A;try{for(;;){const t=yield s(this,ut).objectStream();if(!t)break;yield(A=this.subscriber)==null?void 0:A.onObjectReader(t)}}catch(t){return t}})},pB=function(){this.close()},wQ=OA(KI,17,"#runOutgoingMessages",bE,pA,wQ),DQ=OA(KI,17,"#runControl",NE,pA,DQ),mQ=OA(KI,17,"#runObjects",UE,pA,mQ),pB=OA(KI,17,"#dispose",RE,pA,pB),Te(KI,zQ);const yl=128;class fl{constructor(A,t,e){n(this,HA);n(this,st);n(this,Hs);n(this,Fi,!0);n(this,YI,!1);n(this,qs);E(this,st,A),E(this,Hs,t),E(this,qs,e)}writeUnsigned8(A){return r(this,null,function*(){return d(this,HA,Zi).call(this),yield d(this,HA,Xi).call(this),s(this,st).writeUnsigned8(A)})}writeVarInt(A){return r(this,null,function*(){return d(this,HA,Zi).call(this),yield d(this,HA,Xi).call(this),s(this,st).writeVarInt(A)})}writeBigVarInt(A){return r(this,null,function*(){return d(this,HA,Zi).call(this),yield d(this,HA,Xi).call(this),s(this,st).writeBigVarInt(A)})}write(A){return r(this,null,function*(){return d(this,HA,Zi).call(this),yield d(this,HA,Xi).call(this),s(this,st).write(A)})}writeString(A){return r(this,null,function*(){return d(this,HA,Zi).call(this),yield d(this,HA,Xi).call(this),s(this,st).writeString(A)})}flush(){return r(this,null,function*(){d(this,HA,Zi).call(this),E(this,Fi,!0),yield s(this,st).flush()})}close(){return r(this,null,function*(){s(this,YI)||(E(this,Fi,!0),yield d(this,HA,Xi).call(this,!1),yield s(this,st).flush(),E(this,YI,!0),s(this,qs).call(this))})}}st=new WeakMap,Hs=new WeakMap,Fi=new WeakMap,YI=new WeakMap,qs=new WeakMap,HA=new WeakSet,Zi=function(){if(s(this,YI))throw new Error("Stream is closed")},Xi=function(A=!0){if(s(this,Fi))return E(this,Fi,!1),s(this,st).writeUnsigned8(s(this,Hs)|(A?yl:0))};class pl{constructor(A,t){n(this,JC);n(this,Re);n(this,te);n(this,TI);n(this,Gi);n(this,ee,new Map);n(this,PI,UA.get().createContext("WebSocketConnection"));n(this,xI,new Set(new Array(128).fill(0).map((A,t)=>t+1)));E(this,Re,A),E(this,te,t),E(this,TI,new ReadableStream(new qd(A))),s(this,Re).addEventListener("close",()=>{s(this,te).markPostHandshake(),s(this,ee).forEach(e=>e.close())})}openSendStream(){const A=s(this,xI).values().next().value;if(!A)throw new Error("No stream IDs available");return s(this,xI).delete(A),Promise.resolve(new fl(new kg(s(this,Re)),A,()=>d(this,JC,rr).call(this,A)))}transportType(){return"websocket"}url(){return s(this,Re).url}afterHandshake(){return s(this,te).postHandshake()}objectStream(){return r(this,null,function*(){var A;for(;;){E(this,Gi,s(this,TI).getReader());try{const{value:t,done:e}=yield s(this,Gi).read();if(e)return;const[g,B,C]=t;if(s(this,ee).has(v(B))){const Q=s(this,ee).get(v(B));if(!Q)throw new Error("Stream not found");C.length>0&&(yield Q.push(C)),g||(s(this,PI).debug("Closing stream",{streamId:B}),Q.close(),s(this,ee).delete(v(B)))}else{let c;s(this,PI).debug("Creating new stream",{streamId:B});const[Q,o]=xe(1e3),a=new ReadableStream({pull(h){return r(this,null,function*(){const l=yield o.pop();l?h.enqueue(l):h.close()})}});if(s(this,ee).set(v(B),Q),g||(s(this,PI).debug("Closing new stream",{streamId:B}),yield a.cancel(),s(this,ee).delete(v(B))),C.length>0)return yield ua(new tC(C,a),B)}}finally{(A=s(this,Gi))==null||A.releaseLock()}}})}close(){var A;return s(this,te).cancel().catch(F),s(this,TI).cancel("closing").catch(F),(A=s(this,Gi))==null||A.cancel("closing").catch(F),s(this,Re).close()}closed(){return Promise.resolve()}writeMessage(A){return r(this,null,function*(){yield s(this,te).write(A)})}readMessage(){return r(this,null,function*(){return s(this,te).read()})}}Re=new WeakMap,te=new WeakMap,TI=new WeakMap,Gi=new WeakMap,ee=new WeakMap,PI=new WeakMap,xI=new WeakMap,JC=new WeakSet,rr=function(A){s(this,xI).add(A)};class Fl{constructor(A,t,e){n(this,HC);n(this,ie);n(this,Ie);n(this,Ue,new We(100));n(this,vs);n(this,Ks,0);n(this,MC,UA.get().createContext("WebTransportConnection"));E(this,vs,e),E(this,ie,A),E(this,Ie,t),d(this,HC,cr).call(this).catch(g=>{s(this,MC).debug("Incoming streams handling ended with error",g),s(this,Ie).markPostHandshake(),s(this,Ue).close()}),s(this,ie).closed.then(()=>{s(this,Ie).markPostHandshake(),s(this,Ue).close()})}openSendStream(){return r(this,null,function*(){const A=yield s(this,ie).createUnidirectionalStream();return new wa(A)})}transportType(){return"webtransport"}url(){return s(this,vs)}afterHandshake(){return s(this,Ie).postHandshake()}closed(){return r(this,null,function*(){yield s(this,ie).closed})}close(){s(this,ie).close()}writeMessage(A){return r(this,null,function*(){yield s(this,Ie).write(A)})}readMessage(){return r(this,null,function*(){return s(this,Ie).read()})}objectStream(){return r(this,null,function*(){return s(this,Ue).pop()})}}ie=new WeakMap,Ie=new WeakMap,Ue=new WeakMap,vs=new WeakMap,Ks=new WeakMap,MC=new WeakMap,HC=new WeakSet,cr=function(){return r(this,null,function*(){const A=s(this,ie).incomingUnidirectionalStreams.getReader();for(;;){const{value:t,done:e}=yield A.read();if(e){s(this,Ue).close();return}const g=new tC(new Uint8Array,t);yield s(this,Ue).push(ua(g,s(this,Ks))),ft(this,Ks)._++}})};function _Q(i){return r(this,null,function*(){const A=new WebSocket(i.wsUrl||i.url);A.binaryType="arraybuffer",yield new Promise((B,C)=>{A.addEventListener("error",()=>C(new Error("WebSocket error")),{once:!0}),A.addEventListener("open",B,{once:!0})});const t=sC.wrapWebsocket(A);Ha(t,i.role).catch(()=>{A.close()});const e=new pl(A,t);return new zQ(e,i.authToken)})}function Gl(i){return r(this,null,function*(){const A="60b82e8021689e163c1041b4475ef9c86e7565bc45d1a0aa43f5148769f461c7",t=new Uint8Array(A.length/2);for(let o=0;o<t.length;o+=1)t[o]=parseInt(A.slice(2*o,2*o+2),16);const e=new WebTransport(i.url,{congestionControl:"low-latency"});yield Promise.race([e.ready,e.closed.then(()=>Promise.reject(new Error("WebTransport closed")))]);const g=yield e.createBidirectionalStream(),B=sC.wrapWebTransport(g);Ha(B,i.role).catch(()=>{e.close()});const C=new Fl(e,B,i.url.toString());return new zQ(C,i.authToken)})}function kl(i){return r(this,null,function*(){if(self.WebTransport&&(i==null?void 0:i.preferredTransport)!=="websocket"&&i.url.protocol.startsWith("https")){const A=Gl(i).catch(()=>_Q(i)),t=yield Promise.race([A,ce(i.websocketFallbackTimeoutMs)]);return t||_Q(i)}return _Q(i)})}class Vt{constructor(){n(this,ge,{name:"",priority:0,groupOrder:"ascending",filterType:{type:"latest-group"}})}name(A){return s(this,ge).name=A,this}priority(A){return s(this,ge).priority=A,this}groupOrder(A){return s(this,ge).groupOrder=A,this}startGroup(A){return s(this,ge).filterType={type:"absolute-start",start:{group:A,object:v(0)}},this}range(A,t){return s(this,ge).filterType={type:"absolute-range",start:{group:A,object:v(0)},end:{group:t,object:v(0)}},this}build(){return s(this,ge)}}ge=new WeakMap;class va{constructor(A,t){n(this,WI);n(this,Ys);E(this,WI,A),E(this,Ys,t)}subscribe(A,t=new Map){return s(this,WI).subscribe(this.namespace(),A,t)}closed(){return s(this,WI).closed()}namespace(){return s(this,Ys).namespace}}WI=new WeakMap,Ys=new WeakMap;function Rl(i,A){return["com.vindral.moq",i]}function $e(i){const A=i[1];if(!A)throw new Error("namespace must contain a channel ID");return A}function Ul(i){return"tracks"in i}function Nl(i){const A=new TextDecoder().decode(i);return JSON.parse(A)}const Zo=class Zo{constructor(A,t){n(this,Ps);n(this,$A);n(this,Jt);n(this,ki,new W(100));n(this,Bt);n(this,Ts);n(this,qC,A=>r(this,null,function*(){if(!A)return s(this,$A).close();if(s(this,Bt))return;const t=s(this,ki).items().reduce((e,g)=>e<g?e:g,A);E(this,Bt,d(this,Ps,an).call(this,t,A)),s(this,Bt).size===0&&(yield s(this,$A).close())}));E(this,$A,A),E(this,Jt,t),A.done().then(e=>r(this,null,function*(){var g;return s(this,qC).call(this,(g=e.finalInfo)==null?void 0:g.group)})).catch(F),E(this,Ts,A.groups())}static subscribe(A,t){return r(this,null,function*(){const e=yield A.subscribe(t);return new Zo(e,void 0)})}subscribeId(){return s(this,$A).id}name(){return s(this,$A).name}largestGroupId(){return s(this,Jt)}needsRenewal(){return s(this,$A).expiryState()==="active"&&s(this,Bt)===void 0}endOfTrack(A){const t=s(this,ki).items().reduce((e,g)=>e<g?e:g,A);return this.update(t,A)}update(A,t){return r(this,null,function*(){return E(this,Bt,d(this,Ps,an).call(this,A,t)),s(this,Bt).size===0&&(yield s(this,$A).close()),s(this,$A).update(A,t)})}unsubscribe(){return s(this,$A).unsubscribe()}next(){return r(this,null,function*(){var e;if(s(this,Bt)&&s(this,Bt).size===0)return{done:!0,value:void 0};const A=yield s(this,Ts).next();if(A.done)return A;const t=A.value.groupId();return(e=s(this,Bt))==null||e.delete(t),s(this,ki).push(t),s(this,Jt)||E(this,Jt,t),E(this,Jt,s(this,Jt)<t?t:s(this,Jt)),A})}return(){return s(this,$A).return()}[Symbol.asyncIterator](){return this}};$A=new WeakMap,Jt=new WeakMap,ki=new WeakMap,Bt=new WeakMap,Ts=new WeakMap,qC=new WeakMap,Ps=new WeakSet,an=function(A,t){const e=new Set;for(let g=A;g<=t;g++)e==null||e.add(g);return s(this,ki).items().forEach(g=>{e==null||e.delete(g)}),e};let QC=Zo;const Xo=class Xo{constructor(A){n(this,xs);n(this,wt);n(this,Ri);n(this,se,new We(10));n(this,Mt);n(this,Ws,(A,t)=>r(this,null,function*(){var h=[];try{const e=ot(h,yield s(this,wt).lock());const g={subscribeId:e.value.subscribeId()};if(!e.value.needsRenewal()){s(this,Mt).debug("Subscription does not need renewal",g);return}const B=e.value.largestGroupId();const C=B!==void 0;const Q=new Vt().name(t.name).priority(t.priority).groupOrder(t.groupOrder);g.largestGroupId=B;s(this,Mt).debug("Renewing subscription",g);switch(t.filterType.type){case"absolute-range":s(this,Mt).debug("Absolute range is not renewed",g);return;case"absolute-start":case"latest-group":case"latest-object":C&&Q.startGroup(B+v(1));break}const o=Q.build();g.newTrack=o;const[a]=yield Promise.all([A.subscribe(o),C?e.value.update(B,B):e.value.unsubscribe()]);a.done().then(()=>d(this,xs,En).call(this,a)).catch(F);a.expiryNotification().then(()=>s(this,Ws).call(this,A,o)).catch(F);const c=new QC(a,B);e.value=c;yield s(this,se).push(c);s(this,Mt).info("Subscription renewed",g)}catch(l){var m=l,y=!0}finally{nt(h,m,y)}}));E(this,wt,new _r(A)),E(this,Ri,A),E(this,Mt,UA.get().createContext(`Renewable '${A.name()}'`))}static subscribe(A,t,e){return r(this,null,function*(){const g=e==null?void 0:e.params,B=e==null?void 0:e.largestGroupId,C=yield A.subscribe(t,g),Q=new Xo(new QC(C,B));return C.done().then(()=>{var o;return d(o=Q,xs,En).call(o,C)}).catch(F),C.expiryNotification().then(()=>{var o;return s(o=Q,Ws).call(o,A,t)}).catch(F),Q})}largestGroupId(){return s(this,wt).unsafeValue().largestGroupId()}update(A,t){return r(this,null,function*(){var g=[];try{const e=ot(g,yield s(this,wt).lock());s(this,se).close();return e.value.update(A,t)}catch(B){var C=B,Q=!0}finally{nt(g,C,Q)}})}endOfTrack(A){return r(this,null,function*(){var e=[];try{const t=ot(e,yield s(this,wt).lock());s(this,se).close();return t.value.endOfTrack(A)}catch(g){var B=g,C=!0}finally{nt(e,B,C)}})}unsubscribe(){return r(this,null,function*(){var t=[];try{const A=ot(t,yield s(this,wt).lock());s(this,se).close();return A.value.unsubscribe()}catch(e){var g=e,B=!0}finally{nt(t,g,B)}})}return(){return r(this,null,function*(){var t=[];try{const A=ot(t,yield s(this,wt).lock());s(this,se).close();return A.value.return()}catch(e){var g=e,B=!0}finally{nt(t,g,B)}})}next(){return r(this,null,function*(){var t,e;const A=yield s(this,Ri).next();if(A.done){yield(e=(t=s(this,Ri)).return)==null?void 0:e.call(t);const g=yield s(this,se).pop();if(g)return E(this,Ri,g),this.next()}return A})}[Symbol.asyncIterator](){return this}objects(){return Ee(this,null,function*(){try{for(var Q=rA(this),o,a,c;o=!(a=yield new EA(Q.next())).done;o=!1){var A=a.value;var t=[];try{const h=ot(t,A,!0);yield*Bn(h)}catch(e){var g=e,B=!0}finally{var C=nt(t,g,B);C&&(yield new EA(C))}}}catch(a){c=[a]}finally{try{o&&(a=Q.return)&&(yield new EA(a.call(Q)))}finally{if(c)throw c[0]}}})}};wt=new WeakMap,Ri=new WeakMap,se=new WeakMap,Mt=new WeakMap,xs=new WeakSet,En=function(A){return r(this,null,function*(){var t;if(A.unsubscribed()||(t=A.range())!=null&&t.endGroup){s(this,Mt).info("Server initiated subscribe done but the subscription is already closing");return}if(s(this,wt).unsafeValue().subscribeId()!==A.id){s(this,Mt).info("subscribeId mismatch - the subscription already has been renewed");return}return this.return()})},Ws=new WeakMap;let de=Xo;const bl="catalog";function Ka(i){const A=Nl(i.payload);if(!Ul(A))throw new Error("unexpected catalog type");return A}const KC=class KC{constructor(A,t,e){n(this,vC);n(this,Ne);n(this,Os);n(this,Vs);n(this,Zs);E(this,Os,A),E(this,Ne,t),E(this,Vs,e),E(this,Zs,d(this,vC,hr).call(this)),this.closed().finally(()=>s(this,Ne).close()).catch(F)}catalog(){return s(this,Ne)}closed(){return s(this,Zs)}close(){return r(this,null,function*(){return s(this,Ne).close(),(yield s(this,Os).promise).unsubscribe()})}static start(A,t){return r(this,null,function*(){const e=$.fromPromise(de.subscribe(A,new Vt().name(t.catalogName||bl).groupOrder("ascending").build())),g=$.fromPromise(e.promise.then(o=>o.objects()));if(t.catalog)return new KC(e,new vA(t.catalog),g);const C=yield(yield g.promise).next();if(!C.value)throw new Error("No catalog found");const Q=Ka(C.value);return new KC(e,new vA(Q),g)})}};Ne=new WeakMap,Os=new WeakMap,Vs=new WeakMap,Zs=new WeakMap,vC=new WeakSet,hr=function(){return r(this,null,function*(){const A=yield s(this,Vs).promise;try{for(var t=rA(A),e,g,B;e=!(g=yield t.next()).done;e=!1){const C=g.value;if(C.objectStatus!==KA.Normal)continue;const Q=Ka(C);s(this,Ne).update(Q)}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield g.call(t))}finally{if(B)throw B[0]}}})};let $Q=KC;class Ll{constructor(A,t,e,g){n(this,zs);n(this,Xs);n(this,OI);n(this,js);I(this,"track");n(this,VI,UA.get().createContext("CmafGroup"));this.track=g,E(this,Xs,e),E(this,OI,A),E(this,js,t)}[Symbol.asyncIterator](){return Ee(this,null,function*(){const A={name:this.track.trackObject.name,namespace:this.track.namespace};s(this,VI).debug("start",D({},A));try{for(var t=rA(s(this,OI)),e,g,B;e=!(g=yield new EA(t.next())).done;e=!1){const C=g.value;if(C.objectStatus===KA.EndOfTrackAndGroup&&(yield new EA(this.track.endOfTrack(C.groupId))),C.objectStatus!==KA.Normal)continue;const Q=s(this,js).createFragment(C.payload),o=Q.timescale(),a=Q.baseMediaDecodeTime()/o*1e3,c=Q.duration()/o*1e3,h=a+c,l=s(this,Xs)/1e3*o;Q.updateBaseMediaDecodeTime(Q.baseMediaDecodeTime()-l);const m=this.track.timestampRange();if(m&&a>=m[1])break;s(this,VI).debug("fragment",V(D({},A),{startTime:a,endTime:h,subscribeId:C.subscribeId,groupId:C.groupId,objectId:C.objectId,streamId:C.streamId})),yield[C.groupId,Q]}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield new EA(g.call(t)))}finally{if(B)throw B[0]}}s(this,VI).debug("end",D({},A))})}[pt()](){return d(this,zs,rn).call(this)}[Symbol.asyncDispose](){return d(this,zs,rn).call(this)}}Xs=new WeakMap,OI=new WeakMap,js=new WeakMap,VI=new WeakMap,zs=new WeakSet,rn=function(){return r(this,null,function*(){var A,t;return yield(t=(A=s(this,OI)).return)==null?void 0:t.call(A),Promise.resolve()})};const ZI=class ZI{constructor(A,t,e,g,B){n(this,_s);n(this,Ht);n(this,$s);n(this,AB);I(this,"trackObject");I(this,"namespace");this.trackObject=A,this.namespace=t,E(this,Ht,e),E(this,_s,g),E(this,$s,B)}static subscribe(C,Q,o){return r(this,arguments,function*(A,t,{timestampOffsetMs:e,startGroup:g,params:B}){var y;if(t.format!=="cmaf")throw new Error("format must be cmaf");const a=new Vt().name(t.name);g&&a.startGroup(g);const c=a.build();if(t.initTrack){const f=new Vt().name(t.initTrack).build(),[k,q]=yield Promise.all([d(y=ZI,YC,dr).call(y,A,f),de.subscribe(A,c,{params:B,largestGroupId:g?g-v(1):void 0})]),U=new ia(k);return new ZI(t,A.namespace(),q,U,e)}lA(t.initData,"no init data found on track");const h=ln(t.initData),l=new ia(new Uint8Array(h)),m=yield de.subscribe(A,c,{params:B,largestGroupId:g?g-v(1):void 0});return new ZI(t,A.namespace(),m,l,e)})}largestGroupId(){return s(this,Ht).largestGroupId()}stopAfterTimestampReached(A){E(this,AB,[0,A])}timestampRange(){return s(this,AB)}endOfTrack(A){return s(this,Ht).endOfTrack(A)}update(A,t){return s(this,Ht).update(A,t)}unsubscribe(){return r(this,null,function*(){return s(this,Ht).unsubscribe()})}next(){return r(this,null,function*(){const A=yield s(this,Ht).next();return A.done?A:{done:!1,value:new Ll(A.value,s(this,_s),s(this,$s),this)}})}return(){return r(this,null,function*(){return yield s(this,Ht).return(),{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[pt()](){return this.unsubscribe()}[Symbol.asyncDispose](){return r(this,null,function*(){return this.unsubscribe()})}};_s=new WeakMap,Ht=new WeakMap,$s=new WeakMap,AB=new WeakMap,YC=new WeakSet,dr=function(A,t){return r(this,null,function*(){var B=[];try{const e=ot(B,yield A.subscribe(t),!0);const g=yield e.objects().next();if(g.done)throw new Error("No init object");yield e.close();return g.value.payload}catch(C){var Q=C,o=!0}finally{var a=nt(B,Q,o);a&&(yield a)}})},n(ZI,YC);let Ao=ZI;const Ya=1e4,Jl=3e4,jo=class jo{constructor(A,t,e){n(this,Ni);n(this,TC,UA.get().createContext("Timeline"));n(this,be,new vA([]));n(this,Ui);n(this,tB);n(this,eB);n(this,iB);E(this,tB,A),E(this,eB,e),E(this,Ui,t),E(this,iB,d(this,Ni,cn).call(this,s(this,Ui))),this.closed().finally(()=>s(this,be).close()).catch(F)}closed(){return s(this,iB)}close(){return r(this,null,function*(){return(yield s(this,Ui).promise).unsubscribe()})}timeline(){const[A,t]=s(this,be).value();return A}timestampWallclockOffset(){return Wt(this.timeline().map(A=>A.mediaPts-A.wallclock))}static start(A,t){const e=$.fromPromise(de.subscribe(A,new Vt().name(t).groupOrder("ascending").build()));return new jo(A,e,t)}waitForWallclockTime(A){return r(this,null,function*(){return yield s(this,be).waitFor(t=>!!t.find(e=>e.wallclock>=A)),this.timeline()})}waitForTimelineToHaveMinDuration(){return r(this,null,function*(){return yield s(this,be).waitFor(A=>{const t=A[0],e=A[A.length-1];return!t||!e?!1:e.wallclock-t.wallclock>Ya}),this.timeline()})}};TC=new WeakMap,be=new WeakMap,Ui=new WeakMap,tB=new WeakMap,eB=new WeakMap,iB=new WeakMap,Ni=new WeakSet,cn=function(A){return r(this,null,function*(){const t=yield A.promise;try{for(var m=rA(t),y,f,k;y=!(f=yield m.next()).done;y=!1){var Q=f.value;var o=[];try{const q=ot(o,Q,!0);try{for(var e=rA(q),g,B,C;g=!(B=yield e.next()).done;g=!1){const U=B.value;if(U.objectStatus!==KA.Normal)continue;const H=Ml(U.payload);s(this,be).update(T=>{var z,Y;for(T.push(...H),T.sort((FA,nA)=>FA.wallclock-nA.wallclock);T[0]&&((Y=(z=T[T.length-1])==null?void 0:z.wallclock)!=null?Y:0)-T[0].wallclock>Jl;)T.shift();return T}),t===s(this,Ui).resolved&&U.groupId>v(0)&&U.objectId==v(0)&&d(this,Ni,lr).call(this,U.groupId).catch(T=>{s(this,TC).warn("backfill failed",T)})}}catch(B){C=[B]}finally{try{g&&(B=e.return)&&(yield B.call(e))}finally{if(C)throw C[0]}}}catch(a){var c=a,h=!0}finally{var l=nt(o,c,h);l&&(yield l)}}}catch(f){k=[f]}finally{try{y&&(f=m.return)&&(yield f.call(m))}finally{if(k)throw k[0]}}})},lr=function(A){return r(this,null,function*(){const t=A-v(1),e=this.timeline(),g=e[0],B=e[e.length-1];if(!g||!B||B.wallclock-g.wallclock>Ya)return;const C=$.fromPromise(de.subscribe(s(this,tB),new Vt().name(s(this,eB)).groupOrder("ascending").range(t,t).build()));return d(this,Ni,cn).call(this,C)})};let to=jo;function Ml(i){var t;const A=new TextDecoder("utf-8").decode(i).split(`
|
|
2
2
|
`);return(t=A[0])!=null&&t.startsWith("MEDIA_PTS")&&A.shift(),A.filter(e=>e.length>0).map(e=>{const[g,B,C,Q,o]=e.split(",");if(!g||!Q)throw new Error(`invalid timeline row: ${e}`);return{mediaPts:parseInt(g),groupId:B?parseInt(B):void 0,objectId:C?parseInt(C):void 0,wallclock:parseInt(Q),metadata:o}})}function Hl(i){return typeof i.language=="string"}const zo=class zo{constructor(A,t,e,g,B){n(this,PC,new aa);n(this,IB);n(this,Le);n(this,XI,0);I(this,"trackObject");I(this,"namespace");E(this,Le,A),E(this,IB,t),this.trackObject=e,this.namespace=g,E(this,XI,B)}static subscribe(A,t,e){return r(this,null,function*(){if(!Hl(t))throw new Error("track object language is required");const g=new Vt().name(t.name).build(),B=yield de.subscribe(A,g),C=B.objects();return new zo(B,C,t,A.namespace(),e)})}largestGroupId(){return s(this,Le).largestGroupId()}update(A,t){return s(this,Le).update(A,t)}unsubscribe(){return s(this,Le).unsubscribe()}next(){return r(this,null,function*(){for(;;){const A=yield s(this,IB).next();if(A.done)return A;if(A.value.objectStatus!==KA.Normal)continue;const t=new TextDecoder().decode(A.value.payload),e=s(this,PC).parse(t).map(B=>(B.startTime-=s(this,XI)/1e3,B.endTime-=s(this,XI)/1e3,B));return{done:!1,value:{language:this.trackObject.language,cues:e}}}})}return(){return r(this,null,function*(){return yield s(this,Le).return(),{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[pt()](){return this.unsubscribe()}[Symbol.asyncDispose](){return this.unsubscribe()}};PC=new WeakMap,IB=new WeakMap,Le=new WeakMap,XI=new WeakMap;let eo=zo;LE=[ZA({context:"Channel",enter:"info"})];const zI=class zI{constructor(A,t,e,g,B){n(this,jI);I(this,"namespace");n(this,bi);n(this,Li);n(this,Ji);n(this,Je);this.namespace=g,E(this,bi,A),E(this,Li,t),E(this,Ji,e),E(this,Je,B)}static start(A,t){return r(this,null,function*(){const e=new va(A,{namespace:t.namespace}),[g,B]=yield Promise.all([to.start(e,"timeline"),$Q.start(e,{catalog:t.catalog,namespace:t.namespace})]);return new zI(e,g,B,t.namespace,0)})}closed(){return s(this,Ji).closed()}catalog(){return s(this,Ji).catalog()}timestampWallclockOffset(){return s(this,Li).timestampWallclockOffset()}timestampOffsetMs(){return s(this,Je)}setTimestampOffsetMs(A){E(this,Je,A)}waitForWallclockTime(A){return s(this,Li).waitForWallclockTime(A)}subscribeCmafTrack(A,t){const e=t==null?void 0:t.startGroup,g=t==null?void 0:t.params,B=this.catalog().current().tracks,C=A["com.vindral.variant_uid"]!==void 0?B.find(Q=>Q["com.vindral.variant_uid"]===A["com.vindral.variant_uid"]):void 0;return d(this,jI,SQ).call(this,()=>Ao.subscribe(s(this,bi),C!=null?C:A,{timestampOffsetMs:s(this,Je),startGroup:e,params:g}))}subscribeWebVttTrack(A){return d(this,jI,SQ).call(this,()=>eo.subscribe(s(this,bi),A,s(this,Je)))}subscribeTrack(A){return d(this,jI,SQ).call(this,()=>s(this,bi).subscribe(A))}close(){return Promise.all([s(this,Ji).close(),s(this,Li).close()])}};_o=Wi(null),bi=new WeakMap,Li=new WeakMap,Ji=new WeakMap,Je=new WeakMap,jI=new WeakSet,SQ=function(A){return r(this,null,function*(){const[t,e]=this.catalog().value();try{return yield A()}catch(g){if(t===this.catalog().current()&&e&&(yield Promise.race([e,ce(500)])),t!==this.catalog().current())return A();throw g}})},OA(_o,9,"start",LE,zI),Te(_o,zI),Oi(_o,3,zI);let oC=zI;const ql=v(8);function vl(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:ql,payload:A}}const $o=class $o{constructor(A){n(this,xC);n(this,Mi);n(this,gB);const[t,e]=A.value.value();E(this,Mi,{createdAt:new Date,wallclock:new Date(t.ntpTimestamp),rtt:t.rtt}),E(this,gB,d(this,xC,ur).call(this,A))}wallclock(){const t=Date.now()-s(this,Mi).createdAt.getTime();return s(this,Mi).wallclock.getTime()+t}closed(){return s(this,gB)}static start(A){return new $o(A)}};Mi=new WeakMap,gB=new WeakMap,xC=new WeakSet,ur=function(A){return r(this,null,function*(){try{for(var t=rA(A.value),e,g,B;e=!(g=yield t.next()).done;e=!1){const C=g.value;E(this,Mi,{createdAt:new Date,wallclock:new Date(C.ntpTimestamp),rtt:C.rtt})}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield g.call(t))}finally{if(B)throw B[0]}}})};let io=$o;function nC(i){return typeof i=="string"||i===null||i===void 0}function Kl(i){return"provider"in i&&typeof i.provider=="string"&&(!("widevineLicenseUrl"in i)||nC(i.widevineLicenseUrl))&&(!("playreadyLicenseUrl"in i)||nC(i.playreadyLicenseUrl))&&(!("fairplayLicenseUrl"in i)||nC(i.fairplayLicenseUrl))&&(!("fairplayCertificate"in i)||nC(i.fairplayCertificate))}function Yl(i){try{return ln(i)}catch(A){throw new Error("Failed to convert fairplayCertificate")}}function Tl(i){const A=new TextDecoder().decode(i),t=JSON.parse(A);if(!Kl(t))throw new Error("Invalid drm object");const B=t,{fairplayCertificate:e}=B,g=TE(B,["fairplayCertificate"]);return V(D({},g),{fairplayCertificate:e?Yl(e):void 0})}class Io{constructor(A){I(this,"value");this.value=A}static create(A,t,e){return r(this,null,function*(){var o=[];try{const g=ot(o,yield A.subscribeTrack(new Vt().name("drm").build()),!0);const B=g.objects();const C=yield B.next();if(C.done)throw new Error("No drm object received");const Q=Tl(C.value.payload);return new Io(V(D({},Q),{videoCodec:t,audioCodec:e}))}catch(a){var c=a,h=!0}finally{var l=nt(o,c,h);l&&(yield l)}})}}function Pl(i){return"rtt"in i&&typeof i.rtt=="number"&&"ntpTimestamp"in i&&typeof i.ntpTimestamp=="number"&&"estimatedBandwidth"in i&&typeof i.estimatedBandwidth=="number"}function Ta(i){const A=new TextDecoder().decode(i),t=JSON.parse(A);if(!Pl(t))throw new Error("Invalid stats object");return t}const xl=1e4,An=class An{constructor(A,t,e){n(this,WC);I(this,"ip");I(this,"value");n(this,sB);this.ip=e,this.value=new vA(t),E(this,sB,d(this,WC,wr).call(this,A))}closed(){return s(this,sB)}idleTimeout(){return r(this,null,function*(){for(;;){const[A,t]=this.value.value();try{yield Promise.race([kQ(xl,new Error("Idle timeout")),t])}catch(e){return e}}})}static start(A){return r(this,null,function*(){const e=(yield A.subscribe(new Vt().name("stats").groupOrder("ascending").build())).objects(),g=yield e.next();if(g.done)throw new Error("No stats object received");const B=Ta(g.value.payload);if(!B.ip)throw new Error("Expected IP in initial stats object");return new An(e,B,B.ip)})}};sB=new WeakMap,WC=new WeakSet,wr=function(A){return r(this,null,function*(){try{for(var t=rA(A),e,g,B;e=!(g=yield t.next()).done;e=!1){const C=g.value;if(C.objectStatus!==KA.Normal)continue;const Q=Ta(C.payload);this.value.update(Q)}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield g.call(t))}finally{if(B)throw B[0]}}})};let go=An;class Wl{constructor(A){n(this,OC,UA.get().createContext("UpstreamWatcher"));n(this,_I);E(this,_I,new vA($.fromPromise(A.closed())))}update(A){s(this,_I).update($.fromPromise(A.closed()))}closed(){return r(this,null,function*(){try{for(;;){const[A,t]=s(this,_I).value();let e=!1;yield Promise.race([t==null?void 0:t.then(()=>e=!0),A.promise.then(()=>{if(!e)throw s(this,OC).warn("Upstream closed"),new Error("Upstream closed")})])}}catch(A){return A}})}}OC=new WeakMap,_I=new WeakMap;class so{constructor(A,t){n(this,$I,UA.get().createContext("TracksIterator"));n(this,BB);n(this,CB);E(this,BB,A),E(this,CB,t)}[Symbol.asyncIterator](){return Ee(this,null,function*(){const A=s(this,CB);try{for(var t=rA(s(this,BB)),e,g,B;e=!(g=yield new EA(t.next())).done;e=!1){const C=g.value;if(!C)continue;const Q={name:C.trackObject.name,namespace:C.namespace};s(this,$I).debug("track start",D({mediaType:A},Q)),yield*Bn(C),s(this,$I).debug("track end",D({mediaType:A},Q))}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield new EA(g.call(t)))}finally{if(B)throw B[0]}}s(this,$I).debug("tracks ended",{mediaType:A})})}}$I=new WeakMap,BB=new WeakMap,CB=new WeakMap;let Ol=(HE=[ZA({context:"Player",enter:"info"})],ME=[ZA({context:"Player",enter:"info",return:"info"})],JE=[ZA({context:"Player",enter:"info"})],Be=class{constructor(A,t,e){Oi(oB,5,this);n(this,TA);n(this,Ag);n(this,tg);n(this,Hi);n(this,bA);n(this,Dt,new vA(void 0));n(this,mt,new vA(void 0));n(this,Me,new vA(void 0));n(this,eg);n(this,QB);I(this,"subtitles",new so(s(this,Me),"subtitles"));I(this,"video",new so(s(this,mt),"video"));I(this,"audio",new so(s(this,Dt),"audio"));E(this,Ag,A),E(this,tg,io.start(e)),E(this,Hi,e),E(this,bA,new vA(t)),E(this,eg,new Wl(t)),E(this,QB,Promise.race([e.idleTimeout(),d(this,TA,Dr).call(this),s(this,eg).closed()])),s(this,Ag).closed().then(()=>this.close()).catch(F)}closed(){return s(this,QB)}static start(A,t){return r(this,null,function*(){const e=new Map;if(t.burstMs!==void 0){const c=vl(t.burstMs);e.set(c.type,c)}const g=new va(A,{namespace:Rl("auxiliary")}),[[B,C,Q],o]=yield Promise.all([oC.start(A,t).then(c=>Promise.all([Promise.resolve(c),t.videoTrack?c.subscribeCmafTrack(t.videoTrack,{params:e}):void 0,t.audioTrack?c.subscribeCmafTrack(t.audioTrack,{params:e}):void 0])),go.start(g)]),a=new Be(A,B,o);return Q&&s(a,Dt).update(Q),C&&s(a,mt).update(C),a})}connectionInfo(){const A=s(this,Hi).value.current();return{ip:s(this,Hi).ip,rtt:A.rtt,estimatedBandwidth:A.estimatedBandwidth}}stats(){return s(this,Hi).value}catalog(){return s(this,bA).current().catalog()}namespace(){return s(this,bA).current().namespace}videoTrack(){var A;return(A=s(this,mt).current())==null?void 0:A.trackObject}audioTrack(){var A;return(A=s(this,Dt).current())==null?void 0:A.trackObject}referenceClock(){return s(this,tg)}drm(){return r(this,null,function*(){var t,e;if(this.catalog().current().tracks.find(({name:g})=>g==="drm"))return Io.create(s(this,bA).current(),(t=this.videoTrack())==null?void 0:t.codec,(e=this.audioTrack())==null?void 0:e.codec)})}close(){return Promise.all([s(this,bA).current().close(),s(this,bA).close(),d(this,TA,yQ).call(this,s(this,Dt)),d(this,TA,yQ).call(this,s(this,mt)),d(this,TA,yQ).call(this,s(this,Me))])}zap(A,t){return r(this,null,function*(){var y,f;const e=yield oC.start(s(this,Ag),A),g=s(this,tg).wallclock()-t,B=s(this,bA).current(),C=B.timestampWallclockOffset(),Q=yield e.waitForWallclockTime(g);s(this,eg).update(e),yield s(this,bA).current().close();const o=Q.toReversed().find(k=>k.wallclock<=g),a=o!=null&&o.mediaPts?o.mediaPts-B.timestampOffsetMs():void 0,l=e.timestampWallclockOffset()-C+B.timestampOffsetMs();e.setTimestampOffsetMs(l);const m=o!=null&&o.groupId?v(o.groupId):void 0;a&&((y=s(this,mt).current())==null||y.stopAfterTimestampReached(a),(f=s(this,Dt).current())==null||f.stopAfterTimestampReached(a)),s(this,bA).update(e),yield Promise.all([A.videoTrack?this.setVideoTrack(A.videoTrack,m):void 0,A.audioTrack?this.setAudioTrack(A.audioTrack,m):void 0])})}setSubtitleTrack(A){return r(this,null,function*(){var e,g;if(!A){yield(e=s(this,Me).current())==null?void 0:e.unsubscribe();return}const[t]=yield Promise.all([s(this,bA).current().subscribeWebVttTrack(A),(g=s(this,Me).current())==null?void 0:g.unsubscribe()]);s(this,Me).update(t)})}setVideoTrack(A,t){return r(this,null,function*(){const e=yield d(this,TA,FB).call(this,s(this,bA).current(),A,s(this,mt).current(),t);s(this,mt).update(e)})}setAudioTrack(A,t){return r(this,null,function*(){const e=yield d(this,TA,FB).call(this,s(this,bA).current(),A,s(this,Dt).current(),t);s(this,Dt).update(e)})}},oB=Wi(null),Ag=new WeakMap,tg=new WeakMap,Hi=new WeakMap,bA=new WeakMap,Dt=new WeakMap,mt=new WeakMap,Me=new WeakMap,eg=new WeakMap,QB=new WeakMap,TA=new WeakSet,yQ=function(A){const t=A.current(),e=t==null?void 0:t.largestGroupId();return A.isClosed()||A.update(void 0),A.close(),e?t==null?void 0:t.update(e,e):t==null?void 0:t.unsubscribe()},FB=function(A,t,e,g){return r(this,null,function*(){const B=e==null?void 0:e.largestGroupId(),[C,Q]=yield Promise.all([A.subscribeCmafTrack(t,{startGroup:g||(B?B+v(1):void 0)}),B?e==null?void 0:e.update(B,B):e==null?void 0:e.unsubscribe()]);return C})},Dr=function(){return r(this,null,function*(){try{for(var B=rA(s(this,bA)),C,Q,o;C=!(Q=yield B.next()).done;C=!1){const a=Q.value;try{for(var A=rA(a.catalog()),t,e,g;t=!(e=yield A.next()).done;t=!1){const c=e.value;yield Promise.all([d(this,TA,hn).call(this,c,s(this,mt)),d(this,TA,hn).call(this,c,s(this,Dt))])}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}}}catch(Q){o=[Q]}finally{try{C&&(Q=B.return)&&(yield Q.call(B))}finally{if(o)throw o[0]}}})},hn=function(A,t){return r(this,null,function*(){const e=t.current();if(!e)return;const g=e.trackObject.name,B=e.trackObject["com.vindral.variant_uid"],C=A.tracks.find(o=>o.name===g),Q=A.tracks.find(o=>o["com.vindral.variant_uid"]===B);if(!C){if(!Q){t.update(void 0);return}t.update(yield s(this,bA).current().subscribeCmafTrack(Q))}})},OA(oB,1,"close",HE,Be),OA(oB,1,"zap",ME,Be),FB=OA(oB,17,"#replaceTrack",JE,TA,FB),Te(oB,Be),Be);function Bo(i,A,t){const e=new URL("/voq/subscribe",i);return e.searchParams.set("sessionId",A.sessionId),e.searchParams.set("clientId",A.clientId),e.searchParams.set("channelId",A.channelId),t&&e.searchParams.set("authToken",t),e}const Vl=1e4,tn=class tn{constructor(A,t,e,g,B,C,Q){n(this,xA);n(this,RA);n(this,PA);n(this,Ct);n(this,qi,"disconnected");n(this,dA);n(this,He,new Map);n(this,nB);n(this,ig);n(this,aB);n(this,Ig,new Map);n(this,gg,A=>{if(!A){s(this,dA).setSubtitleTrack(void 0).catch(F);return}const t=s(this,He).get($e(s(this,dA).namespace())),e=t==null?void 0:t.getTextTrack(A);e&&s(this,dA).setSubtitleTrack(e).catch(F)});n(this,EB,A=>{switch(A.type){case"subscribe":{if(s(this,sg)){s(this,PA).info("Ignoring - we are already switching");return}E(this,sg,!0),d(this,xA,yr).call(this,A.subscription).catch(t=>{s(this,PA).error("error handling subscription",t),s(this,RA).emit("received signal",{type:"subscription changed",subscription:A.subscription,reset:!0})}).finally(()=>E(this,sg,!1))}break;case"telemetry":ca(new URL("/api/telemetry",s(this,Ct).url().replace("wss://","https://")),{body:A.body,headers:{"Content-Type":"text/plain"}}).catch(F);break;case"refresh auth":s(this,Ct).updateAuthToken(A.token);break}});n(this,sg,!1);I(this,"disconnect",(A="Disconnect Requested")=>{s(this,PA).info("Disconnecting",A),s(this,Ct).close(),s(this,dA).close().catch(F),E(this,Ig,new Map),E(this,qi,"disconnected")});E(this,RA,A),E(this,PA,t),E(this,Ct,e),E(this,dA,g),E(this,He,B),E(this,nB,C),E(this,ig,Q),s(this,RA).on("send signal",s(this,EB)),s(this,RA).on("disconnect",this.disconnect),s(this,RA).on("text track",s(this,gg)),d(this,xA,mr).call(this).catch(F),d(this,xA,fr).call(this).catch(F)}get estimatedBandwidth(){return s(this,aB)}unload(){s(this,RA).off("send signal",s(this,EB)),s(this,RA).off("disconnect",this.disconnect),s(this,RA).off("text track",s(this,gg)),this.disconnect()}suspend(){}unsuspend(){}getStatistics(){return{edgeUrl:s(this,Ct).url(),connectionProtocol:"moq"}}static start(A,t,e,g,B){return r(this,null,function*(){var U,H,T,z;const C=new Map(g.connectInfo.channels.map(Y=>[$e(Y.catalog.namespace),new Qo(new vA(Y.catalog))])),Q=yield g.onConnectInfo(g.connectInfo),o=g.options.get("authenticationToken");let a,c;switch(typeof g.edgeUrl){case"string":{a=Bo(g.edgeUrl,Q,o);break}default:a=Bo(g.edgeUrl.moqUrl||g.edgeUrl.moqWsUrl,Q,o),c=Bo(g.edgeUrl.moqWsUrl,Q,o);break}const h=(U=g.connectInfo.channels.find(Y=>Y.channelId===Q.channelId))==null?void 0:U.catalog;t.debug("Resolved edge url",{edgeUrl:a,edgeWsUrl:c}),lA(h,"no catalog found");const l=(H=C.get($e(h.namespace)))==null?void 0:H.getVideoTrack(Q.video),m=(T=C.get($e(h.namespace)))==null?void 0:T.getAudioTrack(Q.audio),y=yield kl({url:a,wsUrl:c,authToken:g.options.get("authenticationToken"),preferredTransport:g.options.get("webtransportEnabled")?"webtransport":"websocket",role:Il.Subscriber,websocketFallbackTimeoutMs:2e3}),f=yield Promise.race([Ol.start(y.subscriber,{namespace:h.namespace,catalog:h,videoTrack:l==null?void 0:l.track,audioTrack:m==null?void 0:m.track,burstMs:Q.burstMs||0}),kQ(Vl,new Error("Timeout waiting for player to start")),$r(y.closed(),"Session closed before player started")]),k=new Qo(f.catalog());C.set($e(h.namespace),k),A.emit("received signal",{type:"client ip",ip:f.connectionInfo().ip}),f.drm().then(Y=>{Y&&A.emit("received drm data",Y.value)}).catch(Y=>{t.error("Error getting DRM data",Y)});const q=new tn(A,t,y,f,C,e,B);return Q.textTrack&&s(z=q,gg).call(z,Q.textTrack),q})}getState(){return s(this,qi)}close(){s(this,Ct).close()}closed(){return Promise.race([s(this,Ct).closed(),s(this,dA).closed()])}};RA=new WeakMap,PA=new WeakMap,Ct=new WeakMap,qi=new WeakMap,dA=new WeakMap,He=new WeakMap,nB=new WeakMap,ig=new WeakMap,aB=new WeakMap,Ig=new WeakMap,xA=new WeakSet,mr=function(){return r(this,null,function*(){s(this,Ct).transportType()==="websocket"&&(yield ce(5e3));try{for(var A=rA(s(this,dA).stats()),t,e,g;t=!(e=yield A.next()).done;t=!1){const{rtt:B,estimatedBandwidth:C}=e.value;E(this,aB,C),s(this,ig).push(B),s(this,RA).emit("rtt",Wt(s(this,ig).items()))}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}})},gg=new WeakMap,EB=new WeakMap,sg=new WeakMap,Sr=function(A){return r(this,null,function*(){var g;const t=yield s(this,nB).connect({channelId:A});if(!Rn(t))throw new Error("no moq connect info found");const e=(g=t.channels.find(B=>B.channelId===A))==null?void 0:g.catalog;if(!e)throw new Error("no catalog found");return e})},yr=function(A){return r(this,null,function*(){var C,Q,o;s(this,PA).info("handle subscription",A);const t=s(this,dA);let e=s(this,He).get(A.channelId);if(e||(e=new Qo(new vA(yield d(this,xA,Sr).call(this,A.channelId))),s(this,He).set(A.channelId,e)),t.namespace().join("/")!==e.namespace().join("/")){s(this,PA).info("changing channel",A.channelId);const a=e.getVideoTrack(A.video),c=e.getAudioTrack(A.audio);yield t.zap({namespace:e.namespace(),catalog:e.catalog(),videoTrack:a==null?void 0:a.track,audioTrack:c==null?void 0:c.track},500),t.drm().then(h=>{h&&s(this,RA).emit("received drm data",h.value)}).catch(h=>{s(this,PA).error("Error getting DRM data",h)}),s(this,PA).info("switched channel",A.channelId),(C=s(this,He).get($e(t.namespace())))==null||C.updateCatalog(t.catalog()),s(this,RA).emit("received signal",{type:"subscription changed",subscription:A});return}const g=e.getVideoTrack(A.video),B=e.getAudioTrack(A.audio);yield Promise.all([g&&g.track.name!==((Q=s(this,dA).videoTrack())==null?void 0:Q.name)?s(this,dA).setVideoTrack(g.track):void 0,B&&B.track.name!==((o=s(this,dA).audioTrack())==null?void 0:o.name)?s(this,dA).setAudioTrack(B.track):void 0]),s(this,RA).emit("received signal",{type:"subscription changed",subscription:A})})},fr=function(){return r(this,null,function*(){try{E(this,qi,"connecting"),s(this,PA).info("Connecting..."),E(this,qi,"connected"),yield Promise.all([d(this,xA,dn).call(this,s(this,dA).referenceClock(),s(this,dA).audio),d(this,xA,dn).call(this,s(this,dA).referenceClock(),s(this,dA).video),d(this,xA,pr).call(this,s(this,dA).subtitles)]),yield s(this,dA).closed(),s(this,Ct).close(),s(this,PA).info("Session closed")}catch(A){s(this,PA).warn("Session error",A)}})},pr=function(A){return r(this,null,function*(){try{for(var t=rA(A),e,g,B;e=!(g=yield t.next()).done;e=!1){const C=g.value;s(this,RA).emit("text track data",C)}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield g.call(t))}finally{if(B)throw B[0]}}})},dn=function(A,t){return r(this,null,function*(){var Q;let e="",g="",B;const C=s(this,dA).videoTrack()===void 0;try{for(var l=rA(t),m,y,f;m=!(y=yield l.next()).done;m=!1){const k=y.value;const q=$e(k.track.namespace),U=k.track.trackObject.language,H=UQ((Q=k.track.trackObject.codec)!=null?Q:""),T=k.track.trackObject.codec,z=H?ze({codec:H,codecString:T}):void 0,Y=!!k.track.trackObject["com.vindral.drm"];try{for(var o=rA(k),a,c,h;a=!(c=yield o.next()).done;a=!1){const[FA,nA]=c.value;const tt={channelId:e!==""&&(C||nA.mediaType()==="video")&&e!==q?q:void 0,language:nA.mediaType()==="audio"&&g!==U?U:void 0,drmTransition:B!==void 0&&B!==Y};e=q,g=U,B=Y;const JA=nA.producerReferenceTime(),w=s(this,Ig).get(k.track.namespace)||0;if(JA&&Date.now()-w>1e3){s(this,Ig).set(k.track.namespace,Date.now());const G=A.wallclock()-JA.getTime();s(this,PA).debug("timing-info",{mediaType:nA.mediaType(),referenceClock:A,delta:G,groupId:FA,timestamp:nA.baseMediaDecodeTime()/nA.timescale()*1e3+G,wallclockTime:JA.getTime()}),s(this,RA).emit("received signal",{type:"timing info",timingInfo:{channelId:q,timestamp:nA.baseMediaDecodeTime()/nA.timescale()*1e3+G,wallclockTime:JA.getTime()}})}s(this,RA).emit("received moq data",{payload:nA,channelId:q,groupId:FA,mimeType:z,codec:H,switchInfo:tt,renditionId:Zl(k.track.trackObject.name)})}}catch(c){h=[c]}finally{try{a&&(c=o.return)&&(yield c.call(o))}finally{if(h)throw h[0]}}}}catch(y){f=[y]}finally{try{m&&(y=l.return)&&(yield y.call(l))}finally{if(f)throw f[0]}}})};let Co=tn;function Zl(i){return i.split("").reduce((t,e)=>t=e.charCodeAt(0)+(t<<6)+(t<<16)-t,0)}class Qo{constructor(A){n(this,VC);n(this,Ce);n(this,vi);E(this,Ce,A),E(this,vi,d(this,VC,Fr).call(this))}catalog(){return s(this,Ce).current()}namespace(){return s(this,Ce).current().namespace}updateCatalog(A){E(this,Ce,A)}getTextTrack(A){return s(this,Ce).current().tracks.find(t=>t.label===A)}getAudioTrack(A){if(!A.codec)return;const t=s(this,vi).filter(e=>!(!je(e)||e.bitRate>A.bitRate||A.codec&&e.codec!==A.codec||A.language&&e.language!==A.language));return t[t.length-1]}getVideoTrack(A){if(!A.codec)return;const t=s(this,vi).filter(e=>!(!Xe(e)||e.bitRate>A.bitRate||A.codec&&e.codec!==A.codec));return t[t.length-1]}renditions(){return s(this,vi)}}Ce=new WeakMap,vi=new WeakMap,VC=new WeakSet,Fr=function(){const[A,t]=s(this,Ce).value();return Un(A)};const Xl=(i,A)=>{const t=new URL("/subscribe",i);return t.searchParams.append("channelId",A.channelId),t.searchParams.append("sessionId",A.sessionId),t.searchParams.append("clientId",A.clientId),A.audio&&A.audio.codec&&(t.searchParams.append("audio.bitRate",Math.round(A.audio.bitRate).toString()),t.searchParams.append("audio.codec",A.audio.codec),A.audio.language&&t.searchParams.append("audio.language",A.audio.language)),A.video&&A.video.codec&&(t.searchParams.append("video.width",A.video.width.toString()),t.searchParams.append("video.height",A.video.height.toString()),t.searchParams.append("video.bitRate",Math.round(A.video.bitRate).toString()),t.searchParams.append("video.codec",A.video.codec)),A.expectAdditionalConnection&&t.searchParams.append("expectAdditionalConnection",A.expectAdditionalConnection.toString()),A.burstMs&&t.searchParams.append("burstMs",A.burstMs.toString()),A.channelGroupId&&t.searchParams.append("channelGroupId",A.channelGroupId),A.authToken&&(t.searchParams.append("auth.token",A.authToken),t.searchParams.append("auth.type","jwt")),t.toString()};class jl extends it{constructor(t,e){super();I(this,"options");I(this,"websockets",[]);I(this,"logger");I(this,"reconnectState",{reconnectRetries:0});I(this,"isSuspended",!1);I(this,"_connectionAttemptCount",0);I(this,"connectStartTime",0);I(this,"_connectTime");I(this,"shouldContinueConnecting",!1);I(this,"_isConnectInProgress",!1);I(this,"readyState",()=>{if(this.websockets.length===0)return WebSocket.CLOSED;const t=this.websockets.map(e=>e.readyState);for(const e of t)switch(e){case WebSocket.OPEN:continue;default:return e}return WebSocket.OPEN});I(this,"url",()=>{var t;return(t=this.websockets[0])==null?void 0:t.url});I(this,"send",t=>{var e;this.websockets.length&&((e=this.websockets[0])==null||e.send(t))});I(this,"close",t=>{var g;let e=!1;return(g=this.websockets)==null||g.forEach(B=>{B.onmessage=F,B.removeEventListener("error",this.onError),B.removeEventListener("close",this.onClose),B.removeEventListener("open",this.onOpen),B.close(1e3,t),e=!0}),this.websockets=[],this.shouldContinueConnecting=!1,this._isConnectInProgress=!1,this.logger.info("Closed websocket",{reason:t}),e});I(this,"suspend",()=>{this.isSuspended=!0});I(this,"unsuspend",()=>{this.isSuspended=!1,this.readyState()!==WebSocket.OPEN&&!this.isConnectInProgress&&this.connect()});I(this,"onMessage",(t,e)=>{this.websockets.length!==0&&this.options.onMessage(t,e.data)});I(this,"onError",()=>{this.logger.info("On error",D({},this.options)),this.close("one websocket had an error"),this.emit("error",new x("WebSocket error",{code:"websocket_error",isFatal:!1}))});I(this,"onClose",t=>{switch(this.logger.info("Closed",V(D({},this.options),{reason:t.reason,code:t.code,isSuspended:this.isSuspended})),this.close("one websocket was closed"),t.code){case 4e3:this.emit("error",UB(yg()));break;case 4001:this.emit("error",UB(yg()));break;case 4002:this.emit("error",cc(yg()));break;case 4003:this.emit("error",xn("internal",yg()));break;case 4010:this.emit("error",hc("internal",yg()));break}this.emit("close",this)});I(this,"onOpen",()=>{this.logger.info("Opened",D({},this.options)),this.readyState()===WebSocket.OPEN&&(this._connectTime=Date.now()-this.connectStartTime,this.reconnectState.reconnectRetries=0,this._isConnectInProgress=!1,this.emit("open",this))});I(this,"connect",(t=!1)=>r(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,t&&this.options.reconnectDelay>0){this.logger.info("Waiting for reconnect delay",D({},this.options)),yield ce(this.options.reconnectDelay);const e=yield this.options.reconnectHandler(this.reconnectState);if(this.reconnectState.reconnectRetries++,!e)return this._isConnectInProgress=!1,this.emit("error",Wn()),!1}this._connectionAttemptCount++;try{if(!this.shouldContinueConnecting)return this._isConnectInProgress=!1,this.logger.info("Connection aborted"),!1;const{url:e,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(D({},this.options),{url:e}));for(let B=0;B<g;B++){const C=new WebSocket(e);C.binaryType="arraybuffer",C.onmessage=Q=>this.onMessage(B,Q),C.addEventListener("error",this.onError),C.addEventListener("close",this.onClose),C.addEventListener("open",this.onOpen),this.websockets.push(C)}return!0}catch(e){return this._isConnectInProgress=!1,e instanceof x&&(this.logger.error("Failed to connect",e.toStringifiable()),e.isFatal())||this.shouldContinueConnecting&&(this.logger.info("Connection aborted",{error:e}),this.emit("error",new x("Failed to connect",{code:"failed_to_connect",isFatal:!1,source:e,type:"internal"}))),!1}}));this.options=t,this.logger=e}get isConnectInProgress(){return this._isConnectInProgress}get connectionCount(){return this.websockets.length}get connectionAttemptCount(){return this._connectionAttemptCount}get connectTime(){return this._connectTime}}const zl=65536*8,_l=.9,$l=40,Au=i=>{const A=i||$l;return zl*_l*1e3/A},qt=class qt{constructor(A,t,e,g){I(this,"emitter");I(this,"transport");I(this,"logger");I(this,"config");I(this,"rtts");I(this,"lastPingSentTime",Date.now());I(this,"isPingInFlight",!1);I(this,"connectCount",0);I(this,"missedPings",0);I(this,"contextSwitchesInProgress",new Set);I(this,"contextSwitchesCompleted",new Set);I(this,"buffer",[]);I(this,"disconnected",new $);I(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")});I(this,"suspend",()=>{this.resetPingState(),this.transport.suspend()});I(this,"unsuspend",()=>{this.transport.unsuspend()});I(this,"getState",()=>{switch(this.transport.readyState()){case WebSocket.OPEN:return"connected";case WebSocket.CONNECTING:return"connecting";default:return"disconnected"}});I(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))});I(this,"getStatistics",()=>{var A;return{edgeUrl:(A=this.transport)==null?void 0:A.url(),connectionProtocol:"vindral_ws"}});I(this,"onMessage",(A,t)=>{var e;if(this.pingCooldownExpired()&&this.sendPing(),this.contextSwitchesCompleted.size===((e=this.transport)==null?void 0:e.connectionCount)){this.logger.info("Completing context switch"),this.contextSwitchesInProgress.clear(),this.contextSwitchesCompleted.clear();const g=this.buffer.filter(([C,Q])=>!(Q instanceof ArrayBuffer)),B=this.buffer.filter(([C,Q])=>Q instanceof ArrayBuffer);g.map(C=>this.handleMessage(C[0],C[1])),B.map(C=>this.handleMessage(C[0],C[1])),this.buffer=[]}if(this.contextSwitchesInProgress.has(A)){if(!(t instanceof ArrayBuffer)){const g=JSON.parse(t);if(Nn(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,t]);return}this.handleMessage(A,t)});I(this,"resolveEdgeUrl",()=>r(this,null,function*(){const A=this.config.connectInfo,t=yield this.config.onConnectInfo(A),e=this.config.options.getOverride("separateVideoSocketEnabled",t.channelId),g=this.config.options.get("media")==="audio+video";let B=1;g&&(B=e!==!1?2:1);const C=Xl(this.config.edgeUrl,{video:t.video,audio:t.audio,burstMs:t.burstMs,sessionId:t.sessionId,clientId:t.clientId,channelId:t.channelId,channelGroupId:t.channelGroupId,expectAdditionalConnection:B>1,authToken:this.config.options.get("authenticationToken")});return this.logger.debug("Resolved edge url",{edgeUrl:C}),{url:C,connectionCount:B}}));I(this,"handleMessage",(A,t)=>{if(t instanceof ArrayBuffer)this.emitter.emit("received data",t);else{const e=JSON.parse(t);if(!Nn(e))return;switch(e.type){case"pong":this.lastPingSentTime&&(this.rtts.push(Date.now()-this.lastPingSentTime),this.isPingInFlight=!1,this.emitter.emit("rtt",Wt(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",e);break}}});I(this,"connectWebSocketTransport",()=>{const A=new jl({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",t=>this.disconnected.reject(t)),A.connect(),A});I(this,"close",(A="Disconnect Requested")=>{var t;this.contextSwitchesCompleted.clear(),this.contextSwitchesInProgress.clear(),this.buffer=[],this.resetPingState(),this.disconnected.resolve(),(t=this.transport)==null||t.close(A)});I(this,"onTransportChange",()=>{var A;switch(this.getState()){case"connected":(A=this.transport)!=null&&A.connectTime&&(this.rtts.push(this.transport.connectTime/qt.TLS_ROUNDTRIPS/(this.transport.connectionCount||1)),this.emitter.emit("rtt",Wt(this.rtts.items()))),this.connectCount++,this.resetPingState();break;default:this.contextSwitchesCompleted.clear(),this.contextSwitchesInProgress.clear(),this.buffer=[],this.resetPingState(),this.disconnected.resolve();break}this.emitter.emit("connection state",this.getState())});I(this,"reconnect",A=>{if(this.transport.isConnectInProgress){this.logger.debug("Stopping reconnect, already mid-connection");return}this.close(A)});I(this,"resetPingState",()=>{this.missedPings=0,this.isPingInFlight=!1});I(this,"pingCooldownExpired",()=>Date.now()-this.lastPingSentTime>qt.PING_INTERVAL);I(this,"sendPing",()=>{if(this.isPingInFlight){this.missedPings++,this.missedPings>qt.MAX_MISSED_PINGS&&this.reconnect("missed pings");return}this.isPingInFlight=!0,this.lastPingSentTime=Date.now(),this.missedPings=0,this.sendSignal({type:"ping"})});this.logger=t,this.emitter=A,this.config=e,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(F),this.transport=this.connectWebSocketTransport()}closed(){return this.disconnected.promise}};I(qt,"PING_INTERVAL",5e3),I(qt,"MAX_MISSED_PINGS",4),I(qt,"TLS_ROUNDTRIPS",3),I(qt,"start",(A,t,e,g)=>new Promise((B,C)=>{const Q=new qt(A,t,e,g);Q.transport.once("error",o=>C(o)),Q.transport.once("open",()=>B(Q))}));let oo=qt;class tu{constructor(A){n(this,Bg);n(this,qe,[]);n(this,Cg);E(this,Bg,A)}select(A){if(s(this,Bg).edgeUrl)return s(this,Bg).edgeUrl;s(this,qe).length===0&&E(this,qe,s(this,qe).concat(A));const t=s(this,qe).shift();if(E(this,Cg,t),t)return t}shiftedEdge(){return s(this,Cg)}reset(){E(this,Cg,void 0),E(this,qe,[])}}Bg=new WeakMap,qe=new WeakMap,Cg=new WeakMap;const Eg=class Eg{constructor(A,t,e){n(this,jC);I(this,"emitter");I(this,"logger");I(this,"config");I(this,"apiClient");I(this,"connectionImpl");n(this,vt,new W(10));n(this,Kt,!0);n(this,Qg);n(this,Qe,0);n(this,og,0);n(this,ng);n(this,ag);I(this,"unload",()=>{var A;this.logger.debug("Unloading module..."),this.disconnect("Unloading"),(A=this.connectionImpl)==null||A.unload(),this.logger.debug("Unloaded module")});I(this,"suspend",()=>{var A;E(this,Kt,!1),(A=this.connectionImpl)==null||A.suspend()});I(this,"unsuspend",()=>{var A;E(this,Kt,!0),(A=this.connectionImpl)==null||A.unsuspend(),this.connect()});I(this,"getState",()=>this.connectionImpl?this.connectionImpl.getState():"disconnected");I(this,"getStatistics",()=>this.connectionImpl?V(D({},this.connectionImpl.getStatistics()),{rtt:re(s(this,vt).items()),estimatedBandwidth:this.estimatedBandwidth,connectCount:s(this,og),connectionAttemptCount:s(this,Qe)}):{rtt:{min:0,max:0,average:0,last:0},estimatedBandwidth:0,connectCount:s(this,og),connectionAttemptCount:s(this,Qe),connectionProtocol:void 0});I(this,"connect",()=>{E(this,Kt,!0),!s(this,Qg)&&E(this,Qg,d(this,jC,Gr).call(this))});I(this,"disconnect",(A="Disconnect Requested")=>{var t;E(this,Kt,!1),(t=this.connectionImpl)==null||t.close(A)});I(this,"reconnect",A=>{this.disconnect(A),this.connect()});n(this,ZC,()=>r(this,null,function*(){try{return yield this.apiClient.connect(this.config.options.getOptions())}catch(A){if(kd(A))switch(A.status){case 401:throw this.emitter.emit("error",UB(A)),UB(A);case 403:throw this.emitter.emit("error",On(A.message)),On(A.message)}throw this.emitter.emit("error",lc(A instanceof Error?A:void 0)),A}}));n(this,XC,()=>r(this,null,function*(){const A=Date.now(),t=()=>Date.now()-A;return Promise.race([ce(Eg.PING_TIMEOUT),fetch(new URL("/api/v4/connect/ping",this.config.options.get("url")).toString(),{method:"HEAD"})]).then(t,t)}));this.logger=t,this.emitter=A,this.config=e,this.apiClient=new da({publicEndpoint:this.config.options.get("url").toString(),tokenFactory:()=>this.config.options.get("authenticationToken")})}get rtt(){return s(this,vt).items().length>0?Wt(s(this,vt).items()):0}get estimatedBandwidth(){return this.connectionImpl&&"estimatedBandwidth"in this.connectionImpl&&this.connectionImpl.estimatedBandwidth?this.connectionImpl.estimatedBandwidth:Au(this.rtt)}get firstConnectionTime(){return s(this,ng)}get lastConnectionTime(){return s(this,ag)}};vt=new WeakMap,Kt=new WeakMap,Qg=new WeakMap,Qe=new WeakMap,og=new WeakMap,ng=new WeakMap,ag=new WeakMap,ZC=new WeakMap,XC=new WeakMap,jC=new WeakSet,Gr=function(){return r(this,null,function*(){var t;const A=new tu({edgeUrl:this.config.options.get("edgeUrl")});for(E(this,Qe,0);;){ft(this,Qe)._++;try{const[g,B]=yield Promise.all([s(this,ZC).call(this),s(this,XC).call(this)]),C=B/2;if(s(this,vt).clear(),s(this,vt).push(C),!s(this,Kt))break;const Q=A.select(g.edges);if(!Q)throw new x("Failed to resolve edge url",{isFatal:!0,code:"failed_to_resolve_edge_url"});Rn(g)?this.connectionImpl=yield Co.start(this.emitter,this.logger,this.apiClient,V(D({},this.config),{connectInfo:g,edgeUrl:Q}),s(this,vt)):(lA(typeof Q=="string","Edge URL is expected to be a string"),this.connectionImpl=yield oo.start(this.emitter,this.logger,V(D({},this.config),{connectInfo:g,edgeUrl:Q}),s(this,vt))),A.reset(),ft(this,og)._++,E(this,Qe,0),E(this,ag,Date.now()),s(this,ng)||E(this,ng,s(this,ag)),yield this.connectionImpl.closed()}catch(g){this.logger.info("Failed to connect",g);const B=A.shiftedEdge();B&&this.emitter.emit("telemetry event",{code:"shifted_edge",edgeUrl:typeof B=="string"?B:B.moqUrl||B.moqWsUrl}),g instanceof x?this.emitter.emit("error",g):g instanceof Error&&this.emitter.emit("error",new x(g.message,{code:"start_failed",isFatal:!1}))}if((t=this.connectionImpl)==null||t.unload(),this.connectionImpl=void 0,!s(this,Kt))break;if(!(yield this.config.reconnectHandler({reconnectRetries:s(this,Qe)}))){this.emitter.emit("error",Wn());break}if(yield ce(1e3),!s(this,Kt))break}E(this,Qg,void 0)})},I(Eg,"PING_TIMEOUT",1e3),I(Eg,"create",(A,t,e)=>new Eg(A,t,e));let no=Eg;const ao=()=>({video:V(D({},kB()),{bitRate:he()}),audio:{bitRate:he()}}),eu=()=>({width:window.innerWidth,height:window.innerHeight,bitRate:he()}),rg=class rg{constructor(A,t,e,g){I(this,"emitter");I(this,"timers",new NA);I(this,"pictureInPictureSource");I(this,"element");I(this,"currentCap");I(this,"userSpecifiedCap");I(this,"renditionLevelSource");I(this,"resizeObserver");I(this,"elementSize");I(this,"_sizeBasedResolutionCapEnabled");I(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()});I(this,"load",()=>{window.ResizeObserver&&(this.resizeObserver=new ResizeObserver(this.onResize),this.resizeObserver.observe(this.element)),this.evaluateConstraintCap()});I(this,"unsuspend",()=>{this.timers.setInterval(this.evaluateConstraintCap,rg.CHECK_SIZE_INTERVAL),this.evaluateConstraintCap()});I(this,"suspend",()=>{this.timers.unload()});I(this,"setUserSpecifiedCap",A=>{var e;const t=(e=this.getUserSpecifiedCap())!=null?e:ao();this.userSpecifiedCap=V(D({},t),{video:D(D({},t.video),A.video),audio:D(D({},t.audio),A.audio)}),this.evaluateConstraintCap()});I(this,"getUserSpecifiedCap",()=>this.userSpecifiedCap);I(this,"getCurrentConstraintCap",()=>this.currentCap);I(this,"getStatistics",()=>({constraintCap:this.getUserSpecifiedCap(),windowInnerWidth:window.innerWidth,windowInnerHeight:window.innerHeight,elementWidth:this.elementSize.width,elementHeight:this.elementSize.height,pixelRatio:window.devicePixelRatio}));I(this,"constrainSubscription",A=>{const t=this.getCurrentConstraintCap();return t&&(A.video.codec&&(A.video.bitRate=Math.min(t.video.bitRate,A.video.bitRate),A.video.width=Math.min(t.video.width,A.video.width),A.video.height=Math.min(t.video.height,A.video.height)),A.audio.codec&&(A.audio.bitRate=Math.min(t.audio.bitRate,A.audio.bitRate))),A});I(this,"onResize",A=>{A.forEach(t=>{this.elementSize={width:t.contentRect.width,height:t.contentRect.height}})});I(this,"evaluateConstraintCap",()=>{var C,Q,o,a,c;const A=this.sizeBasedResolutionCapEnabled?V(D({},ao()),{video:eu()}):ao();if(!this.resizeObserver){const h=this.element.getBoundingClientRect();this.elementSize={width:h.width,height:h.height}}if(this.sizeBasedResolutionCapEnabled){const h=window.devicePixelRatio,l=(C=this.pictureInPictureSource)==null?void 0:C.getPictureInPictureSize();this.elementSize.width>0&&this.elementSize.height>0&&(A.video.width=this.elementSize.width,A.video.height=this.elementSize.height),l&&(A.video.width=l.width,A.video.height=l.height),A.video.width*=h,A.video.height*=h}const e=this.renditionLevelSource.getRenditionLevels().find(h=>{if(h.video){const l=h.video.width/h.video.height,m=A.video.width/A.video.height;return l>m?h.video.width>A.video.width:h.video.height>A.video.height}});e&&e.video&&(A.video.width=e.video.width,A.video.height=e.video.height);const g=(Q=this.userSpecifiedCap)==null?void 0:Q.video,B=(o=this.userSpecifiedCap)==null?void 0:o.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=(a=g==null?void 0:g.bitRate)!=null?a:A.video.bitRate,A.audio.bitRate=(c=B==null?void 0:B.bitRate)!=null?c:A.audio.bitRate,Ve(A,this.currentCap)?this.currentCap=D({},A):(this.currentCap=D({},A),this.emitter.emit("constraint cap changed",A))});I(this,"enterPictureInPicture",A=>{this.pictureInPictureSource=A,this.evaluateConstraintCap()});I(this,"exitPictureInPicture",()=>{this.pictureInPictureSource=void 0,this.evaluateConstraintCap()});this.element=t;const B=this.element.getBoundingClientRect();this.elementSize={width:B.width,height:B.height},this.emitter=A,this.renditionLevelSource=e,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()}};I(rg,"CHECK_SIZE_INTERVAL",1e3),I(rg,"create",(A,t,e,g)=>new rg(A,t,e,g));let Eo=rg;const iu=5,Iu=100,gu=1e3;class ro{constructor(A,t,e,g){I(this,"timers",NA.create());I(this,"logger");I(this,"emitter");I(this,"trackContexts");I(this,"playbackSource");I(this,"isSuspended",!1);I(this,"load",()=>{this.timers.setInterval(this.emitDecodedFrames,Iu),this.timers.setInterval(this.emitDecodeRate,gu),this.emitter.on("init segment",this.onInitSegment),this.emitter.on("coded sample",this.decode)});I(this,"unload",()=>{this.trackContexts.forEach(({decoderContext:A})=>A.unload()),this.timers.unload(),this.emitter.off("init segment",this.onInitSegment),this.emitter.off("coded sample",this.decode)});I(this,"suspend",()=>{this.isSuspended=!0});I(this,"unsuspend",()=>{this.isSuspended=!1});I(this,"getBuffer",A=>{var t;return(t=this.trackContexts.get(A))==null?void 0:t.buffer});I(this,"videoDecodeRate",()=>{var B,C,Q;const A=this.trackContexts.get("video"),t=(B=A==null?void 0:A.sampleDuration)!=null?B:40,e=re((C=A==null?void 0:A.decodeTime.items())!=null?C:[]),g=re((Q=A==null?void 0:A.transportTime.items())!=null?Q:[]);return t/(e.average+g.average)});I(this,"getStatistics",()=>{var B,C,Q,o;const A=this.trackContexts.get("video"),t=re((B=A==null?void 0:A.decodeTime.items())!=null?B:[]),e=re((C=A==null?void 0:A.transportTime.items())!=null?C:[]),g=re((o=(Q=this.trackContexts.get("audio"))==null?void 0:Q.decodeTime.items())!=null?o:[]);return{videoDecodeRate:this.videoDecodeRate(),videoDecodeTime:t,audioDecodeTime:g,videoTransportTime:e}});I(this,"onInitSegment",({initSegment:A})=>{var e;const t=(e=this.trackContexts.get(A.type))==null?void 0:e.decoderContext;if(!t)throw new x("No known decoder context",{code:"no_known_decoder_context",isFatal:!1});t.initSegment(A)});I(this,"decode",A=>{const t=this.trackContexts.get(A.type);if(!t)throw new x("No known decoder context",{code:"no_known_decoder_context",isFatal:!1});if(this.isSuspended)return;t.sampleDuration=A.duration/A.timescale*1e3;const e=A.compositionTimeOffset||0,{decoderContext:g,buffer:B}=t,C=(A.timestamp+e)/A.timescale*1e3,Q=A.duration/A.timescale*1e3,o=B[B.length-1];!o||C-iu>o.end?B.push({start:C,end:C+Q}):C+Q*5<o.end?t.buffer=[{start:C,end:C+Q}]:o.end=C+Q,g.enqueue(A),this.emitDecodedFrames()});I(this,"emitDecodedFrames",()=>{let A;this.updateBufferState(),this.trackContexts.forEach(t=>{var g,B;let e;for(;(e=(B=(g=t.decoderContext).error)==null?void 0:B.call(g))!==void 0;)this.emitter.emit("error",Yn(!1,e));for(;(A=t.decoderContext.take())!==void 0;){const{statistics:C}=A;C&&(t.decodeTime.push(C.decodeTime),t.transportTime.push((C.transportTimeToWorker+C.transportTimeFromWorker)/C.samplesInBatch)),this.emitter.emit("decoded frame",A)}})});I(this,"emitDecodeRate",()=>{this.emitter.emit("video decode rate",this.videoDecodeRate())});I(this,"updateBufferState",()=>{var B,C;let A;if(this.trackContexts.forEach(Q=>{var o,a,c,h;if(!A)A=Q.buffer;else{const l=(a=(o=Q.buffer[Q.buffer.length-1])==null?void 0:o.end)!=null?a:0;((h=(c=A[A.length-1])==null?void 0:c.end)!=null?h:0)>l&&(A=Q.buffer)}}),!A)return;const t=this.playbackSource.currentTime,e=(C=(B=A[A.length-1])==null?void 0:B.end)!=null?C:0,g=t<e?"playing":"buffering";this.emitter.emit("buffer state",{buffered:A,currentTime:this.playbackSource.currentTime,isPaused:this.playbackSource.isPaused,playbackState:g})});this.logger=t,this.emitter=A,this.trackContexts=e,this.playbackSource=g}static create(A,t,e,g,B){return r(this,null,function*(){const C=new Map;for(const Q of e)switch(Q.type){case"audio":{const{OpusDecoderContext:o}=yield Promise.resolve().then(()=>yw);C.set(Q.type,{buffer:[],decoderContext:yield o.create(48e3,2),decodeTime:new W(100),transportTime:new W(100),sampleDuration:40});break}case"video":{const{H264DecoderWorkerContext:o}=yield Promise.resolve().then(()=>pw);C.set(Q.type,{buffer:[],decoderContext:yield o.create(B),decodeTime:new W(100),transportTime:new W(100),sampleDuration:40});break}}return new ro(A,t,C,g)})}}const zC=class zC{constructor(A){I(this,"emitter");I(this,"isVisibleCount",0);I(this,"isHiddenCount",0);I(this,"isOnlineCount",0);I(this,"isOfflineCount",0);I(this,"isActive",document.visibilityState==="visible");I(this,"unload",()=>{document.removeEventListener("visibilitychange",this.onVisibilityChanged),window.removeEventListener("pagehide",this.onPageHide),window.removeEventListener("online",this.onOnline),window.removeEventListener("offline",this.onOffline)});I(this,"load",()=>{document.addEventListener("visibilitychange",this.onVisibilityChanged),window.addEventListener("pagehide",this.onPageHide),window.addEventListener("online",this.onOnline),window.addEventListener("offline",this.onOffline)});I(this,"unsuspend",()=>{});I(this,"getStatistics",()=>{var A,t,e,g,B;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:(t=navigator.connection)==null?void 0:t.effectiveType,navigatorConnectionType:(e=navigator.connection)==null?void 0:e.type,navigatorSaveData:(g=navigator.connection)==null?void 0:g.saveData,navigatorDownlink:(B=navigator.connection)==null?void 0:B.downlink}});I(this,"onOnline",()=>this.isOnlineCount++);I(this,"onOffline",()=>this.isOfflineCount++);I(this,"onPageHide",A=>this.emitter.emit("pagehide",A));I(this,"onVisibilityChanged",()=>{this.setIsActive(document.visibilityState==="visible")});I(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"}};I(zC,"create",A=>new zC(A));let co=zC;const su=i=>(A,t,e)=>A.timestamp<=t||A.timestampAdded<=e-i,ve=class ve{constructor(A,t,e){I(this,"logger");I(this,"emitter");I(this,"waitingEvents",[]);I(this,"isTriggered",su(ve.EVENT_TIMEOUT));I(this,"timeSource");I(this,"timers",new NA);I(this,"load",()=>{this.timers.setInterval(this.onBufferedStateChanged,ve.EVENT_CHECK_INTERVAL),this.emitter.on("add event",this.addEvent)});I(this,"unload",()=>{this.timers.unload(),this.emitter.off("add event",this.addEvent)});I(this,"addEvent",A=>{this.logger.debug("Adding event",{event:A}),!this.waitingEvents.some(t=>typeof t.id!="undefined"&&t.id===A.id)&&this.waitingEvents.push(V(D({},A),{timestampAdded:Date.now()}))});I(this,"extractEvent",(A,t)=>{t.type==="video"&&A.channelId!==t.channelId&&this.addEvent({type:"channel switch",channelId:t.channelId,timestamp:t.timestamp/t.timescale*1e3}),t.type==="audio"&&A.type==="audio"&&t.language!==void 0&&t.language!==A.language&&this.addEvent({type:"language switch",language:t.language,timestamp:t.timestamp/t.timescale*1e3})});I(this,"onBufferedStateChanged",()=>{var B;const A=Date.now(),t=(B=this.timeSource.drift)!=null?B:0,e=this.timeSource.serverCurrentTime-t;if(this.waitingEvents.length===0)return;const g=this.waitingEvents.filter(C=>this.isTriggered(C,e,A));this.waitingEvents=this.waitingEvents.filter(C=>!this.isTriggered(C,e,A)),g.forEach(C=>{this.logger.debug("Emitting event",{event:C}),this.emitter.emit("event",C)})});this.logger=t,this.emitter=A,this.timeSource=e}};I(ve,"EVENT_TIMEOUT",5e3),I(ve,"EVENT_CHECK_INTERVAL",20),I(ve,"create",(A,t,e)=>new ve(A,t,e));let ho=ve;const St=class St{constructor(A){I(this,"emitter");I(this,"timers",NA.create());I(this,"bytesReceived",new Map);I(this,"timeoutInterval");I(this,"lastBytesUpdated",Date.now());I(this,"load",()=>{this.emitter.on("connection state",this.onConnectionState),this.timers.setInterval(()=>this.bytesReceived.forEach(A=>A.tick()),100)});I(this,"unload",()=>{this.emitter.off("connection state",this.onConnectionState),this.timers.unload()});I(this,"averageBitRate",A=>{var t,e;return((e=(t=this.bytesReceived.get(A))==null?void 0:t.average)!=null?e:0)*8});I(this,"totalBytesReceived",()=>{let A=0;return this.bytesReceived.forEach(t=>{A+=t.total}),A});I(this,"add",(A,t)=>{let e=this.bytesReceived.get(A);e||(e=new Or(20),this.bytesReceived.set(A,e)),t>0&&(this.lastBytesUpdated=Date.now(),this.timeoutInterval||(this.timeoutInterval=this.timers.setInterval(this.checkTimeout,St.UPDATE_RECEIVED_BYTES_INTERVAL))),e.add(t)});I(this,"getStatistics",()=>({bytesReceived:this.totalBytesReceived(),videoBitRate:this.averageBitRate("video"),audioBitRate:this.averageBitRate("audio")}));I(this,"onConnectionState",A=>{this.clearTimeoutInterval(),A==="connected"&&(this.lastBytesUpdated=Date.now(),this.timeoutInterval=this.timers.setInterval(this.checkTimeout,St.UPDATE_RECEIVED_BYTES_INTERVAL))});I(this,"checkTimeout",()=>{const A=Date.now()-this.lastBytesUpdated;if(this.totalBytesReceived()===0&&A>St.NO_DATA_ERROR_TIMEOUT){this.emitter.emit("error",dc()),this.emitter.emit("reconnect","no incoming data"),this.clearTimeoutInterval();return}A>St.NO_DATA_TIMEOUT&&this.totalBytesReceived()>0&&(this.emitter.emit("no data timeout",this.totalBytesReceived()),this.clearTimeoutInterval())});I(this,"clearTimeoutInterval",()=>{this.timeoutInterval&&(this.timers.clearInterval(this.timeoutInterval),this.timeoutInterval=void 0)});this.emitter=A}};I(St,"NO_DATA_ERROR_TIMEOUT",20*1e3),I(St,"NO_DATA_TIMEOUT",5*1e3),I(St,"UPDATE_RECEIVED_BYTES_INTERVAL",1e3),I(St,"create",A=>new St(A));let lo=St;const Pa=1e3,xa=50;class uo{constructor(A){I(this,"logger");I(this,"trackingState",new Map);I(this,"runningJitter",new Map);I(this,"recentJitterSamples",new Map);I(this,"load",()=>{this.logger.debug("JitterModule loaded")});I(this,"unload",()=>{this.trackingState.clear(),this.runningJitter.clear(),this.recentJitterSamples.clear(),this.logger.debug("JitterModule unloaded")});this.logger=A}static create(A){return new uo(A)}getTrackingKey(A,t){return`${A}-${t}`}recordSample(A){var l,m,y,f;const t=this.getTrackingKey(A.type,A.renditionId),e=(y=(m=(l=globalThis.performance)==null?void 0:l.now)==null?void 0:m.call(l))!=null?y:Date.now(),g=A.timestamp/A.timescale*1e3,B=this.trackingState.get(t);if(!B){this.trackingState.set(t,{lastArrivalTime:e,lastTimestampMs:g,jitterSamples:new W(Pa),interArrivalTimes:new W(Pa)}),this.runningJitter.set(t,0),this.recentJitterSamples.set(t,new W(xa));return}const C=g-B.lastTimestampMs;if(C<=0){B.lastArrivalTime=e,B.lastTimestampMs=g;return}const Q=e-B.lastArrivalTime,o=Math.abs(Q-C);B.jitterSamples.push(o),B.interArrivalTimes.push(Q);const a=(f=this.runningJitter.get(t))!=null?f:0,c=a+(o-a)/16;this.runningJitter.set(t,c);let h=this.recentJitterSamples.get(t);h||(h=new W(xa),this.recentJitterSamples.set(t,h)),h.push(o),B.lastArrivalTime=e,B.lastTimestampMs=g}getJitterForType(A){var t,e,g;for(const[B,C]of this.trackingState)if(B.startsWith(A)){if(C.jitterSamples.items().length<1)return;const o=(t=this.runningJitter.get(B))!=null?t:0,a=(g=(e=this.recentJitterSamples.get(B))==null?void 0:e.items())!=null?g:[],{min:c,max:h,average:l}=re(a);return{min:Math.round(c),max:Math.round(h),last:Math.round(l),average:Math.round(o)}}}getRunningJitter(A){for(const[t,e]of this.runningJitter)if(t.startsWith(A))return e}reset(A,t){if(A!==void 0&&t!==void 0){const e=this.getTrackingKey(A,t);this.trackingState.delete(e),this.runningJitter.delete(e),this.recentJitterSamples.delete(e)}else if(A!==void 0)for(const e of this.trackingState.keys())e.startsWith(A)&&(this.trackingState.delete(e),this.runningJitter.delete(e),this.recentJitterSamples.delete(e));else this.trackingState.clear(),this.runningJitter.clear(),this.recentJitterSamples.clear()}getStatistics(){return{audioJitter:this.getJitterForType("audio"),videoJitter:this.getJitterForType("video")}}}const Bu=()=>window.AudioContext||window.webkitAudioContext,_C=class _C extends it{constructor(){super();I(this,"context",new(Bu()));I(this,"timers",NA.create());I(this,"previousCurrentTime",0);I(this,"_isStuck",!1);I(this,"mediaStreamDestination");I(this,"unload",()=>(this.timers.unload(),this.context.removeEventListener("statechange",this.onStateChange),this.context.state!=="closed"?this.context.close():Promise.resolve()));I(this,"createGain",()=>this.context.createGain());I(this,"createBuffer",(t,e,g)=>this.context.createBuffer(t,e,g));I(this,"createBufferSource",()=>this.context.createBufferSource());I(this,"getMediaStreamDestination",()=>(this.mediaStreamDestination||(this.mediaStreamDestination=this.context.createMediaStreamDestination()),this.mediaStreamDestination));I(this,"getDefaultDestination",()=>this.context.destination);I(this,"createSplitter",()=>this.context.createChannelSplitter(2));I(this,"resume",()=>r(this,null,function*(){try{return yield Promise.race([this.context.resume(),kQ(1e3,rc())])}catch(t){throw this.suspend().catch(F),t}}));I(this,"suspend",()=>r(this,null,function*(){var t;yield(t=this.context.suspend())!=null?t:Promise.resolve()}));I(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},_C.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}};I(_C,"CHECK_INTERVAL",1e3);let wo=_C;const $C=class $C extends it{constructor(t,e,{muted:g,reInitWhenStuck:B}){super();I(this,"logger");I(this,"audio");I(this,"gainNode");I(this,"splitter");I(this,"_volume",1);I(this,"_userProvidedMuted",!1);I(this,"_muted",!1);I(this,"startTime",0);I(this,"samples",new Float32Array(new ArrayBuffer(5*960*4*2)));I(this,"preInitSampleQueue",new W(500));I(this,"unplayedBufferSources",new W(100));I(this,"sampleRate",48e3);I(this,"channels",2);I(this,"index",0);I(this,"clockSource");I(this,"clockDelta");I(this,"startTimeIsInvalidated",!0);I(this,"lastSampleTimestamp",0);I(this,"reInitWhenStuck");I(this,"ignoreSuspendCalls",!1);I(this,"isActivated",!1);I(this,"unload",()=>r(this,null,function*(){var t,e;(t=this.gainNode)==null||t.disconnect(),yield(e=this.audio)==null?void 0:e.unload(),this.reset(),this.audio=void 0,this.gainNode=void 0}));I(this,"suspend",()=>{this.setGain(0)});I(this,"unsuspend",()=>{var t;this.setGain(this._volume),this.ignoreSuspendCalls=!!this.audio,(t=this.audio)==null||t.suspend().then(()=>r(this,null,function*(){yield this.resume(),this.ignoreSuspendCalls=!1})).catch(()=>{this.ignoreSuspendCalls=!1,this.emit("state change","suspended")})});I(this,"flush",()=>{if(!this.audio||!this.gainNode)throw new x("AudioContext must be initialized to flush",{isFatal:!1,code:"audiocontext_must_be_initialized"});const t=this.samples.length/this.channels,e=this.audio.createBufferSource(),g=this.audio.createBuffer(this.channels,t,this.sampleRate);let B=0;for(let Q=0;Q<this.channels;Q++){B=Q;const o=g.getChannelData(Q);for(let a=0;a<t;a++)o[a]=this.samples[B],B+=this.channels}const C=Math.max(this.startTime,0);e.buffer=g,e.connect(this.gainNode),this.splitter&&e.connect(this.splitter),e.start(C),this.unplayedBufferSources.push([C,e]),this.startTime+=g.duration});I(this,"onDecodedFrame",t=>{if(!(this.gainNode&&this.audio&&this.audio.isRunning)){if(t.type==="audio"){this.preInitSampleQueue.push(V(D({},t),{data:t.data.slice(0,t.data.length)}));const e=this.clockSource.currentTime;this.preInitSampleQueue.filterPop(({timestamp:g,timescale:B})=>g/B*1e3>e)}return}for(;!this.preInitSampleQueue.isEmpty();){const e=this.preInitSampleQueue.items();this.preInitSampleQueue.clear(),e.forEach(this.onDecodedFrame)}if(this.unplayedBufferSources.filterPop(([e,g])=>{var B,C;return((C=(B=this.audio)==null?void 0:B.currentTime)!=null?C:0)<e}),t.type==="audio"){const e=t.timestamp/t.timescale*1e3;if(e<this.lastSampleTimestamp&&(this.logger.info("Unordered timestamp - invalidating start time"),this.startTimeIsInvalidated=!0),this.lastSampleTimestamp=e,this.startTimeIsInvalidated){const g=this.audio.currentTime*1e3,B=this.clockSource.currentTime,C=(g+e-B)/1e3;this.clockDelta=B-g,this.startTime=C,this.startTimeIsInvalidated=!1,this.unplayedBufferSources.items().forEach(([Q,o])=>{C<=Q&&o.stop()})}this.samples.set(t.data,this.index),this.index+=t.data.length,this.channels=t.channels,this.sampleRate=t.sampleRate,this.samples.length<=this.index&&(this.index=0,this.flush())}});I(this,"play",()=>r(this,null,function*(){this.audio=this.getAudioContext(),yield this.resume()}));I(this,"pause",()=>{});I(this,"flushBuffer",()=>{this.unplayedBufferSources.items().forEach(([t,e])=>e.stop()),this.index=0});I(this,"resume",()=>r(this,null,function*(){var t;if(!this._userProvidedMuted)try{yield(t=this.audio)==null?void 0:t.resume(),this._muted=this._userProvidedMuted,this.startTimeIsInvalidated=!0}catch(e){throw this._muted=!0,e}}));I(this,"getAudioContext",()=>this.audio?this.audio:this.setupContext());I(this,"setupContext",()=>{var t,e,g;return(t=this.audio)==null||t.unload(),this.audio=new wo,this.audio.on("state",B=>{this.logger.info("AudioContext state change",{state:B}),B==="running"&&(this._muted=this._userProvidedMuted,this.setGain(this._volume)),!this.ignoreSuspendCalls&&this.emit("state change",B)}),this.audio.on("stuck",()=>{this.reInitWhenStuck&&(this.logger.info("Re-init audio context"),this.setupContext(),this.resume().catch(F),this.emit("stuck"))}),(e=this.gainNode)==null||e.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});I(this,"setGain",t=>{this.gainNode&&(this.gainNode.gain.value=this._muted?0:t)});this._muted=g,this._userProvidedMuted=g,this.logger=t,this.clockSource=e,this.reInitWhenStuck=B}get isContextRunning(){var t;return((t=this.audio)==null?void 0:t.state)==="running"}get volume(){return this._volume}set volume(t){this._volume=t,this.muted||this.setGain(t)}get seekTime(){return 0}get isSeeking(){return!1}get muted(){var t;return this._muted||!((t=this.audio)!=null&&t.isRunning)}set muted(t){this._userProvidedMuted=t,this._muted=t,this.setGain(this._volume)}get isPaused(){return!1}get currentTime(){var t;return!this.audio||!this.audio.isRunning||this.audio.isStuck?this.clockSource.currentTime:this.audio.currentTime*1e3+((t=this.clockDelta)!=null?t:0)}set currentTime(t){this.logger.debug("setting current time to",{currentTime:t}),this.startTimeIsInvalidated=!0}get audioNode(){return this.splitter}useMediaStreamDestination(){var g;const e=this.getAudioContext().getMediaStreamDestination();return(g=this.gainNode)==null||g.connect(e),e}useDefaultDestination(){var g;const e=this.getAudioContext().getDefaultDestination();return(g=this.gainNode)==null||g.connect(e),e}};I($C,"create",(t,e,g)=>new $C(t,e,g));let aC=$C;class Cu{constructor(){n(this,Qt);n(this,rB,[]);n(this,Yt,document.createElement("canvas"));n(this,LA);n(this,Ki,window.devicePixelRatio||1);I(this,"config",{backgroundColor:"rgba(0,0,0,0.6)",textPadding:8,fontSize:"28px",lineGap:16});const A=s(this,Yt).getContext("2d",{alpha:!0});if(!A)throw new Error("Failed to create 2d context");E(this,LA,A),d(this,Qt,Dg).call(this)}get canvas(){return s(this,Yt)}setActiveCues(A){E(this,rB,A)}render(A,t=!1){const e=s(this,rB).flatMap(Q=>Q.text.split(`
|
|
3
3
|
`).flatMap(a=>d(this,Qt,Rr).call(this,a,A.width)).map(a=>{d(this,Qt,Dg).call(this);const c=s(this,LA).measureText(a);return{text:a,measurement:c,size:{height:c.fontBoundingBoxAscent+c.fontBoundingBoxDescent+this.config.textPadding*2,width:c.width+this.config.textPadding*2}}})),g=Math.max(...e.map(Q=>Q.size.width)),B=e.reduce((Q,{size:o})=>Q+o.height,0)+(e.length-1)*this.config.lineGap;let C=0;d(this,Qt,kr).call(this,g,B),s(this,LA).clearRect(0,0,s(this,Yt).width,s(this,Yt).height);for(const{size:Q,text:o}of e)d(this,Qt,Dg).call(this),s(this,LA).fillStyle=this.config.backgroundColor,s(this,LA).fillRect(0,C,Q.width,Q.height),d(this,Qt,Dg).call(this),s(this,LA).fillText(o,this.config.textPadding,C+this.config.textPadding),C+=Q.height+this.config.lineGap;t&&(s(this,LA).strokeStyle="red",s(this,LA).strokeRect(0,0,A.width,s(this,Yt).height))}}rB=new WeakMap,Yt=new WeakMap,LA=new WeakMap,Ki=new WeakMap,Qt=new WeakSet,kr=function(A,t){s(this,Yt).width=A*s(this,Ki),s(this,Yt).height=t*s(this,Ki),s(this,LA).scale(s(this,Ki),s(this,Ki)),this.canvas.style.width=`${A}px`,this.canvas.style.height=`${t}px`},Dg=function(){s(this,LA).fillStyle="white",s(this,LA).textAlign="left",s(this,LA).textBaseline="top",s(this,LA).font=`${this.config.fontSize} sans-serif`},Rr=function(A,t){const e=[],g=A.split(" ");let B="";for(;g.length>0;){d(this,Qt,Dg).call(this);let C=0;for(;s(this,LA).measureText(B+(B.length>0?" ":"")+g[0]).width+this.config.textPadding*2<=t&&g.length>0;)C++,B+=(B.length>0?" ":"")+g.shift();if(C==0){e.push(g.shift()||""),B="";continue}e.push(B),B=""}return e};const Qu=`
|
|
4
4
|
precision mediump float;
|
|
@@ -46,8 +46,8 @@ void main() {
|
|
|
46
46
|
texture_coordinate = position;
|
|
47
47
|
gl_Position = model * vec4(position, 0.0, 1.0);
|
|
48
48
|
}
|
|
49
|
-
`,Xa={width:256,codedWidth:256,height:144,codedHeight:144},ja={preserveDrawingBuffer:!1,alpha:!1,depth:!1,stencil:!1,antialias:!1,premultipliedAlpha:!1},lB=class lB extends it{constructor(){super();I(this,"canvas",document.createElement("canvas"));I(this,"context",Wa(this.canvas,ja));I(this,"pixelShader",tI(this.context,this.context.FRAGMENT_SHADER,Va));I(this,"vertexShader",tI(this.context,this.context.VERTEX_SHADER,Za));I(this,"buffer",Oa(this.context,lB.SQUARE_VERTICES));I(this,"program",Do(this.context,this.vertexShader,this.pixelShader));I(this,"textures",{y:Ai(this.context),u:Ai(this.context),v:Ai(this.context)});I(this,"textRenderer");I(this,"size",Xa);I(this,"onContextLost",t=>{this.textRenderer=void 0;const e=new Error(t instanceof WebGLContextEvent?t.statusMessage:"webgl context lost");this.emit("context lost",uc(e)),t.preventDefault()});I(this,"onContextRestored",()=>{this.emit("context restored"),this.context=Wa(this.canvas,ja),this.pixelShader=tI(this.context,this.context.FRAGMENT_SHADER,Va),this.vertexShader=tI(this.context,this.context.VERTEX_SHADER,Za),this.buffer=Oa(this.context,lB.SQUARE_VERTICES),this.program=Do(this.context,this.vertexShader,this.pixelShader),this.textures={y:Ai(this.context),u:Ai(this.context),v:Ai(this.context)},this.load()});I(this,"load",()=>{this.context.useProgram(this.program),this.setupPositionVertexAttributes(),this.setSize(Xa),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(this.rec709())});I(this,"unload",()=>{var e;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),(e=this.context.getExtension("WEBGL_lose_context"))==null||e.loseContext()});I(this,"resetSize",()=>{this.setSize({width:this.size.width/2,height:this.size.height/2,codedHeight:this.size.codedHeight/2,codedWidth:this.size.codedWidth/2})});I(this,"render",(t,e)=>{var g;this.context.useProgram(this.program),this.setSize({width:t.width,height:t.height,codedWidth:t.codedWidth,codedHeight:t.codedHeight}),this.setConversionMatrix(this.rec709()),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,t.data[0]),this.context.activeTexture(this.context.TEXTURE1),this.updateTexture(this.textures.u,this.size.codedWidth/2,this.size.codedHeight/2,t.data[1]),this.context.activeTexture(this.context.TEXTURE2),this.updateTexture(this.textures.v,this.size.codedWidth/2,this.size.codedHeight/2,t.data[2]),this.context.drawArrays(this.context.TRIANGLE_STRIP,0,4),this.textRenderer&&this.textRenderer.render({width:Math.max(e.clientWidth,960)*window.devicePixelRatio,height:Math.max(e.clientHeight,540)*window.devicePixelRatio,padding:-parseInt((g=e.style.getPropertyValue("--vindral-control-bar-offset"))!=null?g:"0",10)})});I(this,"updateTexture",(t,e,g,B)=>{const Q=this.context.LUMINANCE,o=this.context.UNSIGNED_BYTE;this.context.bindTexture(this.context.TEXTURE_2D,t),this.context.texImage2D(this.context.TEXTURE_2D,0,Q,e,g,0,Q,o,B)});I(this,"setupPositionVertexAttributes",()=>{const t=this.context.getAttribLocation(this.program,"position");this.context.enableVertexAttribArray(t),this.context.vertexAttribPointer(t,2,this.context.FLOAT,!1,0,0)});I(this,"setSize",t=>{Ve(t,this.size)||(this.size=t,this.canvas.setAttribute("width",t.width.toString()),this.canvas.setAttribute("height",t.height.toString()),this.context.viewport(0,0,t.width,t.height),this.setModelMatrix(t.width/t.codedWidth,t.height/t.codedHeight))});I(this,"setModelMatrix",(t,e)=>{const g=this.context.getUniformLocation(this.program,"model");this.context.uniformMatrix4fv(g,!1,this.transformMatrix(t,e))});I(this,"setConversionMatrix",t=>{const e=this.context.getUniformLocation(this.program,"conversion");this.context.uniformMatrix4fv(e,!1,t)});I(this,"transformMatrix",(t,e)=>[2/t,0,0,0,0,-2/e,0,0,0,0,2/1,0,-1,1,0,1]);I(this,"rec709",()=>[1.16438,0,1.79274,-.97295,1.16438,-.21325,-.53291,.30148,1.16438,2.1124,0,-1.1334,0,0,0,1]);I(this,"rec601",()=>[1.16438,0,1.59603,-.87079,1.16438,-.39176,-.81297,.52959,1.16438,2.01723,0,-1.08139,0,0,0,1]);this.canvas.addEventListener("webglcontextlost",this.onContextLost),this.canvas.addEventListener("webglcontextrestored",this.onContextRestored,!1),this.canvas.style.width="100%",this.canvas.style.position="relative"}getTextRenderer(){return this.textRenderer||(this.textRenderer=new nu(this.context)),this.textRenderer}};I(lB,"SQUARE_VERTICES",new Float32Array([0,0,0,1,1,0,1,1]));let mo=lB;const eQ=class eQ{constructor(A,t,e,g){I(this,"oldTimestampLimit",400);I(this,"pool");I(this,"logger");I(this,"videoRenderer",new mo);I(this,"renderQueue",[]);I(this,"clockSource");I(this,"isFirstFrame",!0);I(this,"animationFrameRequest");I(this,"renderedFrameCount",0);I(this,"rendererDroppedFrameCount",0);I(this,"renderTargetSize");I(this,"load",()=>{this.videoRenderer.load()});I(this,"unload",()=>(this.stopRender(),this.videoRenderer.unload(),Promise.resolve()));I(this,"suspend",()=>{this.renderQueue=[],this.stopRender()});I(this,"unsuspend",()=>{this.animationFrameRequest=requestAnimationFrame(this.render)});I(this,"element",()=>this.videoRenderer.canvas);I(this,"getStatistics",()=>({renderedFrameCount:this.renderedFrameCount,rendererDroppedFrameCount:this.rendererDroppedFrameCount,contextLostCount:0,contextRestoredCount:0}));I(this,"resetSize",()=>{this.videoRenderer.resetSize()});I(this,"setActiveCues",(A,t)=>{this.videoRenderer.getTextRenderer().setActiveCues(A,t)});I(this,"onDecodedFrame",A=>{if(A.type==="video")if(this.isFirstFrame)this.isFirstFrame=!1,requestAnimationFrame(()=>{this.renderSample(A)});else{const t=(this.clockSource.currentTime-this.oldTimestampLimit)/1e3;this.renderQueue=this.renderQueue.filter(e=>{const g=e.timestamp/e.timescale,B=A.timestamp/A.timescale,C=g>t&&g<=B;return C||this.pool.reclaim(e.buffer),C}),this.renderQueue.push(A)}});I(this,"render",()=>{const A=this.clockSource.currentTime;let t=this.renderQueue[0],e,g=0;for(;t&&(t.timestamp+(t.compositionTimeOffset||0))/t.timescale*1e3<=A;)t=this.renderQueue.shift(),t&&(g++,e&&this.pool.reclaim(e.buffer),e=t),t=this.renderQueue[0];e&&this.renderSample(e),this.rendererDroppedFrameCount+=Math.max(g-1,0),this.animationFrameRequest=requestAnimationFrame(this.render)});I(this,"renderSample",A=>{this.renderedFrameCount++,this.videoRenderer.render(A,this.renderTargetSize),this.pool.reclaim(A.buffer)});I(this,"stopRender",()=>{this.animationFrameRequest&&cancelAnimationFrame(this.animationFrameRequest)});this.logger=A,this.clockSource=t,this.pool=e,this.renderTargetSize=g||this.videoRenderer.canvas}};I(eQ,"create",(A,t,e,g)=>new eQ(A,t,e,g));let EC=eQ;class za{constructor(){n(this,Ye,[]);E(this,Ye,[])}addTextTrack(A,t,e){const g=[],B={kind:A,label:t,language:e,mode:"disabled",cues:g,addCue:C=>{g.push(C)},removeCue:C=>{const Q=g.findIndex(o=>o===C);Q!==-1&&g.splice(Q,1)}};return s(this,Ye).push(B),B}set language(A){s(this,Ye).forEach(t=>{t.language===A?t.mode="showing":t.mode="hidden"})}get language(){var A;return(A=s(this,Ye).find(t=>t.mode==="showing"))==null?void 0:A.language}getActiveCues(A){const t=s(this,Ye).find(e=>e.mode==="showing");return t?t.cues.filter(({startTime:e,endTime:g})=>A>=e&&A<=g):[]}}Ye=new WeakMap;const ti=(i,A)=>{let t;for(t=A;i>1;i--)t+=A;return t};class au{constructor(){I(this,"audio");I(this,"unmute",()=>this.audio.play().catch(F));const A=document.createElement("div");A.innerHTML="<audio x-webkit-airplay='deny'></audio>";const t=A.children.item(0);if(t instanceof HTMLAudioElement)this.audio=t,this.audio.controls=!1,this.audio.disableRemotePlayback=!0,this.audio.preload="auto",this.audio.src="data:audio/mpeg;base64,//uQx"+ti(23,"A")+"WGluZwAAAA8AAAACAAACcQCA"+ti(16,"gICA")+ti(66,"/")+"8AAABhTEFNRTMuMTAwA8MAAAAAAAAAABQgJAUHQQAB9AAAAnGMHkkI"+ti(320,"A")+"//sQxAADgnABGiAAQBCqgCRMAAgEAH"+ti(15,"/")+"7+n/9FTuQsQH//////2NG0jWUGlio5gLQTOtIoeR2WX////X4s9Atb/JRVCbBUpeRUq"+ti(18,"/")+"9RUi0f2jn/+xDECgPCjAEQAABN4AAANIAAAAQVTEFNRTMuMTAw"+ti(97,"V")+"Q==",this.audio.loop=!1,this.audio.load();else throw new Error("Failed to create audio tag")}}const iQ=class iQ{constructor(A,t,e,g,B){I(this,"logger");I(this,"emitter");I(this,"audioPlayer");I(this,"videoPlayer");I(this,"pool");I(this,"unmuter",new au);I(this,"_isPaused",!1);I(this,"isDisconnected",!1);I(this,"timers",new NA);I(this,"textTracks",new za);I(this,"playbackRate");I(this,"reset",()=>{});I(this,"load",()=>{this.audioPlayer.useDefaultDestination(),this.emitter.on("decoded frame",this.onDecodedFrame),this.emitter.on("flush buffers",this.flushBuffers),this.videoPlayer.load(),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)});I(this,"unload",()=>{this.emitter.off("decoded frame",this.onDecodedFrame),this.emitter.off("flush buffers",this.flushBuffers),this.audioPlayer.unload(),this.videoPlayer.unload(),this.timers.unload()});I(this,"suspend",()=>{this.videoPlayer.suspend(),this.audioPlayer.suspend()});I(this,"unsuspend",()=>{this.videoPlayer.unsuspend(),this.audioPlayer.unsuspend()});I(this,"element",()=>this.videoPlayer.element());I(this,"getStatistics",()=>this.videoPlayer.getStatistics());I(this,"flushBuffers",()=>{this.audioPlayer.flushBuffer()});I(this,"activateAudioPlayer",()=>(this.isDisconnected&&(this.isDisconnected=!1,this.audioPlayer.useDefaultDestination()),this._isPaused=!1,this.unmuter.unmute(),this.audioPlayer.play()));I(this,"onDecodedFrame",A=>{try{this.audioPlayer.onDecodedFrame(A)}catch(t){t instanceof Error&&this.emitter.emit("error",Tn(!1,t))}this.videoPlayer.onDecodedFrame(A)});this.logger=t,this.emitter=A,this.pool=e,this.audioPlayer=aC.create(this.logger.createContext("AudioPlayerModule"),g,{muted:B,reInitWhenStuck:!0}),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=EC.create(this.logger.createContext("VideoPlayerModule"),this.audioPlayer,this.pool)}get volume(){return this.audioPlayer.volume}set volume(A){this.audioPlayer.volume=A}get muted(){return this.audioPlayer.muted}set muted(A){const t=this.muted;this.audioPlayer.muted=A,!A&&t&&this.activateAudioPlayer().catch(F)}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 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")}};I(iQ,"create",(A,t,e,g,B)=>new iQ(A,t,e,g,B));let So=iQ;const IQ=class IQ{constructor(A,t,e,g,{muted:B,type:C,poster:Q}){I(this,"logger");I(this,"emitter");I(this,"mediaElement");I(this,"audioPlayer");I(this,"videoPlayer");I(this,"pool");I(this,"isDisconnected",!0);I(this,"_userProvidedMuted",!1);I(this,"timers",new NA);I(this,"volumeState");I(this,"textTracks",new za);I(this,"reset",()=>{});I(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.timers.setInterval(()=>{if(!this.textTracks.language)return;const A=this.textTracks.getActiveCues(this.currentTime/1e3);this.videoPlayer.setActiveCues(A,{width:this.mediaElement.element.clientWidth,height:this.mediaElement.element.clientHeight})},100)});I(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.mediaElement.unload(),this.timers.unload(),this.audioPlayer.unload(),this.videoPlayer.unload()});I(this,"suspend",()=>{this.videoPlayer.suspend(),this.audioPlayer.suspend()});I(this,"unsuspend",()=>{this.videoPlayer.unsuspend(),this.audioPlayer.unsuspend()});I(this,"element",()=>this.mediaElement);I(this,"getStatistics",()=>this.videoPlayer.getStatistics());I(this,"activateAudioPlayer",()=>(this.isDisconnected&&this.connectStreams(),this.audioPlayer.play()));I(this,"flushBuffers",()=>{this.audioPlayer.flushBuffer()});I(this,"resetCanvasSize",()=>{this.videoPlayer.resetSize()});I(this,"onEnterIOSHack",()=>{this.mediaElement._iosHackEnterPiPMode()});I(this,"onExitIOSHack",()=>{this.mediaElement._iosHackExitPiPMode()});I(this,"onDecodedFrame",A=>{try{this.audioPlayer.onDecodedFrame(A)}catch(t){t instanceof Error&&this.emitter.emit("error",Tn(!1,t))}this.videoPlayer.onDecodedFrame(A)});I(this,"connectStreams",()=>{const A=this.videoPlayer.element().captureStream(),t=this.audioPlayer.useMediaStreamDestination().stream,e=[];e.push(...A.getTracks(),...t.getTracks()),this.mediaElement.element.srcObject=new MediaStream(e),this.isDisconnected=!1});I(this,"updateVolumeState",()=>{const A={isMuted:this.muted,volume:this.volume};Ve(A,this.volumeState)||(this.volumeState=A,this.emitter.emit("volume state",this.volumeState))});this.logger=t,this.emitter=A,this.pool=e,this._userProvidedMuted=B,this.mediaElement=new TQ({poster:Q,type:C,muted:B,autoplay:!1,logger:this.logger.createContext("MediaElement")}),this.mediaElement.on("volume state",o=>{this.updateVolumeState(),!o.isMuted&&!this.audioPlayer.isContextRunning&&this.activateAudioPlayer().catch(F),o.isMuted||(this._userProvidedMuted=!1)}),this.mediaElement.on("media element state",o=>{o==="paused"&&this.audioPlayer.flushBuffer(),this.emitter.emit("media element state",o)}),this.audioPlayer=aC.create(this.logger.createContext("AudioPlayerModule"),g,{muted:!1,reInitWhenStuck:!1}),this.audioPlayer.on("stuck",()=>{this.isDisconnected=!0}),this.audioPlayer.on("state change",o=>{o==="suspended"||o==="interrupted"?this.mediaElement.muted=!0:o==="running"&&(this.mediaElement.muted=this._userProvidedMuted||document.visibilityState==="hidden"),this.updateVolumeState()}),this.videoPlayer=EC.create(this.logger.createContext("VideoPlayerModule"),this.audioPlayer,this.pool,this.mediaElement.element),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 t=this.muted;this._userProvidedMuted=A,this.mediaElement.muted=A,!A&&t&&this.activateAudioPlayer().catch(F)}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 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()}};I(IQ,"create",(A,t,e,g,B)=>new IQ(A,t,e,g,B));let yo=IQ;const Eu=()=>i=>_a(i.buffered.start(0),i.buffered.end(i.buffered.length-1)),_a=(i,A)=>t=>t.remove(Math.max(0,i),Math.min(Number.POSITIVE_INFINITY,A)),$a=i=>A=>A.appendBuffer(i),ru=i=>A=>A.changeType(i),cu=i=>A=>i(A);class hu{constructor(A){I(this,"commandQueue",[]);I(this,"sourceBuffer");I(this,"currentInit");I(this,"handleQueue",()=>{var A;this.sourceBuffer.updating||(A=this.commandQueue.shift())==null||A.execute(this.sourceBuffer)});I(this,"appendBuffer",(A,t)=>new Promise((e,g)=>{if(t&&this.currentInit!==t){const C=new ji($a(t),e,g);this.commandQueue.push(C),this.currentInit=t}const B=new ji($a(A),e,g);this.commandQueue.push(B),this.handleQueue()}));I(this,"execute",A=>new Promise((t,e)=>{const g=new ji(cu(A),t,e);this.commandQueue.push(g),this.handleQueue()}));I(this,"buffered",()=>this.sourceBuffer.buffered);I(this,"removeFromMediaSource",A=>{A.removeSourceBuffer(this.sourceBuffer)});I(this,"changeType",A=>new Promise((t,e)=>{const g=new ji(ru(A),t,e);this.commandQueue.push(g),this.handleQueue()}));I(this,"removeBuffer",(A,t)=>new Promise((e,g)=>{const B=new ji(_a(A,t),e,g);this.commandQueue.push(B),this.handleQueue()}));I(this,"flush",()=>new Promise((A,t)=>{const e=new ji(Eu,A,t);this.commandQueue.push(e),this.handleQueue()}));this.sourceBuffer=A,this.sourceBuffer.addEventListener("updateend",this.handleQueue)}}class AE extends it{constructor(){super();I(this,"MediaSource",Sg());I(this,"mediaSource",new this.MediaSource);I(this,"isOpen",()=>this.mediaSource.readyState==="open");I(this,"isClosed",()=>this.mediaSource.readyState==="closed");I(this,"isEnded",()=>this.mediaSource.readyState==="ended");I(this,"createObjectURL",()=>URL.createObjectURL(this.mediaSource));I(this,"attach",t=>{const e=t;if("srcObject"in e)try{e.srcObject=this.mediaSource}catch(g){if(g instanceof Error&&g.name!=="TypeError")throw g;e.src=this.createObjectURL()}else t.src=this.createObjectURL()});I(this,"detach",t=>{if(this.mediaSource&&this.mediaSource.readyState==="open")try{this.mediaSource.endOfStream()}catch(e){}t.srcObject&&(t.srcObject=null),t.src!==""&&(URL.revokeObjectURL(t.src),t.removeAttribute("src")),t.load()});I(this,"addSourceBuffer",t=>{const e=this.mediaSource.addSourceBuffer(t);return new hu(e)});I(this,"removeSourceBuffer",t=>{t.removeFromMediaSource(this.mediaSource)});I(this,"endOfStream",t=>{this.mediaSource.endOfStream(t)});I(this,"onSourceOpen",()=>{this.setDurationIfNeeded(),this.emit("source open")});I(this,"onSourceEnded",()=>this.emit("source ended"));I(this,"onSourceClosed",()=>this.emit("source close"));I(this,"setDurationIfNeeded",()=>{if(Number.isNaN(this.mediaSource.duration)&&this.mediaSource.readyState==="open"){for(let t=0;t<this.mediaSource.sourceBuffers.length;t++){const e=this.mediaSource.sourceBuffers[t];if(e!=null&&e.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)}}I(AE,"isTypeSupported",t=>{var e,g;return(g=(e=Sg())==null?void 0:e.isTypeSupported(t))!=null?g:!1});class tE{constructor(){I(this,"initSegments",new Map);I(this,"set",(A,t,e)=>{var B;const g=(B=this.initSegments.get(A))!=null?B:new Map;g.set(t,e),this.initSegments.set(A,g)});I(this,"get",(A,t)=>{var e;return(e=this.initSegments.get(A))==null?void 0:e.get(t)})}}function du(i,{mediaSource:A,mimeType:t,codec:e}){return V(D({},i),{state:"initialized",mimeType:t,codec:e,sourceBuffer:A.addSourceBuffer(t),isWorkingOnPendingSamples:!1,sequenceNumber:0,lastBufferCleanupTime:Date.now()})}function eE({initSegments:i,pendingSamples:A}){return{state:"uninitialized",initSegments:i!=null?i:new tE,sequenceNumber:0,isWorkingOnPendingSamples:!1,hasFirstSync:!!A,pendingSamples:A!=null?A:[],consecutiveQuotaExceededErrorCount:0,successfulAppendCalls:0}}const gQ=class gQ{constructor(A,t,e){I(this,"maxChunkSize",20);I(this,"minConsecutiveErrorsBeforeEmit",5);I(this,"maxSecondsInBuffer",60);I(this,"logger");I(this,"timers",NA.create());I(this,"emitter");I(this,"mediaElement");I(this,"mediaSource",new AE);I(this,"trackContexts",new Map);I(this,"autoRecoverFromMediaErrors",!0);I(this,"quotaErrorCount",0);I(this,"recoveredFromErrorCount",0);I(this,"sourceOpenStartTime",Date.now());I(this,"sourceOpenEndTime",Date.now());I(this,"pendingTracksToAddSourceBuffers");I(this,"hasAddedInitialPosterFrame",!0);I(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)});I(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=[]),this.timers.unload(),this.logger.debug("Unloaded module")});I(this,"getStatistics",()=>{var t,e,g,B;const A={quotaErrorCount:this.quotaErrorCount,mediaSourceOpenTime:this.sourceOpenEndTime-this.sourceOpenStartTime,successfulAudioAppendsCalls:(t=this.trackContexts.get("audio"))==null?void 0:t.successfulAppendCalls,successfulVideoAppendCalls:(e=this.trackContexts.get("video"))==null?void 0:e.successfulAppendCalls};if(this.mediaElement instanceof HTMLVideoElement){const C=(B=(g=this.mediaElement).getVideoPlaybackQuality)==null?void 0:B.call(g);A.totalVideoFrames=C==null?void 0:C.totalVideoFrames,A.droppedVideoFrames=C==null?void 0:C.droppedVideoFrames}return A});I(this,"flushBuffers",()=>{this.trackContexts.forEach(A=>{A.pendingSamples=[],A.hasFirstSync=!1,A.state!=="uninitialized"&&this.mediaSource.isOpen()&&A.sourceBuffer.removeBuffer(0,Number.POSITIVE_INFINITY).catch(t=>{this.logger.error("Failed to remove buffer",t)})})});I(this,"setTrackContexts",(A=new Map)=>{this.logger.debug("setTrackContexts"),["audio","video"].forEach(e=>{var C,Q,o,a;const g=(Q=(C=A.get(e))==null?void 0:C.pendingSamples)!=null?Q:[],B=(o=A.get(e))==null?void 0:o.initSegments;for(;g.length>0&&!((a=g[0])!=null&&a.isSync);)g.shift();this.trackContexts.set(e,eE({pendingSamples:g,initSegments:B}))})});I(this,"setSourceBuffers",A=>r(this,null,function*(){if(this.mediaSource.isClosed()){this.pendingTracksToAddSourceBuffers=A;return}let t=!0;for(const e of A){const g=this.trackContexts.get(e.type);if(!g||g.state==="uninitialized"||g.mimeType!==e.mimeType){t=!1;break}}if(t){this.logger.debug("Already setup with the correct mime types");return}for(const e of A){let g=this.trackContexts.get(e.type);g||(g=eE({pendingSamples:[],initSegments:new tE}),this.trackContexts.set(e.type,g)),g.state==="initialized"?e.mimeType!==g.mimeType&&(yield g.sourceBuffer.changeType(e.mimeType)):this.trackContexts.set(e.type,du(g,{mimeType:e.mimeType,mediaSource:this.mediaSource,codec:e.codec}))}}));I(this,"getBuffer",A=>{const t=[];if(this.mediaSource.isClosed())return[];const e=this.trackContexts.get(A);if(!e||e.state==="uninitialized")return[];try{const g=e.sourceBuffer.buffered();if(!g)return[];for(let B=0;B<g.length;B++)t.push({start:g.start(B)*1e3,end:g.end(B)*1e3});return t}catch(g){return[]}});I(this,"init",({initSegment:A,mimeType:t})=>{this.logger.debug("Added init segment",{channel:A.channelId,renditionId:A.renditionId});const e=this.trackContexts.get(A.type);if(!e)throw RB(A.type,A.renditionId);e.state==="initialized"&&(e.mimeType=t);const g=ed({codec:A.codec,timescale:A.timescale,initData:A.data});g&&e.initSegments.set(A.channelId,A.renditionId,new Uint8Array(g))});I(this,"append",(A,t)=>r(this,null,function*(){var Q;const e=A[0];if(!e)return;const g=this.trackContexts.get(e.type),B=g==null?void 0:g.initSegments.get(e.channelId,e.renditionId);if(this.mediaSource.isClosed())return;if(!B)throw ac(e.renditionId,e.channelId);if(!g)throw RB(e.type,e.renditionId);if(g.state==="uninitialized")throw Ec(e.type,e.renditionId);if(t){const o=(e.timestamp+((Q=e.compositionTimeOffset)!=null?Q:0))/e.timescale;yield g.sourceBuffer.removeBuffer(o,Number.POSITIVE_INFINITY);const a=g.previousSample;if(a&&a.codec!==e.codec&&g.sourceBuffer.changeType)try{yield g.sourceBuffer.changeType(g.mimeType)}catch(c){}"fragmented"in e||(yield g.sourceBuffer.appendBuffer(B))}const C=Math.max(0,e.timestamp/e.timescale-this.maxSecondsInBuffer);C>0&&Date.now()-g.lastBufferCleanupTime>1e4&&(g.lastBufferCleanupTime=Date.now(),yield g.sourceBuffer.removeBuffer(0,C+10));try{let o=g.sequenceNumber;if("fragmented"in e)for(const a of A)"initData"in a&&(yield g.sourceBuffer.appendBuffer(a.data,a.initData));else{const a=Cd(A,o++);yield g.sourceBuffer.appendBuffer(a)}g.sequenceNumber=o,g.consecutiveQuotaExceededErrorCount=0,g.successfulAppendCalls++}catch(o){throw o instanceof DOMException&&(o.code===DOMException.QUOTA_EXCEEDED_ERR?(this.quotaErrorCount++,g.consecutiveQuotaExceededErrorCount++,this.logger.error("quota exceeded error",{error:o}),g.pendingSamples.unshift(...A)):this.mediaElement.error&&g.pendingSamples.unshift(...A)),o}}));I(this,"onFragment",({fragment:A,mimeType:t,codec:e,channelId:g,renditionId:B})=>{const C=A.mediaType(),Q=A.rawBytes(),o=A.header().rawBytes(),a=A.baseMediaDecodeTime(),c=A.timescale(),h=A.duration(),l=C==="video"?A.startsWithKeyframe():!0,m=A.compositionTimeOffset(0);if(C==="text"){this.logger.warn("Skipping unexpected text fragment");return}if(!e){this.logger.warn("Skipping fragment with no codec");return}const y=this.trackContexts.get(C);if(!y)throw RB(C);y.state==="initialized"&&t&&(y.mimeType=t,y.initSegments.set(g,B,o));const f={fragmented:!0,type:C,data:Q,initData:o,timestamp:a,duration:h,timescale:c,channelId:g,renditionId:B,isSync:l,codec:e,fragment:A,compositionTimeOffset:m};this.onCodedSample(f)});I(this,"onCodedSample",A=>{if(A.duration===0)return;const t=this.trackContexts.get(A.type);if(!t)throw RB(A.type,A.renditionId);if(!(!t.hasFirstSync&&!A.isSync)){if(this.hasAddedInitialPosterFrame&&A.isSync&&A.type==="video"){this.hasAddedInitialPosterFrame=!1;const e=D({},A);"fragment"in e?(e.fragment=e.fragment.clone(),e.fragment.updateBaseMediaDecodeTime(0),e.data=e.fragment.rawBytes()):e.timestamp=0,t.pendingSamples.push(e)}t.hasFirstSync=!0,t.pendingSamples.push(A),t.state!=="uninitialized"&&(t.isWorkingOnPendingSamples||lu(t,this.append,this.maxChunkSize).catch(e=>{if(t.isWorkingOnPendingSamples=!1,e instanceof Error){if(this.logger.error("append failed",{message:e.message,name:e.name}),e instanceof DOMException&&e.code===DOMException.QUOTA_EXCEEDED_ERR){if(t.consecutiveQuotaExceededErrorCount>=this.minConsecutiveErrorsBeforeEmit){const g=Pn(!1,e,t.consecutiveQuotaExceededErrorCount,A.type);this.emitter.emit("error",g)}}else{const g=Pn(!1,e,t.consecutiveQuotaExceededErrorCount,A.type);this.emitter.emit("error",g)}this.mediaElement.error&&this.onSourceEnded()}}))}});I(this,"onSourceOpen",()=>{this.logger.debug("source opened"),this.sourceOpenEndTime=Date.now(),this.pendingTracksToAddSourceBuffers&&(this.setSourceBuffers(this.pendingTracksToAddSourceBuffers),this.pendingTracksToAddSourceBuffers=void 0)});I(this,"onSourceEnded",()=>{const{error:A}=this.mediaElement;if(A){const t=/AUDIO_RENDERER/.test(A.message)||!this.autoRecoverFromMediaErrors,e=nc(t,A);if(this.logger.error("MediaElement error",{error:e}),this.emitter.emit("error",e),!e.isFatal()){this.logger.info("Re-opening MediaSource"),this.emitter.emit("recovered from media error",{error:e,count:this.recoveredFromErrorCount}),this.recoveredFromErrorCount++;const g=!this.mediaElement.paused,B=[];this.trackContexts.forEach((C,Q)=>{C.state==="initialized"&&B.push({type:Q,mimeType:C.mimeType,codec:C.codec})}),this.sourceOpenStartTime=Date.now(),this.pendingTracksToAddSourceBuffers=B,this.mediaElement.src="",this.setTrackContexts(this.trackContexts),this.mediaSource.attach(this.mediaElement),g&&this.mediaElement.play().catch(F)}}this.logger.debug("source ended")});this.logger=A,this.mediaElement=e,this.emitter=t}};I(gQ,"create",(A,t,e)=>{const g=new gQ(A,t,e);return g.setTrackContexts(),g.mediaSource.on("source ended",g.onSourceEnded),g.mediaSource.on("source open",g.onSourceOpen),g.mediaSource.attach(e),g});let fo=gQ;const iE=(i,A)=>{var Q;const t=i.renditionId!==A.renditionId,e=i.channelId!==A.channelId,g=((Q=i.timestamp)!=null?Q:0)>A.timestamp,B=i.type==="video"&&A.type==="video"&&"levelIdc"in i&&"levelIdc"in A&&i.levelIdc!==A.levelIdc;let C=!1;return i.type==="video"&&A.type==="video"&&"width"in i&&"width"in A&&(C=A.width!==i.width||A.height!==i.height),e||t||g||C||B},lu=(i,A,t)=>r(null,null,function*(){for(i.isWorkingOnPendingSamples=!0;i.pendingSamples.length>0;){const e=[];let g=0;for(let Q=0;Q<i.pendingSamples.length;Q++){g=Q;const o=i.pendingSamples[Q],a=i.pendingSamples[Q+1];if(o&&(e.push(o),a)){if(iE(o,a))break;const c=(o.timestamp+o.duration)/o.timescale;if(a.timestamp/a.timescale-c>.1)break}if(Q===t-1)break}const B=e[0];if(!B)break;const C=i.previousSample?iE(i.previousSample,B):!0;yield A(e,C),i.pendingSamples=i.pendingSamples.slice(g+1),i.previousSample=e[e.length-1]}i.isWorkingOnPendingSamples=!1}),sQ=class sQ{constructor(A,t){I(this,"logger");I(this,"emitter");I(this,"element");I(this,"pictureInPictureWindow");I(this,"unload",()=>{this.emitter.off("add picture in picture listener",this.onEnablePictureInPicture)});I(this,"onEnablePictureInPicture",A=>{this.element=A.element,A.element.addEventListener("leavepictureinpicture",()=>{this.pictureInPictureWindow=void 0,this.logger.debug("Leave picture in picture"),this.emitter.emit("exit picture in picture")}),A.element.addEventListener("enterpictureinpicture",t=>{this.pictureInPictureWindow=t.pictureInPictureWindow,this.logger.debug("Enter picture in picture"),this.emitter.emit("enter picture in picture",this)}),A.element.autopictureinpicture=!0});I(this,"getPictureInPictureSize",()=>this.pictureInPictureWindow);I(this,"isPictureInPictureActive",()=>this.isWebkitPresentationModeActive()||this.isStandardPictureInPictureActive());I(this,"isPictureInPictureSupported",()=>this.isWebkitPresentationModeSupported()||this.isStandardPictureInPictureSupported());I(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"))));I(this,"exitPictureInPicture",()=>this.isStandardPictureInPictureSupported()?this.exitStandardPictureInPicture():this.isWebkitPresentationModeSupported()?this.requestWebkitPresentationMode("inline"):Promise.reject(new Error("Picture in picture is not supported")));I(this,"getStatistics",()=>({isPictureInPictureActive:this.isPictureInPictureActive()}));I(this,"requestStandardPictureInPicture",()=>r(this,null,function*(){return yield this.element.requestPictureInPicture()}));I(this,"exitStandardPictureInPicture",()=>r(null,null,function*(){return yield document.exitPictureInPicture()}));I(this,"isStandardPictureInPictureSupported",()=>!!this.element&&!!this.element.requestPictureInPicture&&!!document.pictureInPictureEnabled);I(this,"isStandardPictureInPictureActive",()=>!!this.element&&!!document.pictureInPictureElement);I(this,"isWebkitPresentationModeActive",()=>!!this.element&&this.element.webkitPresentationMode==="picture-in-picture");I(this,"requestWebkitPresentationMode",A=>r(this,null,function*(){return this.element.webkitSetPresentationMode(A),Promise.resolve()}));I(this,"isWebkitPresentationModeSupported",()=>!!this.element&&!!this.element.webkitSetPresentationMode);this.emitter=A,this.logger=t,this.emitter.on("add picture in picture listener",this.onEnablePictureInPicture)}};I(sQ,"create",(A,t)=>new sQ(A,t));let po=sQ;const BQ=class BQ{constructor(A,t,e,g){I(this,"emitter");I(this,"logger");I(this,"clockSource");I(this,"state","buffering");I(this,"bufferFullness",0);I(this,"targetBufferTime");I(this,"lastBufferStateEvent","drained");I(this,"firstFrameTime");I(this,"currentTimeIsInRange",!1);I(this,"needsInputForAudioCount",0);I(this,"needsInputForVideoCount",0);I(this,"unload",()=>{this.emitter.off("buffer state",this.onBufferedStateChanged),this.emitter.off("needs user input",this.onNeedsUserInput)});I(this,"setTargetBufferTime",A=>{this.targetBufferTime=A,this.emitter.emit("target buffer time",A)});I(this,"getTargetBufferTime",()=>this.targetBufferTime);I(this,"getBufferFullness",()=>this.bufferFullness);I(this,"getLastBufferStateEvent",()=>this.lastBufferStateEvent);I(this,"getState",()=>this.state);I(this,"getFirstFrameTime",()=>this.firstFrameTime);I(this,"getStatistics",()=>({bufferTime:this.targetBufferTime,needsInputForAudioCount:this.needsInputForAudioCount,needsInputForVideoCount:this.needsInputForVideoCount}));I(this,"onBufferedStateChanged",({buffered:A,isPaused:t})=>{const e=this.clockSource.currentTime,g=A.some(c=>c.start<e&&e<c.end),B=A[A.length-1],C=B?B.end-B.start>=this.targetBufferTime:!1,Q=B?Math.max(0,B.end-e)/this.targetBufferTime:0,o=t?"paused":g?"playing":"buffering",a=this.state;this.currentTimeIsInRange!==g&&!g?(this.lastBufferStateEvent="drained",this.emitter.emit("buffer state event",this.lastBufferStateEvent)):g&&C&&this.lastBufferStateEvent==="drained"&&(this.lastBufferStateEvent="filled",this.emitter.emit("buffer state event",this.lastBufferStateEvent)),o==="playing"&&!this.firstFrameTime&&(this.firstFrameTime=Date.now()),this.currentTimeIsInRange=g,this.state=o,this.bufferFullness=g?Q:0,a!==o&&this.emitter.emit("playback state",o),this.emitter.emit("buffer fullness",this.bufferFullness)});I(this,"onNeedsUserInput",({forAudio:A,forVideo:t})=>{A&&this.needsInputForAudioCount++,t&&this.needsInputForVideoCount++});this.emitter=A,this.logger=t,this.clockSource=e,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)}};I(BQ,"create",(A,t,e,g)=>new BQ(A,t,e,g));let Fo=BQ;const Go=()=>({upgradesFromLevel:[],downgradesFromLevel:[],bufferingRanges:[],activeRanges:[],decodeRate:Number.MAX_SAFE_INTEGER}),uu=()=>({levels:{},levelDowngrades:[],levelUpgrades:[],bufferFullness:0,general:Go()}),CQ=class CQ{constructor(A,t,e){I(this,"minBufferFullnessLengthForRegression",6);I(this,"logger");I(this,"emitter");I(this,"timers",NA.create());I(this,"metrics",uu());I(this,"bufferFullness",new W(30));I(this,"bufferFullnessRegression");I(this,"currentLevel");I(this,"isSuspended",!1);I(this,"_fatalQosCount",0);I(this,"targetBufferTime",0);I(this,"renditionLevelSource");I(this,"qualityIndexOrder",[]);I(this,"hasAsserted",!1);I(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)});I(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()});I(this,"suspend",()=>{this.isSuspended=!0,this.timers.unload(),this.stopBuffering(),this.unsetActive()});I(this,"unsuspend",()=>{this.isSuspended=!1,this.currentLevel&&this.setActive()});I(this,"fatalQosGraceTime",()=>1e4*(this.fatalQosCount+1));I(this,"incrementFatalQosCount",()=>{this._fatalQosCount++});I(this,"getMetrics",()=>this.metrics);I(this,"getLevelStats",A=>{var e,g,B,C;const t=((g=(e=A.video)==null?void 0:e.bitRate)!=null?g:0)+((C=(B=A.audio)==null?void 0:B.bitRate)!=null?C:0);return this.metrics.levels[t]});I(this,"getBufferFullnessRegression",()=>this.bufferFullnessRegression);I(this,"getTargetBufferTime",()=>this.targetBufferTime);I(this,"activeRatios",()=>{const A=new Map,t=_i(this.metrics.general.activeRanges);if(Object.entries(this.metrics.levels).forEach(([e,g])=>{var o;const B=parseInt(e,10),C=t?_i(g.activeRanges)/t:0,Q=this.getQualityIndex(B).toString();A.set(Q,((o=A.get(Q))!=null?o:0)+C)}),!this.hasAsserted){const e=A.size?Math.abs(Array.from(A.values()).reduce((g,B)=>g+B,0)-1)<=.02:!0;e||(this.hasAsserted=!0,console.assert(e,`Active ratios should be close to 1 - actual: ${Array.from(A.values()).reduce((g,B)=>g+B,0)}`))}return A});I(this,"bufferingRatios",()=>{const A=new Map,t=_i(this.metrics.general.bufferingRanges);if(Object.entries(this.metrics.levels).forEach(([e,g])=>{var o;const B=parseInt(e,10),C=t?_i(g.bufferingRanges)/t:0,Q=this.getQualityIndex(B).toString();A.set(Q,((o=A.get(Q))!=null?o:0)+C)}),!this.hasAsserted){const e=Array.from(A.values()).reduce((g,B)=>g+B,0)<=1;e||(this.hasAsserted=!0,console.assert(e,`Buffering ratios should be less than 1 - actual: ${Array.from(A.values()).reduce((g,B)=>g+B,0)}`))}return A});I(this,"bufferingEventsLast",A=>this.metrics.general.bufferingRanges.filter(t=>t.start>=Date.now()-A).length);I(this,"timeSpentBufferingLast",A=>yn(this.metrics.general.bufferingRanges,A));I(this,"timeSpentActiveLast",A=>yn(this.metrics.general.activeRanges,A));I(this,"timeSpentPlayingInAtLeastLevelRatio",A=>{var o,a,c,h;const t=this.timeSpentBuffering(),e=this.timeActive(),g=this.bufferingRatios(),B=this.activeRatios(),C=((a=(o=A.video)==null?void 0:o.bitRate)!=null?a:0)+((h=(c=A.audio)==null?void 0:c.bitRate)!=null?h:0),Q=t/e;return Object.keys(this.metrics.levels).map(l=>parseInt(l,10)).filter(l=>l>=C).reduce((l,m)=>{var f,k;const y=this.getQualityIndex(m).toString();return((f=B.get(y))!=null?f:0)-((k=g.get(y))!=null?k:0)*Q+l},0)});I(this,"timeSpentBuffering",()=>_i(this.metrics.general.bufferingRanges));I(this,"timeActive",()=>_i(this.metrics.general.activeRanges));I(this,"getStatistics",()=>({timeSpentBuffering:this.timeSpentBuffering(),bufferingEventsCount:this.metrics.general.bufferingRanges.length,timeSpentRatio:[...this.activeRatios()].reduce((A,[t,e])=>(A[t]=e,A),{}),fatalQosCount:this.fatalQosCount}));I(this,"onRenditionLevelChanged",A=>{var B,C,Q,o,a,c,h,l,m,y,f,k,q,U;const t=((Q=(C=(B=A.from)==null?void 0:B.video)==null?void 0:C.bitRate)!=null?Q:0)+((c=(a=(o=A.from)==null?void 0:o.audio)==null?void 0:a.bitRate)!=null?c:0),e=((m=(l=(h=A.to)==null?void 0:h.video)==null?void 0:l.bitRate)!=null?m:0)+((k=(f=(y=A.to)==null?void 0:y.audio)==null?void 0:f.bitRate)!=null?k:0);this.logger.info("rendition level changed",{fromLevel:t,toLevel:e}),this.metrics.general.activeRanges.length===0&&this.setActive(),A.from&&A.to&&(t<e?this.metrics.general.upgradesFromLevel.push(Date.now()):this.metrics.general.downgradesFromLevel.push(Date.now()));let g=!1;if(A.from){const H=(q=this.metrics.levels[t])!=null?q:Go();t<e?H.upgradesFromLevel.push(Date.now()):H.downgradesFromLevel.push(Date.now()),Ze(H.activeRanges);const T=H.bufferingRanges[H.bufferingRanges.length-1];g=!!T&&!T.end,Ze(H.bufferingRanges),this.metrics.levels[t]=H}if(A.to){const H=(U=this.metrics.levels[e])!=null?U:Go();zi(H.activeRanges),g&&zi(H.bufferingRanges),this.metrics.levels[e]=H,this.currentLevel=e}});I(this,"onBufferFullness",A=>{this.bufferFullness.push(A),this.metrics.bufferFullness=A,this.bufferFullness.items().length>=this.minBufferFullnessLengthForRegression&&(this.bufferFullnessRegression=this.calculateLinearRegression())});I(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}});I(this,"onVideoDecodeRate",A=>{var e;if(this.metrics.general.decodeRate=A,!this.currentLevel)return;const t=this.metrics.levels[(e=this.currentLevel)!=null?e:0];t&&(t.decodeRate=A)});I(this,"onTargetBufferTime",A=>{this.targetBufferTime=A});I(this,"calculateLinearRegression",()=>Wr(this.bufferFullness.items().map((A,t)=>({x:t,y:A}))));I(this,"stopBuffering",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Ze(A.bufferingRanges)}Ze(this.metrics.general.bufferingRanges)});I(this,"startBuffering",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&zi(A.bufferingRanges)}zi(this.metrics.general.bufferingRanges)});I(this,"unsetActive",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Ze(A.activeRanges)}Ze(this.metrics.general.activeRanges)});I(this,"getQualityIndex",A=>{var e,g;if(!this.qualityIndexOrder.length){const C=((g=(e=this.renditionLevelSource)==null?void 0:e.getRenditionLevels())!=null?g:[]).map(Q=>{var o,a,c,h;return((a=(o=Q.video)==null?void 0:o.bitRate)!=null?a:0)+((h=(c=Q.audio)==null?void 0:c.bitRate)!=null?h:0)}).filter(Q=>Q>0);this.qualityIndexOrder=[...new Set(C)].sort((Q,o)=>o-Q)}let t=this.qualityIndexOrder.indexOf(A);return t===-1&&(this.qualityIndexOrder.push(A),this.qualityIndexOrder.sort((B,C)=>C-B),t=this.qualityIndexOrder.indexOf(A)),t});this.logger=t,this.emitter=A,this.renditionLevelSource=e}get fatalQosCount(){return this._fatalQosCount}setActive(){if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&zi(A.activeRanges)}zi(this.metrics.general.activeRanges)}};I(CQ,"create",(A,t,e)=>new CQ(A,t,e));let ko=CQ;const QQ=class QQ{constructor(A,t){I(this,"renditions",new Map);I(this,"renditionLevels",[]);I(this,"languages",[]);I(this,"emitter");I(this,"subscriptionSource");I(this,"renditionLevelChangeCount",0);I(this,"unload",()=>{this.emitter.off("renditions",this.onRenditions),this.emitter.off("subscription changed",this.onSubscriptionChanged)});I(this,"getRenditionLevels",A=>A?this.createRenditionLevels(A):this.renditionLevels);I(this,"getRenditionLevel",A=>{var Q;const t=A!=null?A:this.getCurrentSubscription(),e=A?this.createRenditionLevels(A):this.renditionLevels;if(!t.video)return e.length?e[0]:void 0;const g=t.video.bitRate||Number.MAX_SAFE_INTEGER,B=t.video.width||Number.MAX_SAFE_INTEGER,C=t.video.height||Number.MAX_SAFE_INTEGER;return(Q=e.filter(o=>o.video&&t.video?o.video.bitRate<=g&&o.video.width<=B&&o.video.height<=C:!0).pop())!=null?Q:e[0]});I(this,"setRenditions",(A,t)=>{this.renditions.set(A,t)});I(this,"getLanguages",()=>this.languages);I(this,"getVideoRendition",(A,t=this.getCurrentSubscription().channelId)=>{const e=this.getRendition(A,t);if(e&&Xe(e))return e});I(this,"getAudioRenditions",A=>{const t=this.renditions.get(A);return t==null?void 0:t.filter(g=>je(g))});I(this,"getVideoRenditions",A=>{const t=this.renditions.get(A);return t==null?void 0:t.filter(g=>Xe(g))});I(this,"getAudioRendition",(A,t=this.getCurrentSubscription().channelId)=>{const e=this.getRendition(A,t);if(e&&je(e))return e});I(this,"getRendition",(A,t=this.getCurrentSubscription().channelId)=>{var e;return(e=this.renditions.get(t))==null?void 0:e.find(g=>g.id===A)});I(this,"getStatistics",()=>{var t,e,g,B,C,Q,o,a,c,h;const A=this.getRenditionLevel();return{videoCodec:(t=A==null?void 0:A.video)==null?void 0:t.codec,audioCodec:(e=A==null?void 0:A.audio)==null?void 0:e.codec,videoRenditionId:(g=A==null?void 0:A.video)==null?void 0:g.id,audioRenditionId:(B=A==null?void 0:A.audio)==null?void 0:B.id,videoWidth:(C=A==null?void 0:A.video)==null?void 0:C.width,videoHeight:(Q=A==null?void 0:A.video)==null?void 0:Q.height,expectedVideoBitRate:(o=A==null?void 0:A.video)==null?void 0:o.bitRate,expectedAudioBitRate:(a=A==null?void 0:A.audio)==null?void 0:a.bitRate,frameRate:(c=A==null?void 0:A.video)==null?void 0:c.frameRate,language:(h=A==null?void 0:A.audio)==null?void 0:h.language,renditionLevelChangeCount:this.renditionLevelChangeCount}});I(this,"onRenditions",A=>{const t=this.subscriptionSource.getCurrentSubscription();this.renditions.set(A.channelId,A.renditions),this.updateRenditionLevels({to:t,from:t})});I(this,"onSubscriptionChanged",A=>{this.updateRenditionLevels(A)});I(this,"updateRenditionLevels",({to:A,from:t})=>{var a;const{channelId:e,initiator:g}=A,B=this.getRenditionLevel(t),C=new Set;((a=this.renditions.get(e))!=null?a:[]).filter(c=>c.codec!=="webvtt").forEach(c=>c.language?C.add(c.language):void 0),this.languages=Array.from(C),this.renditionLevels=this.createRenditionLevels(A);const o=this.getRenditionLevel(A);Ve(B,o)||(this.renditionLevelChangeCount++,this.emitter.emit("rendition level changed",{to:o,from:B,reason:g?"manual":"abr"}))});I(this,"createRenditionLevels",A=>{var c;const{video:t,audio:e,channelId:g}=A,B=(c=this.renditions.get(g))!=null?c:[],C=B.filter(Xe).filter(h=>t&&h.codec===t.codec),Q=B.filter(je).filter(h=>e&&h.codec===e.codec&&h.language===e.language),o=Math.max(C.length,Q.length),a=[];for(let h=0;h<o;h++){const l=C[Math.min(C.length-1,h)],m=Q[Math.min(Q.length-1,h)];a.push({audio:m,video:l})}return a});I(this,"getCurrentSubscription",()=>this.subscriptionSource.getCurrentSubscription());this.subscriptionSource=t,this.emitter=A,this.emitter.on("renditions",this.onRenditions),this.emitter.on("subscription changed",this.onSubscriptionChanged)}};I(QQ,"create",(A,t)=>new QQ(A,t));let Ro=QQ;const Rg=i=>JSON.parse(JSON.stringify(i)),wu=1e4,oQ=class oQ{constructor(A,t,e){I(this,"logger");I(this,"timers",new NA);I(this,"emitter");I(this,"targetSubscription");I(this,"currentSubscription");I(this,"_isSwitchingSubscription",!1);I(this,"pendingSubscriptionTimeoutId");I(this,"burstMs",0);I(this,"unload",()=>{this.logger.debug("Unloading module..."),this.timers.unload(),this.emitter.off("subscription changed",this.onSubscriptionChanged),this.logger.debug("Unloaded module")});I(this,"isSwitchingSubscription",()=>this._isSwitchingSubscription);I(this,"getTargetSubscription",()=>this.targetSubscription);I(this,"getCurrentSubscription",()=>this.currentSubscription);I(this,"enableBurst",A=>{this.burstMs=A});I(this,"setSize",A=>{this.targetSubscription.video.width=A.width,this.targetSubscription.video.height=A.height,this.scheduleSubscriptionChange()});I(this,"setVideoConstraint",A=>{this.targetSubscription.video=A,this.scheduleSubscriptionChange()});I(this,"setAudioConstraint",A=>{this.targetSubscription.audio=A,this.scheduleSubscriptionChange()});I(this,"setVideoBitRate",A=>{this.targetSubscription.video.bitRate=A,this.scheduleSubscriptionChange()});I(this,"setAudioBitRate",A=>{this.targetSubscription.audio.bitRate=A,this.scheduleSubscriptionChange()});I(this,"setChannelId",A=>{this.targetSubscription.channelId=A,this.scheduleSubscriptionChange()});I(this,"setLanguage",A=>{this.targetSubscription.audio.language=A,this.scheduleSubscriptionChange()});I(this,"setVideoCodec",A=>{this.targetSubscription.video.codec=A,this.scheduleSubscriptionChange()});I(this,"setAudioCodec",A=>{this.targetSubscription.audio.codec=A,this.scheduleSubscriptionChange()});I(this,"setBurst",A=>{A?this.targetSubscription.burstMs=A:delete this.targetSubscription.burstMs});I(this,"isNewSubscription",()=>{const A=["burstMs","meta","initiator","channelGroupId"];return!Ve(Sn(this.currentSubscription,A),Sn(this.targetSubscription,A))});I(this,"onSubscriptionChanged",({to:A,reset:t})=>{this.logger.debug("onSubscriptionChanged",{to:A,reset:t}),t?this.targetSubscription=Rg(this.currentSubscription):this.currentSubscription=Rg(A),this._isSwitchingSubscription=this.isNewSubscription()});I(this,"scheduleSubscriptionChange",()=>{this.targetSubscription=Rg(this.targetSubscription),this._isSwitchingSubscription=this.isNewSubscription();const A=this.currentSubscription.channelId,t=this.targetSubscription.channelId,e=A!==t;this._isSwitchingSubscription&&(e&&this.burstMs?this.setBurst(this.burstMs):this.setBurst(0),this.pendingSubscriptionTimeoutId&&(this.timers.clearTimeout(this.pendingSubscriptionTimeoutId),this.pendingSubscriptionTimeoutId=void 0),e&&this.timers.setTimeout(()=>{this.currentSubscription.channelId===A&&this.targetSubscription.channelId===t&&(this.logger.warn("Channel switch timeout",t),this.targetSubscription=Rg(this.currentSubscription),this.emitter.emit("channel switch timeout",t))},wu),this.pendingSubscriptionTimeoutId=this.timers.setTimeout(()=>this.emitter.emit("send signal",{type:"subscribe",subscription:this.getTargetSubscription()}),0))});this.logger=A,this.targetSubscription=t,this.currentSubscription=Rg(t),this.emitter=e,this.emitter.on("subscription changed",this.onSubscriptionChanged)}};I(oQ,"create",(A,t,e)=>new oQ(A,e,t));let Uo=oQ;const IE=5e3,Du=()=>un()||GB()||vr(),gE=()=>Du()?100:0,sE=i=>A=>A>i,nQ=class nQ{constructor(A,t,e,g,B){I(this,"emitter");I(this,"logger");I(this,"playbackSource");I(this,"bufferSource");I(this,"keyframeTimestamps",new W(10));I(this,"lastSeekTime",Date.now());I(this,"seekCooldownTime",1e3);I(this,"seekTimeoutTime",5e3);I(this,"seekKeyframeOvershoot",50);I(this,"syncMaxBehind");I(this,"syncMaxBehindMultiplierStep",1);I(this,"syncMaxBehindIncreaseEvery",2);I(this,"syncMaxBehindMaximumAllowed",2e3);I(this,"syncMaxBehindMultiplier",1);I(this,"timeshiftOnAudio",!1);I(this,"syncMaxAhead",150);I(this,"timeshiftSync",{enabled:!1,maxBehind:50,multiplier:1,maxBehindAllowed:600,overshoot:gE(),minOvershootAllowed:gE(),maxOvershootAllowed:500});I(this,"maxTimeSyncDifferenceTolerance",150);I(this,"timers",NA.create());I(this,"rtt",0);I(this,"channelSyncInfo",new Map);I(this,"driftAdjustmentsCount",0);I(this,"timeshiftDriftAdjustmentCount",0);I(this,"driftAdjustments",[]);I(this,"timeShiftAdjustments",[]);I(this,"timestampOffset");I(this,"currentChannelId");I(this,"highestSeenTimestamps",new Map);I(this,"isSuspended",!1);I(this,"isSyncAdjustmentActivated",!1);I(this,"load",()=>{this.timers.setInterval(this.onSync,100)});I(this,"unload",()=>{this.logger.debug("Unloading module..."),this.emitter.off("rtt",this.updateRtt),this.timers.unload(),this.logger.debug("Unloaded module")});I(this,"suspend",()=>{this.isSuspended=!0});I(this,"unsuspend",()=>{this.resetSyncState(),this.isSuspended=!1});I(this,"deactivateSyncAdjustments",()=>{this.isSyncAdjustmentActivated=!1});I(this,"activateSyncAdjustments",()=>{this.tryApplySyncInfo(0),this.lastSeekTime=Date.now(),this.isSyncAdjustmentActivated=!0});I(this,"reset",()=>{this.logger.info("Reset sync state"),this.currentChannelId=void 0,this.timestampOffset=void 0,this.resetSyncState(),this.highestSeenTimestamps.clear()});I(this,"getTimeshiftOffset",()=>{var A;return(A=this.timestampOffset)!=null?A:0});I(this,"getCurrentChannelId",()=>this.currentChannelId);I(this,"resetSyncState",()=>{this.timeshiftSync.multiplier=1,this.syncMaxBehindMultiplier=1,this.driftAdjustments=[],this.timeShiftAdjustments=[]});I(this,"getLiveEdgeTime",A=>{const t=this.channelSyncInfo.get(A);if(!t)return;const e=Date.now()-t.localTimestamp;return t.timestamp+e});I(this,"getLiveEdgeTimeLatencyAdjusted",A=>{const t=this.getLiveEdgeTime(A);if(t)return t+this.rtt/2});I(this,"getWallclockTime",A=>{const t=this.channelSyncInfo.get(A);if(!t)return;const e=Date.now()-t.localTimestamp;return t.wallclockTime+e});I(this,"getWallclockTimeLatencyAdjusted",A=>{const t=this.getWallclockTime(A);if(t)return t+this.rtt/2});I(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-IE);const t=A.type==="video"&&A.isSync;if(this.currentChannelId!==A.channelId){let B=Number.MAX_SAFE_INTEGER;console.assert(this.highestSeenTimestamps.size!==0,"no known timestamps"),this.highestSeenTimestamps.forEach(Q=>{B=Math.min(B,Q)});const C=A.timestamp/A.timescale*1e3;this.currentChannelId=A.channelId,this.timestampOffset=C-B}else(t||this.timeshiftOnAudio)&&this.tryTimeshiftSync();const e=this.timestampOffset*A.timescale/1e3;return A.timestamp-=e,t&&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});I(this,"processFragment",(A,t)=>{var C;this.currentChannelId||(this.currentChannelId=A);const e=t.mediaType();if(!e)throw new Error("Fragment must have a media type");this.timestampOffset||(this.timestampOffset=t.baseMediaDecodeTime()/t.timescale()*1e3-IE);const g=t.mediaType()==="video"&&t.startsWithKeyframe();this.currentChannelId!==A?(console.assert(this.highestSeenTimestamps.size!==0,"no known timestamps"),this.highestSeenTimestamps.forEach(Q=>{}),this.currentChannelId=A):(g||this.timeshiftOnAudio)&&this.tryTimeshiftSync();const B=this.timestampOffset*t.timescale()/1e3;return t.updateBaseMediaDecodeTime(t.baseMediaDecodeTime()-B),g&&this.keyframeTimestamps.push(t.baseMediaDecodeTime()/t.timescale()*1e3),this.highestSeenTimestamps.set(e,Math.max((C=this.highestSeenTimestamps.get(e))!=null?C:0,t.baseMediaDecodeTime()/t.timescale()*1e3)),t});I(this,"getStatistics",()=>({drift:this.drift,driftAdjustmentCount:this.driftAdjustmentsCount,timeshiftDriftAdjustmentCount:this.timeshiftDriftAdjustmentCount,seekTime:this.playbackSource.seekTime}));I(this,"updateRtt",A=>void(this.rtt=A));I(this,"isPlaybackSourceReadyToSeek",()=>!this.isSeeking()&&this.isSeekCooldownExpired()&&this.isSyncAdjustmentActivated);I(this,"isSeeking",()=>this.playbackSource.isSeeking?!this.isSeekTimeoutExpired():!1);I(this,"isAllowedToSync",()=>this.isPlaybackSourceReadyToSeek()&&!!this.currentChannelId&&!this.isSuspended&&!this.playbackSource.isPaused);I(this,"isSeekCooldownExpired",()=>Date.now()-this.lastSeekTime>this.seekCooldownTime);I(this,"isSeekTimeoutExpired",()=>Date.now()-this.lastSeekTime>this.seekTimeoutTime);I(this,"currentTimeshiftMaxBehind",()=>Math.min(this.timeshiftSync.maxBehind*this.timeshiftSync.multiplier,this.timeshiftSync.maxBehindAllowed));I(this,"currentSyncMaxBehind",()=>Math.min(this.syncMaxBehindMultiplier*this.syncMaxBehind,this.syncMaxBehindMaximumAllowed));I(this,"currentSyncMaxAhead",()=>this.playbackSource.seekTime>500?Math.max(this.syncMaxAhead*this.syncMaxBehindMultiplier,300):this.syncMaxAhead);I(this,"tryTimeshiftSync",()=>{var B;if(!this.timeshiftSync.enabled||!this.isAllowedToSync())return;const A=(B=this.drift)!=null?B:0;if(A>=this.syncMaxBehind)return;if(A<this.currentTimeshiftMaxBehind()){this.timeshiftSync.overshoot=0;return}if(!this.timestampOffset)return;const t=Date.now()-this.seekTimeoutTime*this.timeshiftSync.multiplier,e=this.timeShiftAdjustments.filter(sE(t)).length;if(e&&this.timeshiftSync.multiplier>2)return this.logger.debug("Too many diff timeShifts within sliding window",{timeShiftsCooldownMs:t,timeShiftsWithinCooldownTime:e}),!1;const g=A+this.timeshiftSync.overshoot;this.logger.info("Adjusting for drift using timeshift",{drift:A,syncAmount:g,currentTime:this.playbackSource.currentTime,rtt:this.rtt,overshoot:this.timeshiftSync.overshoot}),this.timestampOffset+=g,this.lastSeekTime=Date.now(),!this.playbackSource.isPaused&&(this.timeShiftAdjustments.push(this.lastSeekTime),this.timeshiftDriftAdjustmentCount++,this.timeshiftSync.multiplier++,this.timeshiftSync.overshoot=Math.max(this.timeshiftSync.minOvershootAllowed,Math.min(this.timeshiftSync.multiplier*A/2,this.timeshiftSync.maxOvershootAllowed)))});I(this,"onSync",()=>{var Q;if(!this.isAllowedToSync())return;const A=(Q=this.drift)!=null?Q:0;if(A<0&&-A<this.currentSyncMaxAhead()||A>0&&A<this.currentSyncMaxBehind()||Math.abs(A)<1||!this.isSeekCooldownExpired())return;const t=Date.now()-this.seekTimeoutTime*this.syncMaxBehindMultiplier,e=this.driftAdjustments.filter(sE(t)).length;if(e&&this.syncMaxBehindMultiplier>2)return this.logger.debug("Too many diff adjustments within sliding window",{adjustmentsCooldownMs:t,adjustmentsWithinCooldownTime:e}),!1;const g=this.playbackSource.seekTime,B=this.playbackSource.currentTime+A,C=this.findKeyframeCloseToTimestamp(B);if(C||this.keyframeTimestamps.isEmpty()){const o=C?C+this.seekKeyframeOvershoot:B;if(this.logger.info("Adjusting for drift using seek",{drift:A,currentTime:this.playbackSource.currentTime,targetCurrentTime:o,seekTime:g,rtt:this.rtt}),this.lastSeekTime=Date.now(),this.driftAdjustments.push(this.lastSeekTime),this.driftAdjustmentsCount++,this.playbackSource.currentTime=o+g,this.timeshiftSync.overshoot=Math.max(this.timeshiftSync.minOvershootAllowed,this.timeshiftSync.overshoot/2),this.driftAdjustmentsCount%this.syncMaxBehindIncreaseEvery===0&&!this.playbackSource.isPaused){const a=this.currentSyncMaxBehind;this.syncMaxBehindMultiplier+=this.syncMaxBehindMultiplierStep,a!==this.currentSyncMaxBehind&&this.logger.info("Increasing max drift behind allowed",{from:a,to:this.currentSyncMaxBehind})}}});I(this,"findKeyframeCloseToTimestamp",A=>{const t=this.keyframeTimestamps.items();for(const e of t)if(e>=A&&e<=A+200)return e});this.logger=t,this.emitter=A,this.playbackSource=e,this.bufferSource=g,this.timeshiftSync.enabled=B,this.syncMaxBehind=this.timeshiftSync.enabled?1e3:200,this.emitter.on("rtt",this.updateRtt)}updateChannelSyncInfo(A,t){const e=Date.now(),g=this.channelSyncInfo.get(A),B=this.getLiveEdgeTime(A);if(this.isSuspended)return;if(!g||!B){this.logger.info("Initial timing info",{syncInfo:t}),this.channelSyncInfo.set(A,V(D({},t),{localTimestamp:e,timeDifferences:new W(12)}));return}const C=t.wallclockTime-g.wallclockTime,Q=t.timestamp-g.timestamp,o=e-g.localTimestamp,a=Q-o;if(g.timeDifferences.push(a),this.logger.debug("Timing info",{rtt:this.rtt,channelId:A,syncInfo:t,localTimestamp:e,diffFromEstimated:a,timestampDelta:Q,wallclockDelta:C,localWallclockDelta:o}),Math.abs(a)>=this.bufferSource.getTargetBufferTime()*2){this.logger.info("Resetting sync info",{diffFromEstimated:a}),this.channelSyncInfo.set(A,V(D({},t),{localTimestamp:e,timeDifferences:new W(g.timeDifferences.maxSize+1)})),this.currentChannelId&&this.currentChannelId===A&&(this.reset(),this.emitter.emit("channel reset"));return}g.timeDifferences.isFull()&&this.tryApplySyncInfo(this.maxTimeSyncDifferenceTolerance)}tryApplySyncInfo(A){const t=this.getCurrentChannelId();if(!t)return;const e=this.channelSyncInfo.get(t);if(!e)return;const g=Wt(e.timeDifferences.items());Math.abs(g)>A&&(this.logger.info("Adjusting sync info",{averageDifference:g}),e.timestamp+=g,e.timeDifferences.clear())}get serverCurrentTime(){return this.channelCurrentTime-this.getTimeshiftOffset()}get channelCurrentTime(){const A=this.getCurrentChannelId();if(!A)return 0;const t=this.getLiveEdgeTime(A);return t?t-this.bufferSource.getTargetBufferTime():0}get drift(){return this.serverCurrentTime-this.playbackSource.currentTime}};I(nQ,"create",(A,t,e,g,B)=>new nQ(A,t,e,g,B));let No=nQ;const mu={enabled:!0,interval:3e4,includeErrors:!0,includeEvents:!0,includeStats:!0,maxRetries:10,maxErrorReports:50,maxEvents:50},bo=(i,A)=>V(D({},A),{type:i,timestamp:new Date().toISOString(),discriminator:"web"}),aQ=class aQ{constructor(A,t,e,g){I(this,"logger");I(this,"timers",new NA);I(this,"emitter");I(this,"options");I(this,"parentContext");I(this,"unsentLines",new W(100));I(this,"retries",0);I(this,"errorCount",0);I(this,"eventCount",0);I(this,"statsCount",0);I(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")});I(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)});I(this,"addStats",({isFinal:A,initiator:t}={isFinal:!1,initiator:"interval"},e={})=>{if(!this.options.includeStats)return;const g=this.parentContext.getStatistics(),B=bo("stats",V(D(D({},e),g),{isFinal:A,initiator:t,count:this.statsCount++}));this.unsentLines.push(B)});I(this,"addEvent",A=>{if(!this.options.includeEvents||this.eventCount>this.options.maxEvents)return;const t=this.parentContext.getStatistics(),e=bo("event",D(D({},t),A));this.eventCount++,this.unsentLines.push(e)});I(this,"getStatistics",()=>({errorCount:this.errorCount}));I(this,"send",A=>r(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 t=this.unsentLines.items().map(e=>JSON.stringify(e)).reverse().join(`
|
|
50
|
-
`);switch(A){case"beacon":navigator.sendBeacon(this.options.url,t);break;case"fetch":default:this.parentContext.connectionState==="connected"?this.emitter.emit("send signal",{type:"telemetry",body:t}):yield ca(new URL(this.options.url),{body:t,headers:{"Content-Type":"text/plain"}});break}this.retries=0,this.unsentLines.clear()}catch(t){this.retries++}}}));I(this,"onVisibilityChange",A=>{A==="hidden"&&(this.addStats({isFinal:!0,initiator:"visibilitychange"}),this.send("beacon"))});I(this,"onPageHide",A=>{this.addStats({isFinal:!0,initiator:"pagehide"},{persisted:A.persisted}),this.send("beacon")});I(this,"onRejection",A=>this.addError(A.reason));I(this,"onError",A=>this.addError(A.error));I(this,"addError",A=>{const{includeErrors:t,maxErrorReports:e}=this.options;if(t&&A instanceof x){if(this.errorCount++,this.errorCount>e)return;const g=this.parentContext.getStatistics();this.unsentLines.push(bo("error",D(D({},g),A.toStringifiable())))}});this.logger=A,this.emitter=t,this.options=D(D({},mu),e),this.parentContext=g}};I(aQ,"create",(A,t,e,g)=>new aQ(A,t,e,g));let rC=aQ;const EQ=class EQ{constructor(A,t,e){I(this,"logger");I(this,"element");I(this,"documentState");I(this,"timers",new NA);I(this,"unload",()=>{this.timers.unload()});I(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=t,this.documentState=e,this.timers.setInterval(this.unpause,100)}};I(EQ,"create",(A,t,e)=>new EQ(A,t,e));let cC=EQ;const Su=["minBufferTime","maxBufferTime","burstEnabled","sizeBasedResolutionCapEnabled","separateVideoSocketEnabled","videoCodecs"];function yu(i){return Su.includes(i)}class fu{constructor(A){I(this,"options");I(this,"overrides",new Map);this.options=A}getOptions(){return this.options}addOverrides(A,t){this.overrides.set(A,t)}set(A,t){this.options[A]=t}get(A,t){var e;if(t&&yu(A)){const g=(e=this.overrides.get(t))==null?void 0:e[A];if(typeof g!="undefined")return g}return this.options[A]}getOverride(A,t){var e;return(e=this.overrides.get(t))==null?void 0:e[A]}}const pu=6,Fu=i=>{let A=[i],t=0,e=0,g=!1;const B=(Q,o)=>{var k,q,U;Q.flags&&Gg(Q.flags)&&(t=(k=Q.compositionTimeOffset)!=null?k:0),Q.timestamp+=t,Q.compositionTimeOffset=((q=Q.compositionTimeOffset)!=null?q:0)-t;const a=Q.timestamp/Q.timescale,h=o.flags&&Gg(o.flags)?(U=o.compositionTimeOffset)!=null?U:0:t,m=(o.timestamp+h)/o.timescale,y=Math.max(0,Math.round((m-a)*Q.timescale));return y>0&&(e=y),V(D({},Q),{duration:y>0?y:e})};return(Q,o=!1)=>{if(Q.flags&&Gg(Q.flags)&&o&&(g=!g),!(o&&A.length<pu&&g)&&A.length>0){g=!1;let c=Q;for(let l=A.length-1;l>0;l--){const m=A[l];if(!m||!c)break;m.timestamp>=c.timestamp?A.splice(l,1):c=m}const h=A.map((l,m)=>B(l,A[m+1]||Q));return A=[Q],h}return A.push(Q),[]}},Gu=(i,A,t)=>{if(Xe(A))return D(V(D({},i),{type:"video",codec:A.codec,isSync:Gg(i.flags),data:i.payload,duration:0,width:A.width,height:A.height}),t);if(A.codec==="webvtt")throw new Error("WebVTT is not supported");return V(D({},i),{type:"audio",channels:A.channels,sampleRate:A.sampleRate,codec:A.codec,language:A.language,isSync:Gg(i.flags),data:i.payload,duration:0})};class ku{constructor(){I(this,"highEntropyValues");var A;(A=self.navigator.userAgentData)==null||A.getHighEntropyValues(["architecture","model","platformVersion","fullVersionList"]).then(t=>{this.highEntropyValues=t})}getUserAgentInformation(){var B,C,Q,o,a,c;const A=window.location.origin,e=!A||A=="null"?"":`${window.location.pathname}${window.location.search}`.substring(0,1e3),g={locationOrigin:window.location.origin,locationPath:e,ancestorOrigins:((B=window.location.ancestorOrigins)==null?void 0:B.length)>0?Array.from(window.location.ancestorOrigins):void 0,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory};if(self.navigator.userAgentData&&this.highEntropyValues){const l=[...(C=this.highEntropyValues.brands)!=null?C:[]];l.sort((U,H)=>U.brand.localeCompare(H.brand));const m=[...(Q=this.highEntropyValues.fullVersionList)!=null?Q:[]];m.sort((U,H)=>U.brand.localeCompare(H.brand));const y=m.map(U=>U.version),f=l.map(U=>U.brand),k=l.map(U=>U.version),q=parseInt((a=(o=this.highEntropyValues.platformVersion)==null?void 0:o.split(".")[0])!=null?a:"1");return D({userAgentLegacy:window.navigator.userAgent,ua:{browser:{brands:f,fullVersionBrands:y,majorVersions:k},device:this.highEntropyValues.model||"Other",os:{family:this.highEntropyValues.platform||"Other",version:(c=this.highEntropyValues.platformVersion)!=null?c:"1",major_version:Number.isFinite(q)?q:0}}},g)}else return D({userAgent:window.navigator.userAgent},g)}}const BE=(i,A)=>i&&typeof i=="object"&&A in i,CE=i=>!(typeof i!="object"||!BE(i,"channelId")||typeof i.channelId!="string"||!BE(i,"url")||typeof i.url!="string"||i.channelId.length===0||i.url.length===0),Ru=i=>{if(!CE(i))throw new x("Invalid options",{isFatal:!0,code:"invalid_options"});const A=D({},i);return Object.keys(A).forEach(t=>{const e=A;typeof e[t]=="undefined"&&delete e[t]}),A},Uu=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},oe=class oe extends it{constructor(t){super();I(this,"pictureInPicture");I(this,"drm");I(this,"browser",fQ());I(this,"options");I(this,"element");I(this,"playbackSource");I(this,"emitter",new it);I(this,"logger");I(this,"modules");I(this,"clientIp");I(this,"sessionId");I(this,"clientId",Fn());I(this,"_channels",[]);I(this,"createdAt",Date.now());I(this,"hasCalledConnect",!1);I(this,"latestEmittedLanguages",[]);I(this,"wakeLock");I(this,"pool",new xt(oe.MAX_POOL_SIZE));I(this,"userAgentInformation",new ku);I(this,"encryptedMediaExtensions");n(this,Yi,0);n(this,At,[]);I(this,"sampleProcessingSesssions",new Map);I(this,"sizes",new Map);I(this,"isSuspended",!0);I(this,"disconnectTimeout");n(this,Ti);I(this,"attach",t=>{var e;(e=this.wakeLock)==null||e.attach(t),t.appendChild(this.element)});I(this,"getOptions",()=>this.options.getOptions());I(this,"getThumbnailUrl",()=>{let t=this.options.get("edgeUrl")||this.options.get("url");t=t.replace("wss://","https://"),t=t.replace("ws://","http://"),t=t.endsWith("/")?t.slice(0,-1):t;const e=window.devicePixelRatio||1,g=Math.round(window.innerWidth*e),B=Math.round(window.innerHeight*e),C=this.options.get("authenticationToken"),Q=C?`&auth.token=${C}`:"";return`${t}/api/thumbnail?channelId=${this.channelId}${Q}&width=${g}&height=${B}`});I(this,"updateAuthenticationToken",t=>{this.logger.debug("Got new auth token",{token:t}),this.options.set("authenticationToken",t),this.emitter.emit("send signal",{type:"refresh auth",token:t})});I(this,"connect",()=>{this.hasCalledConnect||(this.play(),this._connect())});I(this,"_connect",()=>{var t,e;this.hasCalledConnect||(this.hasCalledConnect=!0,Object.values(this.modules).forEach(g=>{g&&"load"in g&&g.load()}),this.unsuspend(),this.playbackSource instanceof TQ&&((e=(t=this.playbackSource).load)==null||e.call(t)),this.modules.connection.connect())});I(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")}));I(this,"onConnectInfo",t=>r(this,null,function*(){var a;this.sessionId=Fn();const e=this.modules.subscription.getTargetSubscription(),g=t.channels.find(c=>c.channelId===e.channelId);if(this.emitter.emit("connect info",t),"timeshift"in t&&t.timeshift?(t.timeshift,this._channels=t.channels.map(c=>V(D({},c),{timeshift:t.timeshift})),this.emit("timeshift info",t.timeshift)):this._channels=t.channels,this.updateTextTracks((a=g==null?void 0:g.renditions)!=null?a:[]),!this.textTrack&&this.options.get("textTrack")&&(this.textTrack=this.options.get("textTrack")),yield Promise.all(t.channels.map(c=>r(this,null,function*(){c.overrides&&this.options.addOverrides(c.channelId,c.overrides),c.renditions=yield this.filterRenditions(c.renditions),this.modules.renditions.setRenditions(c.channelId,c.renditions)}))),!g)throw xn("external");const B=this.options.getOverride("sizeBasedResolutionCapEnabled",this.channelId);B!==void 0&&(this.modules.constraintCap.sizeBasedResolutionCapEnabled=B);const C=this.options.getOverride("minBufferTime",this.channelId),Q=this.options.getOverride("maxBufferTime",this.channelId);if((C||Q)&&(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 o=this.options.get("burstEnabled",this.channelId);return{video:this.targetSubscription.video,audio:this.targetSubscription.audio,burstMs:o?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}}));I(this,"emitLanguagesIfChanged",()=>{const t=this.modules.renditions.getLanguages(),e=this.latestEmittedLanguages;t.length==e.length&&t.every(B=>e.includes(B))||(this.logger.debug("Emitting new languages",{currentLanguages:t}),this.latestEmittedLanguages=t,this.emit("languages",this.latestEmittedLanguages))});I(this,"updateTextTracks",t=>{const e=t.filter(g=>g.codec==="webvtt");e.forEach(g=>{if(!s(this,At).find(C=>C.language===g.language)){if(this.modules.canvasModule){const C=this.modules.canvasModule.textTracks.addTextTrack(g.kind,g.label||g.language||"",g.language||"");s(this,At).push(C)}else if(this.mediaElement instanceof HTMLVideoElement){const C=this.mediaElement.addTextTrack(g.kind,g.label||g.language,g.language);s(this,At).push(C)}}});for(const g of s(this,At))e.find(C=>C.language===g.language)?g.mode==="disabled"&&(g.mode="hidden"):g.mode="disabled";this.emit("text tracks",this.textTracks)});I(this,"cleanupTextTracks",(t=this.currentTime-2e4)=>{s(this,At).forEach(e=>{if(e.cues)for(const g of e.cues)g.endTime*1e3<t-2e3&&e.removeCue(g)})});I(this,"filterRenditions",t=>r(this,null,function*(){const e=yield Promise.all(t.map(Q=>r(this,null,function*(){var c,h,l;if(je(Q))return!0;if(!Xe(Q)||!this.isSupportedVideoCodecProfile(Q.codec,Q.codecString))return!1;if(!this.willUseMediaSource()){const m=this.options.get("advanced"),y=(c=m.wasmDecodingConstraint.bitRate)!=null?c:Number.MAX_SAFE_INTEGER,f=(h=m.wasmDecodingConstraint.width)!=null?h:Number.MAX_SAFE_INTEGER,k=(l=m.wasmDecodingConstraint.height)!=null?l:Number.MAX_SAFE_INTEGER;return Q.bitRate<=y&&Q.width<=f&&Q.height<=k}const o=yield ld(Q);if(!o.supported||Q.codec=="av1"&&!o.smooth&&!o.powerEfficient)return!1;const a=this.options.getOverride("maxVideoBitRate",this.channelId);return a?a>=Q.bitRate:!0})));let g=t.filter((Q,o)=>e[o]);const B=g.filter(Q=>Q.codec==="h264").reverse()[0],C=g.filter(Q=>Q.codec==="av1").reverse()[0];return B&&C&&B.width>C.width&&B.height>C.height&&(g=g.filter(Q=>Q.codec!=="av1")),g}));I(this,"patchSubscription",(t,e)=>{const g=this.options.get("maxInitialBitRate"),B=Math.min(this.options.get("maxVideoBitRate"),g,e,this.targetSubscription.video.bitRate),C=Math.min(this.options.get("maxAudioBitRate"),g,e,this.targetSubscription.audio.bitRate),Q=this.options.get("media")==="audio"?[]:this.options.get("videoCodecs",this.channelId),o=this.supportedAudioCodecs(),a=t.renditions.filter(je),c=t.renditions.filter(Xe),h=o.find(f=>a.find(k=>k.codec===f)!==void 0),l=Q.find(f=>c.find(k=>k.codec===f)!==void 0),m=a.map(f=>f.language);if(this.logger.debug("supported and selected codecs",{audioCodecs:o,videoCodecs:Q,audioCodec:h,videoCodec:l}),l){const f=this.options.get("maxSize");this.modules.subscription.setVideoConstraint(D({codec:l,bitRate:this.abrEnabled?B:this.options.get("maxVideoBitRate")},f))}h&&(this.modules.subscription.setAudioConstraint({codec:h,bitRate:this.abrEnabled?C:this.options.get("maxAudioBitRate"),language:this.options.get("language")}),(!m.includes(this.options.get("language"))||this.language===void 0)&&this.modules.subscription.setLanguage(m[0])),this.alignSizeAndBitRate(this.targetSubscription);const y=this.modules.subscription.getTargetSubscription();this.emitter.emit("subscription changed",{to:y,from:this.modules.subscription.getCurrentSubscription()})});I(this,"isSupportedVideoCodecProfile",(t,e)=>{if(this.willUseMediaSource()){const g=Sg();return g?g.isTypeSupported(ze({codec:t,codecString:e})):!0}if(t==="h264"){const g=!!(e!=null&&e.startsWith("avc1.42")),B=!!(e!=null&&e.startsWith("avc1.66."));return g||B}return t!=="av1"});I(this,"supportedAudioCodecs",()=>{if(this.options.get("media")==="video")return[];const t=[];return this.willUseMediaSource()&&t.push("aac"),(this.browser.supportsMp4Opus&&this.options.get("mseOpusEnabled")||!this.willUseMediaSource())&&t.push("opus"),t});I(this,"initializeDecodingModule",()=>r(this,null,function*(){var g,B;const t=this.currentRenditionLevel,e=[];if(!t)throw new x("No currentRenditionLevel",{code:"no_current_rendition_level",isFatal:!1});if(t!=null&&t.video&&e.push({type:"video",mimeType:ze(t.video),codec:t.video.codec}),t!=null&&t.audio&&e.push({type:"audio",codec:t.audio.codec,mimeType:ze(t.audio)}),e.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(g=this.modules.mseModule)==null?void 0:g.setSourceBuffers(e);else{const C=yield ro.create(this.emitter,this.logger.createContext("DecoderModule"),e,this.playbackSource,this.pool);(B=this.modules.decoder)==null||B.unload(),this.modules.decoder=C,this.modules.decoder.load()}}));I(this,"unload",()=>r(this,null,function*(){var t,e,g;this.logger.debug("Unloading modules..."),yield Promise.all(Object.values(this.modules).map(B=>B==null?void 0:B.unload())),(t=this.wakeLock)==null||t.unload(),this.pool=new xt(oe.MAX_POOL_SIZE),(g=(e=this.playbackSource).unload)==null||g.call(e),this.element.remove(),this.emitter.reset(),this.encryptedMediaExtensions.unload(),this.reset(),this.logger.debug("Unloaded modules")}));I(this,"userInput",()=>{this.play()});I(this,"pause",()=>{this.options.get("pauseSupportEnabled")&&this.playbackState!=="paused"&&(this.playbackSource.pause(),this.hasCalledConnect&&this.suspend())});I(this,"registerDebugInstance",()=>{dd(this)});I(this,"play",()=>{var t;this.hasCalledConnect?this.unsuspend():this.playbackState!=="playing"&&(this._connect(),self.addEventListener("__vindral_register_debug__",this.registerDebugInstance),this.modules.timer.setInterval(()=>this.cleanupTextTracks(),oe.REMOVE_CUE_THRESHOLD)),(t=this.wakeLock)==null||t.enable(),this.playbackState==="paused"&&(this.resetModules(),this.emitter.emit("flush buffers"),this.cleanupTextTracks(Number.MAX_SAFE_INTEGER)),this.playbackSource.play()});I(this,"getStatistics",()=>{const t=Object.values(this.modules).reduce((g,B)=>B&&"getStatistics"in B?D(D({},g),B.getStatistics()):g,this.getRuntimeInfo()),e=Math.round(this.timeActive>0?(t.bytesReceived||0)*8/(this.timeActive/1e3):0);return V(D({},t),{averageBitRate:e})});I(this,"resetModules",()=>{Object.values(this.modules).forEach(t=>{t&&"reset"in t&&t.reset()}),this.sampleProcessingSesssions.clear(),this.playbackSource.currentTime=0,this.playbackSource.isActivated=!1});I(this,"getRuntimeInfo",()=>{const t=this.modules.canvasModule?this.options.get("iosMediaElementEnabled"):void 0;return D({uptime:Date.now()-this.createdAt,version:"4.1.5-4-g2cb8ae2c",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(),iosMediaElementEnabled:t},this.userAgentInformation.getUserAgentInformation())});I(this,"onMediaElementState",t=>{this.logger.info("media element state",{state:t}),this.options.get("pauseSupportEnabled")&&(t==="paused"?this.modules.documentState.isVisible&&(this.suspend(),this.modules.connection.disconnect()):(this.unsuspend(),this.modules.connection.getState()==="disconnected"&&this.modules.connection.unsuspend()))});I(this,"onBufferEvent",t=>{var g,B,C,Q;this.emit("buffer state event",t);const e=!this.playbackSource.isActivated||this.playbackSource.isPaused;if(t==="filled"&&e){const o=Math.max(this.currentTime,(B=(g=this.videoBufferedRanges[0])==null?void 0:g.start)!=null?B:0,(Q=(C=this.audioBufferedRanges[0])==null?void 0:C.start)!=null?Q:0);this.logger.info("Buffer filled - starting playback",{currentTime:o}),this.playbackSource.currentTime=o,this.modules.sync.activateSyncAdjustments(),this.playbackSource.isActivated=!0}else t==="drained"&&this.playbackSource.isPaused&&(this.playbackSource.isActivated=!1,this.modules.sync.deactivateSyncAdjustments())});I(this,"timeToFirstFrame",()=>{const t=this.modules.playback.getFirstFrameTime(),e=this.modules.connection.firstConnectionTime;if(e&&t)return t-e});this.options=new fu(D(D({},Ac),Ru(t)));const e=["localhost","127.0.0.1"];t.telemetryEnabled===void 0&&e.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}},B=UA.get();B.setLevel(this.options.get("logLevel")),B.setDebug(!1),this.logger=B;const C=po.create(this.emitter,this.logger.createContext("PictureInPictureModule")),Q=NA.create(),o=no.create(this.emitter,this.logger.createContext("ConnectionModule"),{reconnectHandler:this.options.get("reconnectHandler"),options:this.options,onConnectInfo:this.onConnectInfo}),a=Uo.create(this.logger.createContext("SubscriptionModule"),this.emitter,g),c=Ro.create(this.emitter,a),h=ko.create(this.emitter,this.logger.createContext("QualityOfServiceModule"),c),l=Fo.create(this.emitter,this.logger.createContext("PlaybackModule"),this,this.options.get("minBufferTime"));this.encryptedMediaExtensions=new $n(this.emitter,this.logger.createContext("EncryptedMediaExtensions"),t.drm),this.drm={setHeaders:w=>{this.encryptedMediaExtensions.headers=w},setQueryParams:w=>{this.encryptedMediaExtensions.queryParams=w}};const m=co.create(this.emitter),y=this.options.get("poster"),f=y===!0?this.getThumbnailUrl():y||void 0;let k,q,U;if(this.willUseMediaSource()){const w=new TQ({type:this.options.get("media")=="audio"?"audio":"video",autoplay:!1,muted:this.options.get("muted")||this.options.get("media")==="video",logger:this.logger.createContext("MediaElement"),poster:f});w.on("buffer state",G=>this.emitter.emit("buffer state",G)),w.on("needs user input",G=>this.emitter.emit("needs user input",G)),w.on("volume state",G=>this.emit("volume state",G)),w.on("media element state",G=>this.onMediaElementState(G)),this.element=w.element,this.playbackSource=w,$n.isSupported()&&this.encryptedMediaExtensions.attach(w.element),k=fo.create(this.logger.createContext("MseModule"),this.emitter,this.element),this.options.get("pauseSupportEnabled")||(q=cC.create(this.logger.createContext("UnpauseModule"),w,m)),this.options.get("pictureInPictureEnabled")&&this.emitter.emit("add picture in picture listener",{element:w.element})}else if(this.browser.platform.iosVersion>=15&&this.options.get("iosMediaElementEnabled")){const w=yo.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",poster:f}),G=w.element();this.element=G.element,this.playbackSource=w,U=w,this.options.get("pictureInPictureEnabled")&&this.browser.platform.iosVersion>15&&this.emitter.emit("add picture in picture listener",{element:this.element}),this.options.get("pauseSupportEnabled")||(q=cC.create(this.logger.createContext("UnpauseModule"),G,m))}else{const w=So.create(this.emitter,this.logger.createContext("LegacyCanvasModule"),this.pool,this,this.options.get("muted")||this.options.get("media")==="video");this.element=w.element(),this.playbackSource=w,U=w,this.options.get("iosWakeLockEnabled")&&(this.wakeLock=new cd)}this.emitter.on("channel reset",this.resetModules),this.emitter.on("no data timeout",this.resetModules),this.emitter.on("media element state",w=>this.onMediaElementState(w)),this.emitter.on("volume state",w=>this.emit("volume state",w)),this.options.get("pauseSupportEnabled")||this.emitter.on("exit picture in picture",()=>Q.setTimeout(()=>this.play(),0)),this.emitter.on("constraint cap changed",w=>{this.logger.info("new cap set",{cap:w}),this.alignSizeAndBitRate(this.targetSubscription)}),this.pictureInPicture={enter:()=>C.requestPictureInPicture(),exit:()=>C.exitPictureInPicture(),isActive:()=>C.isPictureInPictureActive(),isSupported:()=>C.isPictureInPictureSupported()},this.emitter.on("error",w=>{if(w.type()==="external"&&this.emit("error",w),w.isFatal())return()=>void this.unload()});const H=this.browser.platform.isIOS&&!this.browser.platform.isIpadOS,T=No.create(this.emitter,this.logger.createContext("SyncModule"),this.playbackSource,l,this.willUseMediaSource()&&!H),z=uo.create(this.logger.createContext("JitterModule")),Y=(this.options.get("edgeUrl")||this.options.get("url")).replace("wss://","https://").replace("ws://","http://").replace("//lb.","//errors."),FA=new URL("/telemetry",Y).toString(),nA=rC.create(this.logger.createContext("TelemetryModule"),this.emitter,{url:FA,enabled:this.options.get("telemetryEnabled"),includeStats:!1,interval:5e3},this);this.modules={telemetry:nA,bufferTime:OQ.create(this.emitter,this.logger.createContext("BufferTimeModule"),h,this,{maxBufferTime:this.options.get("maxBufferTime"),minBufferTime:this.options.get("minBufferTime")}),incomingData:lo.create(this.emitter),adaptivity:WQ.create(this.emitter,this.logger.createContext("AdaptivityModule"),h,{cooldownTime:Math.max(this.options.get("minBufferTime"),2e3)}),constraintCap:Eo.create(this.emitter,this.element,c,this.options.get("abrEnabled")?this.options.get("sizeBasedResolutionCapEnabled"):!1),event:ho.create(this.emitter,this.logger.createContext("EventModule"),T),sync:T,jitter:z,documentState:m,connection:o,playback:l,pictureInPicture:C,timer:Q,subscription:a,renditions:c,qualityOfService:h,mseModule:k,unpause:q,canvasModule:U},this.modules.adaptivity.isEnabled=this.options.get("abrEnabled"),this.emitter.on("page active",w=>{var G;w&&typeof this.disconnectTimeout=="number"&&(this.modules.timer.clearInterval(this.disconnectTimeout),this.disconnectTimeout=void 0),w?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(),(G=this.modules.canvasModule)==null||G.unsuspend()):this.modules.connection.disconnect():(this.disconnectTimeout&&this.modules.timer.clearInterval(this.disconnectTimeout),this.disconnectTimeout=this.modules.timer.setInterval(()=>{const AA=this.playbackState==="paused"||this.muted;this.connectionState==="connected"&&AA&&(this.emitter.emit("flush buffers"),this.modules.connection.disconnect("Page inactive timeout"))},oe.DISCONNECT_TIMEOUT)))});let mA;this.emitter.on("context switch complete",()=>{mA||(mA=window.setTimeout(()=>{window.clearTimeout(mA),mA=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",w=>this.emit("needs user input",w)),this.emitter.on("event",w=>{switch(w.type){case"metadata":this.emit("metadata",w);break;case"channel switch":this.emit("channel switch",{channelId:w.channelId});break;case"language switch":this.emit("language switch",{language:w.language});break}}),this.emitter.on("buffer state event",this.onBufferEvent),this.emitter.on("playback state",w=>this.emit("playback state",w)),this.emitter.on("rendition level changed",({to:w})=>{w&&this.emit("rendition level",w)}),this.emitter.on("connection state",w=>{this.emit("connection state",w)}),this.emitter.on("recovered from media error",()=>{this.modules.adaptivity.reset(this.targetBufferTime*2)}),this.emitter.once("connect info",w=>{var iA,O,_;const AA=((O=(iA=w.telemetry)==null?void 0:iA.probability)!=null?O:1)>=Math.random();w.telemetry&&((_=this.modules.telemetry)==null||_.unload(),this.modules.telemetry=rC.create(this.logger.createContext("TelemetryModule"),this.emitter,V(D({},w.telemetry),{enabled:this.options.get("telemetryEnabled")&&AA}),this),this.modules.telemetry.load())}),this.emitter.on("adapt level",w=>{var R,L,Z,aA,P;this.logger.debug("adapt level",{direction:w});const G=this.modules.renditions.getRenditionLevels(),AA=this.modules.renditions.getRenditionLevel(),iA=G.findIndex(X=>X===AA),O=G.length-1;let _=iA;switch(w){case"upgrade":{const X=Math.min(iA+1,O),WA=G[X],dg=(R=this.modules.connection.estimatedBandwidth)!=null?R:he(),DB=((Z=(L=WA==null?void 0:WA.audio)==null?void 0:L.bitRate)!=null?Z:0)+((P=(aA=WA==null?void 0:WA.video)==null?void 0:aA.bitRate)!=null?P:0),Pi=dg*2>DB;WA&&Pi&&this.modules.adaptivity.isQoSOk(WA)&&(_=X)}break;case"downgrade":_=Math.max(iA-1,0);break;case"double downgrade":_=Math.max(iA-2,0);break;case"reconnect":if(iA===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 _=0}if(_===iA)return;const QA=G[_];this.alignSizeAndBitRate(V(D({},this.targetSubscription),{video:D(D({},this.targetSubscription.video),QA==null?void 0:QA.video),audio:D(D({},this.targetSubscription.audio),QA==null?void 0:QA.audio)})),this.emitter.emit("adapted level")}),this.emitter.on("text track data",w=>{const G=s(this,At).find(_=>_.language===w.language),iA=this.modules.sync.getTimeshiftOffset()/1e3,O=iA-s(this,Yi);if(E(this,Yi,iA),G){if(G.cues)for(const _ of G.cues)_.startTime-=O,_.endTime-=O;for(const _ of w.cues){const QA=new VTTCue(_.startTime-iA,_.endTime-iA,_.text);G.addCue(QA)}}}),this.emitter.on("received signal",w=>{var iA;const G=w,AA=this.modules.subscription.getCurrentSubscription();switch(this.logger.debug("received",D({},G)),G.type){case"client ip":this.clientIp=G.ip;break;case"renditions":this.updateTextTracks(G.renditions),E(this,Ti,this.filterRenditions(G.renditions).then(O=>{this.emitter.emit("renditions",{renditions:O,channelId:this.currentSubscription.channelId}),this.emit("rendition levels",this.modules.renditions.getRenditionLevels()),this.emitLanguagesIfChanged()}).finally(()=>{E(this,Ti,void 0)}));break;case"subscription changed":try{Uu(G.subscription)}catch(O){this.emitter.emit("error",new x("Subscription failed validation",{source:O instanceof Error?O:void 0,isFatal:!1,code:"subscription_failed_validation"}))}this.emitter.emit("subscription changed",{reset:G.reset,to:G.subscription,from:this.modules.subscription.getCurrentSubscription()}),G.reset&&AA.channelId!==G.subscription.channelId&&(this.emit("error",Vn(G.subscription.channelId)),this.emit("channel switch failed",{channelId:AA.channelId})),this.modules.sync.timeshiftOnAudio=!((iA=G.subscription.video)!=null&&iA.codec),this.modules.adaptivity.reset();break;case"timing info":this.modules.sync.updateChannelSyncInfo(G.timingInfo.channelId,G.timingInfo),this.emit("server wallclock time",G.timingInfo.wallclockTime);break}}),this.emitter.on("channel switch timeout",w=>{this.emit("error",Vn(w)),this.emit("channel switch failed",{channelId:this.currentSubscription.channelId})}),this.emitter.on("received data",w=>{const G=this.modules.subscription.getCurrentSubscription(),AA=Ed(w);if(!G){this.logger.warn("Received unwanted message",D({},AA));return}JA(V(D({},AA),{channelId:G.channelId}))}),this.emitter.on("received moq data",w=>{var _,QA,R;const G=w.payload.mediaType(),AA=w.channelId,iA=w.renditionId,O=this.modules.sync.processFragment(AA,w.payload);if(G!=="text"&&this.modules.jitter.recordSample({type:G,renditionId:iA,timestamp:O.baseMediaDecodeTime(),timescale:O.timescale()}),w.switchInfo.channelId&&(w.switchInfo.drmTransition&&this.emitter.emit("error",Zn("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:w.switchInfo.channelId,timestamp:O.baseMediaDecodeTime()/O.timescale()*1e3})),w.switchInfo.language&&this.modules.event.addEvent({type:"language switch",language:w.switchInfo.language,timestamp:O.baseMediaDecodeTime()/O.timescale()*1e3}),this.modules.incomingData.add(G,w.payload.rawBytes().byteLength),O.fragment().emsgs.forEach(L=>{if(!L.presentationTime)return;const Z=Kc(L.data);Z&&this.modules.event.addEvent({id:L.id,timestamp:L.presentationTime/L.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:Z.txx.value,type:"metadata"})}),this.modules.decoder){const L=(_=O.header().init().moov.traks[0])==null?void 0:_.mdia.minf.stbl.stsd,Z=(QA=L==null?void 0:L.avc1)==null?void 0:QA.avcC.bytes,aA=(R=L==null?void 0:L.codec)!=null?R:"h264";if(Z){const P=Z.buffer.slice(Z.byteOffset,Z.byteOffset+Z.byteLength);if(G==="text")throw new Error("Subtitles are not supported");this.emitter.emit("init segment",{initSegment:{channelId:AA,renditionId:iA,data:P,timescale:1e3,type:G,codec:aA},mimeType:G})}for(let P=0;P<O.samplesCount();P++){const X=O.sample(P);X&&this.emitter.emit("coded sample",V(D({},X),{renditionId:iA,channelId:AA,data:X.data.buffer.slice(X.data.byteOffset,X.data.byteOffset+X.data.byteLength)}))}}else this.emitter.emit("fragment",{mimeType:w.mimeType,codec:w.codec,fragment:O,channelId:AA,renditionId:iA})});const tt=this.options.get("container");tt&&this.attach(tt),this.logger.info("Created Vindral instance",{options:this.options});const JA=w=>r(this,null,function*(){const G=w.channelId;s(this,Ti)&&(yield s(this,Ti));const AA=this.modules.renditions.getRendition(w.renditionId,G);if(!od(w.flags)){if(nd(w.flags)){const O=new TextDecoder().decode(w.payload),_=this.modules.sync.getTimeshiftOffset();if(w.renditionId!==0){const QA=pn(O);if(QA&&QA.language!==void 0){const L=new aa().parse(QA.content||""),Z=_/1e3,aA=s(this,At).find(X=>X.language===QA.language),P=Z-s(this,Yi);if(E(this,Yi,Z),aA){if(aA.cues)for(const X of aA.cues)X.startTime-=P,X.endTime-=P;for(const X of L){const WA=new VTTCue(X.startTime-Z,X.endTime-Z,X.text);aA.addCue(WA)}}}}else this.modules.event.addEvent({timestamp:w.timestamp/w.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:O,type:"metadata"})}else if(AA!=null&&AA.codec){const iA=RQ(AA.codec);if(iA==="text")throw new Error("Subtitles are not supported");if(this.modules.incomingData.add(iA,w.payload.byteLength),Qd(w.flags)){const O=V(D({type:iA,data:w.payload,codec:AA.codec},w),{channelId:G}),_=id(O.codec,O.payload);_&&this.sizes.set(O.renditionId,_);const QA=ze({codec:AA.codec,codecString:AA.codecString});this.emitter.emit("init segment",{initSegment:O,mimeType:QA}),this.emit("initialized media")}else{const O=Gu(w,AA,this.sizes.get(w.renditionId));this.modules.jitter.recordSample(O);let _=this.sampleProcessingSesssions.get(iA);if(!_)_=Fu(this.modules.sync.processSample(O)),this.sampleProcessingSesssions.set(iA,_);else{const QA=_(this.modules.sync.processSample(O),this.isSwitchingRenditionLevel&&O.type==="video");let R=O;QA.forEach(L=>{this.modules.event.extractEvent(L,R),this.emitter.emit("coded sample",L),R=L})}}}}});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")),Ve(this.options.get("maxSize"),kB())||(this.maxSize=this.options.get("maxSize")),this.options.get("burstEnabled")&&a.enableBurst(this.targetBufferTime)}set volume(t){this.playbackSource.volume=t}get volume(){return this.playbackSource.volume}set muted(t){if(t===this.muted)return;const e=this.playbackSource.muted;this.playbackSource.muted=t,!t&&e&&!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(t){this.modules.constraintCap.sizeBasedResolutionCapEnabled=t}get abrEnabled(){return this.modules.adaptivity.isEnabled}set abrEnabled(t){this.modules.constraintCap.sizeBasedResolutionCapEnabled=t?this.options.get("sizeBasedResolutionCapEnabled"):!1,this.modules.adaptivity.isEnabled=t,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(t){this.modules.playback.getTargetBufferTime()!==t&&(this.modules.playback.setTargetBufferTime(t),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 t;if(this.playbackSource.currentTime!==0)return this.targetBufferTime+((t=this.modules.sync.drift)!=null?t: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(t){this.modules.subscription.setLanguage(t)}set textTrack(t){s(this,At).forEach(e=>{e.label===t?e.mode="showing":e.mode="hidden"}),this.emitter.emit("text track",t)}get textTracks(){return s(this,At).filter(t=>t.mode!=="disabled").map(t=>t.label)}get textTrack(){var t;return(t=s(this,At).find(e=>e.mode==="showing"))==null?void 0:t.label}get channelId(){var t,e;return(e=(t=this.modules)==null?void 0:t.subscription.getTargetSubscription().channelId)!=null?e:this.options.get("channelId")}set channelId(t){if(t===this.channelId)return;this.modules.subscription.setChannelId(t);const e=this.options.get("media")==="audio"?[]:this.options.get("videoCodecs"),g=this.modules.renditions.getAudioRenditions(t),B=this.modules.renditions.getVideoRenditions(t),C=this.targetSubscription.audio.language,Q=g==null?void 0:g.some(a=>a.language===C),o=e.find(a=>(B==null?void 0:B.find(c=>c.codec===a))!==void 0);o&&this.modules.subscription.setVideoCodec(o),this.logger.debug("Channel switch - started",{audioRenditions:g,targetSubscriptionLanguage:C,targetHasCurrentLanguage:Q}),this.alignSizeAndBitRate(this.targetSubscription)}get maxSize(){var g,B;const{width:t,height:e}=(B=(g=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:g.video)!=null?B:kB();return{width:t,height:e}}set maxSize(t){this.modules.constraintCap.setUserSpecifiedCap({video:{width:t.width,height:t.height}}),this.alignSizeAndBitRate(this.targetSubscription)}get maxVideoBitRate(){var t,e;return(e=(t=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:t.video.bitRate)!=null?e:he()}set maxVideoBitRate(t){this.modules.constraintCap.setUserSpecifiedCap({video:{bitRate:t}}),this.alignSizeAndBitRate(this.targetSubscription)}get maxAudioBitRate(){var t,e;return(e=(t=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:t.audio.bitRate)!=null?e:he()}set maxAudioBitRate(t){this.modules.constraintCap.setUserSpecifiedCap({audio:{bitRate:t}}),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 t,e,g,B;return(B=(g=(t=this.modules.mseModule)==null?void 0:t.getBuffer("video"))!=null?g:(e=this.modules.decoder)==null?void 0:e.getBuffer("video"))!=null?B:[]}get audioBufferedRanges(){var t,e,g,B;return(B=(g=(t=this.modules.mseModule)==null?void 0:t.getBuffer("audio"))!=null?g:(e=this.modules.decoder)==null?void 0:e.getBuffer("audio"))!=null?B:[]}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 t;return(t=this.modules)!=null&&t.canvasModule?this.modules.canvasModule.audioNode:void 0}get drmStatistics(){var t;return(t=this.encryptedMediaExtensions)==null?void 0:t.getStatistics()}get uptime(){return Date.now()-this.createdAt}suspend(){this.isSuspended||(Object.values(this.modules).forEach(t=>{t&&"suspend"in t&&t.suspend()}),this.isSuspended=!0)}unsuspend(){this.isSuspended&&(Object.values(this.modules).forEach(t=>{t&&"unsuspend"in t&&t.unsuspend()}),this.isSuspended=!1)}alignSizeAndBitRate(t){const e=this.modules.constraintCap.constrainSubscription(V(D({},t),{video:D({},t.video),audio:D({},t.audio)})),g=this.modules.constraintCap.getUserSpecifiedCap();!this.abrEnabled&&g&&(e.audio.bitRate=g.audio.bitRate,e.video.bitRate=g.video.bitRate,e.video.width=g.video.width,e.video.height=g.video.height);const B=this.modules.renditions.getRenditionLevel(e);if(B){if(B.video&&(this.modules.subscription.setVideoBitRate(B.video.bitRate),this.modules.subscription.setSize(B.video)),B.audio)this.modules.subscription.setAudioBitRate(B.audio.bitRate),this.modules.subscription.setLanguage(B.audio.language);else if(e.audio.language){let C=this.modules.renditions.getAudioRenditions(e.channelId);!this.abrEnabled&&g&&(C=C==null?void 0:C.filter(h=>h.bitRate<g.audio.bitRate));const Q=e.audio.language,o=C==null?void 0:C.some(h=>h.language===Q),a=C==null?void 0:C.find(h=>h.language),c=(C==null?void 0:C.length)&&C[0]||void 0;o||(a?(this.logger.debug("Randomizing language since target did not have current language"),this.modules.subscription.setAudioBitRate(a.bitRate),this.modules.subscription.setLanguage(a.language)):(this.logger.debug("Randomizing audio rendition since target did not have current language"),c!=null&&c.bitRate&&this.modules.subscription.setAudioBitRate(c.bitRate),this.modules.subscription.setLanguage(c==null?void 0:c.language)))}}}get currentSubscription(){return this.modules.subscription.getCurrentSubscription()}get targetSubscription(){return this.modules.subscription.getTargetSubscription()}willUseMediaSource(){return this.browser.supportsMediaSource&&this.options.get("mseEnabled")}};Yi=new WeakMap,At=new WeakMap,Ti=new WeakMap,I(oe,"MAX_POOL_SIZE",10),I(oe,"DISCONNECT_TIMEOUT",15*1e3),I(oe,"REMOVE_CUE_THRESHOLD",1e3*10);let hC=oe;const QE={bar:"_bar_qm7bl_1",hidden:"_hidden_qm7bl_47"},Ug={"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"},Nu={"icon-button":"_icon-button_5fg7v_1"},oE={enter:{viewBox:"-12 -12 38 38",content:`<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" transform="translate(-5.000000, -5.000000)">
|
|
49
|
+
`,Xa={width:256,codedWidth:256,height:144,codedHeight:144},ja={preserveDrawingBuffer:!1,alpha:!1,depth:!1,stencil:!1,antialias:!1,premultipliedAlpha:!1},lB=class lB extends it{constructor(){super();I(this,"canvas",document.createElement("canvas"));I(this,"context",Wa(this.canvas,ja));I(this,"pixelShader",tI(this.context,this.context.FRAGMENT_SHADER,Va));I(this,"vertexShader",tI(this.context,this.context.VERTEX_SHADER,Za));I(this,"buffer",Oa(this.context,lB.SQUARE_VERTICES));I(this,"program",Do(this.context,this.vertexShader,this.pixelShader));I(this,"textures",{y:Ai(this.context),u:Ai(this.context),v:Ai(this.context)});I(this,"textRenderer");I(this,"size",Xa);I(this,"onContextLost",t=>{this.textRenderer=void 0;const e=new Error(t instanceof WebGLContextEvent?t.statusMessage:"webgl context lost");this.emit("context lost",uc(e)),t.preventDefault()});I(this,"onContextRestored",()=>{this.emit("context restored"),this.context=Wa(this.canvas,ja),this.pixelShader=tI(this.context,this.context.FRAGMENT_SHADER,Va),this.vertexShader=tI(this.context,this.context.VERTEX_SHADER,Za),this.buffer=Oa(this.context,lB.SQUARE_VERTICES),this.program=Do(this.context,this.vertexShader,this.pixelShader),this.textures={y:Ai(this.context),u:Ai(this.context),v:Ai(this.context)},this.load()});I(this,"load",()=>{this.context.useProgram(this.program),this.setupPositionVertexAttributes(),this.setSize(Xa),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(this.rec709())});I(this,"unload",()=>{var e;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),(e=this.context.getExtension("WEBGL_lose_context"))==null||e.loseContext()});I(this,"resetSize",()=>{this.setSize({width:this.size.width/2,height:this.size.height/2,codedHeight:this.size.codedHeight/2,codedWidth:this.size.codedWidth/2})});I(this,"render",(t,e)=>{var g;this.context.useProgram(this.program),this.setSize({width:t.width,height:t.height,codedWidth:t.codedWidth,codedHeight:t.codedHeight}),this.setConversionMatrix(this.rec709()),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,t.data[0]),this.context.activeTexture(this.context.TEXTURE1),this.updateTexture(this.textures.u,this.size.codedWidth/2,this.size.codedHeight/2,t.data[1]),this.context.activeTexture(this.context.TEXTURE2),this.updateTexture(this.textures.v,this.size.codedWidth/2,this.size.codedHeight/2,t.data[2]),this.context.drawArrays(this.context.TRIANGLE_STRIP,0,4),this.textRenderer&&this.textRenderer.render({width:Math.max(e.clientWidth,960)*window.devicePixelRatio,height:Math.max(e.clientHeight,540)*window.devicePixelRatio,padding:-parseInt((g=e.style.getPropertyValue("--vindral-control-bar-offset"))!=null?g:"0",10)})});I(this,"updateTexture",(t,e,g,B)=>{const Q=this.context.LUMINANCE,o=this.context.UNSIGNED_BYTE;this.context.bindTexture(this.context.TEXTURE_2D,t),this.context.texImage2D(this.context.TEXTURE_2D,0,Q,e,g,0,Q,o,B)});I(this,"setupPositionVertexAttributes",()=>{const t=this.context.getAttribLocation(this.program,"position");this.context.enableVertexAttribArray(t),this.context.vertexAttribPointer(t,2,this.context.FLOAT,!1,0,0)});I(this,"setSize",t=>{Ve(t,this.size)||(this.size=t,this.canvas.setAttribute("width",t.width.toString()),this.canvas.setAttribute("height",t.height.toString()),this.context.viewport(0,0,t.width,t.height),this.setModelMatrix(t.width/t.codedWidth,t.height/t.codedHeight))});I(this,"setModelMatrix",(t,e)=>{const g=this.context.getUniformLocation(this.program,"model");this.context.uniformMatrix4fv(g,!1,this.transformMatrix(t,e))});I(this,"setConversionMatrix",t=>{const e=this.context.getUniformLocation(this.program,"conversion");this.context.uniformMatrix4fv(e,!1,t)});I(this,"transformMatrix",(t,e)=>[2/t,0,0,0,0,-2/e,0,0,0,0,2/1,0,-1,1,0,1]);I(this,"rec709",()=>[1.16438,0,1.79274,-.97295,1.16438,-.21325,-.53291,.30148,1.16438,2.1124,0,-1.1334,0,0,0,1]);I(this,"rec601",()=>[1.16438,0,1.59603,-.87079,1.16438,-.39176,-.81297,.52959,1.16438,2.01723,0,-1.08139,0,0,0,1]);this.canvas.addEventListener("webglcontextlost",this.onContextLost),this.canvas.addEventListener("webglcontextrestored",this.onContextRestored,!1),this.canvas.style.width="100%",this.canvas.style.position="relative"}getTextRenderer(){return this.textRenderer||(this.textRenderer=new nu(this.context)),this.textRenderer}};I(lB,"SQUARE_VERTICES",new Float32Array([0,0,0,1,1,0,1,1]));let mo=lB;const eQ=class eQ{constructor(A,t,e,g){I(this,"oldTimestampLimit",400);I(this,"pool");I(this,"logger");I(this,"videoRenderer",new mo);I(this,"renderQueue",[]);I(this,"clockSource");I(this,"isFirstFrame",!0);I(this,"animationFrameRequest");I(this,"renderedFrameCount",0);I(this,"rendererDroppedFrameCount",0);I(this,"renderTargetSize");I(this,"load",()=>{this.videoRenderer.load()});I(this,"unload",()=>(this.stopRender(),this.videoRenderer.unload(),Promise.resolve()));I(this,"suspend",()=>{this.renderQueue=[],this.stopRender()});I(this,"unsuspend",()=>{this.animationFrameRequest=requestAnimationFrame(this.render)});I(this,"element",()=>this.videoRenderer.canvas);I(this,"getStatistics",()=>({renderedFrameCount:this.renderedFrameCount,rendererDroppedFrameCount:this.rendererDroppedFrameCount,contextLostCount:0,contextRestoredCount:0}));I(this,"resetSize",()=>{this.videoRenderer.resetSize()});I(this,"setActiveCues",(A,t)=>{this.videoRenderer.getTextRenderer().setActiveCues(A,t)});I(this,"onDecodedFrame",A=>{if(A.type==="video")if(this.isFirstFrame)this.isFirstFrame=!1,requestAnimationFrame(()=>{this.renderSample(A)});else{const t=(this.clockSource.currentTime-this.oldTimestampLimit)/1e3;this.renderQueue=this.renderQueue.filter(e=>{const g=e.timestamp/e.timescale,B=A.timestamp/A.timescale,C=g>t&&g<=B;return C||this.pool.reclaim(e.buffer),C}),this.renderQueue.push(A)}});I(this,"render",()=>{const A=this.clockSource.currentTime;let t=this.renderQueue[0],e,g=0;for(;t&&(t.timestamp+(t.compositionTimeOffset||0))/t.timescale*1e3<=A;)t=this.renderQueue.shift(),t&&(g++,e&&this.pool.reclaim(e.buffer),e=t),t=this.renderQueue[0];e&&this.renderSample(e),this.rendererDroppedFrameCount+=Math.max(g-1,0),this.animationFrameRequest=requestAnimationFrame(this.render)});I(this,"renderSample",A=>{this.renderedFrameCount++,this.videoRenderer.render(A,this.renderTargetSize),this.pool.reclaim(A.buffer)});I(this,"stopRender",()=>{this.animationFrameRequest&&cancelAnimationFrame(this.animationFrameRequest)});this.logger=A,this.clockSource=t,this.pool=e,this.renderTargetSize=g||this.videoRenderer.canvas}};I(eQ,"create",(A,t,e,g)=>new eQ(A,t,e,g));let EC=eQ;class za{constructor(){n(this,Ye,[]);E(this,Ye,[])}addTextTrack(A,t,e){const g=[],B={kind:A,label:t,language:e,mode:"disabled",cues:g,addCue:C=>{g.push(C)},removeCue:C=>{const Q=g.findIndex(o=>o===C);Q!==-1&&g.splice(Q,1)}};return s(this,Ye).push(B),B}set language(A){s(this,Ye).forEach(t=>{t.language===A?t.mode="showing":t.mode="hidden"})}get language(){var A;return(A=s(this,Ye).find(t=>t.mode==="showing"))==null?void 0:A.language}getActiveCues(A){const t=s(this,Ye).find(e=>e.mode==="showing");return t?t.cues.filter(({startTime:e,endTime:g})=>A>=e&&A<=g):[]}}Ye=new WeakMap;const ti=(i,A)=>{let t;for(t=A;i>1;i--)t+=A;return t};class au{constructor(){I(this,"audio");I(this,"unmute",()=>this.audio.play().catch(F));const A=document.createElement("div");A.innerHTML="<audio x-webkit-airplay='deny'></audio>";const t=A.children.item(0);if(t instanceof HTMLAudioElement)this.audio=t,this.audio.controls=!1,this.audio.disableRemotePlayback=!0,this.audio.preload="auto",this.audio.src="data:audio/mpeg;base64,//uQx"+ti(23,"A")+"WGluZwAAAA8AAAACAAACcQCA"+ti(16,"gICA")+ti(66,"/")+"8AAABhTEFNRTMuMTAwA8MAAAAAAAAAABQgJAUHQQAB9AAAAnGMHkkI"+ti(320,"A")+"//sQxAADgnABGiAAQBCqgCRMAAgEAH"+ti(15,"/")+"7+n/9FTuQsQH//////2NG0jWUGlio5gLQTOtIoeR2WX////X4s9Atb/JRVCbBUpeRUq"+ti(18,"/")+"9RUi0f2jn/+xDECgPCjAEQAABN4AAANIAAAAQVTEFNRTMuMTAw"+ti(97,"V")+"Q==",this.audio.loop=!1,this.audio.load();else throw new Error("Failed to create audio tag")}}const iQ=class iQ{constructor(A,t,e,g,B,C){I(this,"logger");I(this,"emitter");I(this,"audioPlayer");I(this,"videoPlayer");I(this,"pool");I(this,"unmuter",new au);I(this,"_isPaused",!1);I(this,"isDisconnected",!1);I(this,"timers",new NA);I(this,"textTracks",new za);I(this,"playbackRate");I(this,"reset",()=>{});I(this,"load",()=>{this.audioPlayer.useDefaultDestination(),this.emitter.on("decoded frame",this.onDecodedFrame),this.emitter.on("flush buffers",this.flushBuffers),this.videoPlayer.load(),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)});I(this,"unload",()=>{this.emitter.off("decoded frame",this.onDecodedFrame),this.emitter.off("flush buffers",this.flushBuffers),this.audioPlayer.unload(),this.videoPlayer.unload(),this.timers.unload()});I(this,"suspend",()=>{this.videoPlayer.suspend(),this.audioPlayer.suspend()});I(this,"unsuspend",()=>{this.videoPlayer.unsuspend(),this.audioPlayer.unsuspend()});I(this,"element",()=>this.videoPlayer.element());I(this,"getStatistics",()=>this.videoPlayer.getStatistics());I(this,"flushBuffers",()=>{this.audioPlayer.flushBuffer()});I(this,"activateAudioPlayer",()=>(this.isDisconnected&&(this.isDisconnected=!1,this.audioPlayer.useDefaultDestination()),this._isPaused=!1,this.unmuter.unmute(),this.audioPlayer.play()));I(this,"onDecodedFrame",A=>{try{this.audioPlayer.onDecodedFrame(A)}catch(t){t instanceof Error&&this.emitter.emit("error",Tn(!1,t))}this.videoPlayer.onDecodedFrame(A)});this.logger=t,this.emitter=A,this.pool=e,this.audioPlayer=aC.create(this.logger.createContext("AudioPlayerModule"),g,{muted:B,reInitWhenStuck:!0}),C!==void 0&&(this.audioPlayer.volume=C),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=EC.create(this.logger.createContext("VideoPlayerModule"),this.audioPlayer,this.pool)}get volume(){return this.audioPlayer.volume}set volume(A){this.audioPlayer.volume=A}get muted(){return this.audioPlayer.muted}set muted(A){const t=this.muted;this.audioPlayer.muted=A,!A&&t&&this.activateAudioPlayer().catch(F)}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 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")}};I(iQ,"create",(A,t,e,g,B,C)=>new iQ(A,t,e,g,B,C));let So=iQ;const IQ=class IQ{constructor(A,t,e,g,{muted:B,volume:C,type:Q,poster:o}){I(this,"logger");I(this,"emitter");I(this,"mediaElement");I(this,"audioPlayer");I(this,"videoPlayer");I(this,"pool");I(this,"isDisconnected",!0);I(this,"_userProvidedMuted",!1);I(this,"timers",new NA);I(this,"volumeState");I(this,"textTracks",new za);I(this,"reset",()=>{});I(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.timers.setInterval(()=>{if(!this.textTracks.language)return;const A=this.textTracks.getActiveCues(this.currentTime/1e3);this.videoPlayer.setActiveCues(A,{width:this.mediaElement.element.clientWidth,height:this.mediaElement.element.clientHeight})},100)});I(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.mediaElement.unload(),this.timers.unload(),this.audioPlayer.unload(),this.videoPlayer.unload()});I(this,"suspend",()=>{this.videoPlayer.suspend(),this.audioPlayer.suspend()});I(this,"unsuspend",()=>{this.videoPlayer.unsuspend(),this.audioPlayer.unsuspend()});I(this,"element",()=>this.mediaElement);I(this,"getStatistics",()=>this.videoPlayer.getStatistics());I(this,"activateAudioPlayer",()=>(this.isDisconnected&&this.connectStreams(),this.audioPlayer.play()));I(this,"flushBuffers",()=>{this.audioPlayer.flushBuffer()});I(this,"resetCanvasSize",()=>{this.videoPlayer.resetSize()});I(this,"onEnterIOSHack",()=>{this.mediaElement._iosHackEnterPiPMode()});I(this,"onExitIOSHack",()=>{this.mediaElement._iosHackExitPiPMode()});I(this,"onDecodedFrame",A=>{try{this.audioPlayer.onDecodedFrame(A)}catch(t){t instanceof Error&&this.emitter.emit("error",Tn(!1,t))}this.videoPlayer.onDecodedFrame(A)});I(this,"connectStreams",()=>{const A=this.videoPlayer.element().captureStream(),t=this.audioPlayer.useMediaStreamDestination().stream,e=[];e.push(...A.getTracks(),...t.getTracks()),this.mediaElement.element.srcObject=new MediaStream(e),this.isDisconnected=!1});I(this,"updateVolumeState",()=>{const A={isMuted:this.muted,volume:this.volume};Ve(A,this.volumeState)||(this.volumeState=A,this.emitter.emit("volume state",this.volumeState))});this.logger=t,this.emitter=A,this.pool=e,this._userProvidedMuted=B,this.mediaElement=new TQ({poster:o,type:Q,muted:B,volume:C,autoplay:!1,logger:this.logger.createContext("MediaElement")}),this.mediaElement.on("volume state",a=>{this.updateVolumeState(),!a.isMuted&&!this.audioPlayer.isContextRunning&&this.activateAudioPlayer().catch(F),a.isMuted||(this._userProvidedMuted=!1)}),this.mediaElement.on("media element state",a=>{a==="paused"&&this.audioPlayer.flushBuffer(),this.emitter.emit("media element state",a)}),this.audioPlayer=aC.create(this.logger.createContext("AudioPlayerModule"),g,{muted:!1,reInitWhenStuck:!1}),this.audioPlayer.on("stuck",()=>{this.isDisconnected=!0}),this.audioPlayer.on("state change",a=>{a==="suspended"||a==="interrupted"?this.mediaElement.muted=!0:a==="running"&&(this.mediaElement.muted=this._userProvidedMuted||document.visibilityState==="hidden"),this.updateVolumeState()}),this.videoPlayer=EC.create(this.logger.createContext("VideoPlayerModule"),this.audioPlayer,this.pool,this.mediaElement.element),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 t=this.muted;this._userProvidedMuted=A,this.mediaElement.muted=A,!A&&t&&this.activateAudioPlayer().catch(F)}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 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()}};I(IQ,"create",(A,t,e,g,B)=>new IQ(A,t,e,g,B));let yo=IQ;const Eu=()=>i=>_a(i.buffered.start(0),i.buffered.end(i.buffered.length-1)),_a=(i,A)=>t=>t.remove(Math.max(0,i),Math.min(Number.POSITIVE_INFINITY,A)),$a=i=>A=>A.appendBuffer(i),ru=i=>A=>A.changeType(i),cu=i=>A=>i(A);class hu{constructor(A){I(this,"commandQueue",[]);I(this,"sourceBuffer");I(this,"currentInit");I(this,"handleQueue",()=>{var A;this.sourceBuffer.updating||(A=this.commandQueue.shift())==null||A.execute(this.sourceBuffer)});I(this,"appendBuffer",(A,t)=>new Promise((e,g)=>{if(t&&this.currentInit!==t){const C=new ji($a(t),e,g);this.commandQueue.push(C),this.currentInit=t}const B=new ji($a(A),e,g);this.commandQueue.push(B),this.handleQueue()}));I(this,"execute",A=>new Promise((t,e)=>{const g=new ji(cu(A),t,e);this.commandQueue.push(g),this.handleQueue()}));I(this,"buffered",()=>this.sourceBuffer.buffered);I(this,"removeFromMediaSource",A=>{A.removeSourceBuffer(this.sourceBuffer)});I(this,"changeType",A=>new Promise((t,e)=>{const g=new ji(ru(A),t,e);this.commandQueue.push(g),this.handleQueue()}));I(this,"removeBuffer",(A,t)=>new Promise((e,g)=>{const B=new ji(_a(A,t),e,g);this.commandQueue.push(B),this.handleQueue()}));I(this,"flush",()=>new Promise((A,t)=>{const e=new ji(Eu,A,t);this.commandQueue.push(e),this.handleQueue()}));this.sourceBuffer=A,this.sourceBuffer.addEventListener("updateend",this.handleQueue)}}class AE extends it{constructor(){super();I(this,"MediaSource",Sg());I(this,"mediaSource",new this.MediaSource);I(this,"isOpen",()=>this.mediaSource.readyState==="open");I(this,"isClosed",()=>this.mediaSource.readyState==="closed");I(this,"isEnded",()=>this.mediaSource.readyState==="ended");I(this,"createObjectURL",()=>URL.createObjectURL(this.mediaSource));I(this,"attach",t=>{const e=t;if("srcObject"in e)try{e.srcObject=this.mediaSource}catch(g){if(g instanceof Error&&g.name!=="TypeError")throw g;e.src=this.createObjectURL()}else t.src=this.createObjectURL()});I(this,"detach",t=>{if(this.mediaSource&&this.mediaSource.readyState==="open")try{this.mediaSource.endOfStream()}catch(e){}t.srcObject&&(t.srcObject=null),t.src!==""&&(URL.revokeObjectURL(t.src),t.removeAttribute("src")),t.load()});I(this,"addSourceBuffer",t=>{const e=this.mediaSource.addSourceBuffer(t);return new hu(e)});I(this,"removeSourceBuffer",t=>{t.removeFromMediaSource(this.mediaSource)});I(this,"endOfStream",t=>{this.mediaSource.endOfStream(t)});I(this,"onSourceOpen",()=>{this.setDurationIfNeeded(),this.emit("source open")});I(this,"onSourceEnded",()=>this.emit("source ended"));I(this,"onSourceClosed",()=>this.emit("source close"));I(this,"setDurationIfNeeded",()=>{if(Number.isNaN(this.mediaSource.duration)&&this.mediaSource.readyState==="open"){for(let t=0;t<this.mediaSource.sourceBuffers.length;t++){const e=this.mediaSource.sourceBuffers[t];if(e!=null&&e.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)}}I(AE,"isTypeSupported",t=>{var e,g;return(g=(e=Sg())==null?void 0:e.isTypeSupported(t))!=null?g:!1});class tE{constructor(){I(this,"initSegments",new Map);I(this,"set",(A,t,e)=>{var B;const g=(B=this.initSegments.get(A))!=null?B:new Map;g.set(t,e),this.initSegments.set(A,g)});I(this,"get",(A,t)=>{var e;return(e=this.initSegments.get(A))==null?void 0:e.get(t)})}}function du(i,{mediaSource:A,mimeType:t,codec:e}){return V(D({},i),{state:"initialized",mimeType:t,codec:e,sourceBuffer:A.addSourceBuffer(t),isWorkingOnPendingSamples:!1,sequenceNumber:0,lastBufferCleanupTime:Date.now()})}function eE({initSegments:i,pendingSamples:A}){return{state:"uninitialized",initSegments:i!=null?i:new tE,sequenceNumber:0,isWorkingOnPendingSamples:!1,hasFirstSync:!!A,pendingSamples:A!=null?A:[],consecutiveQuotaExceededErrorCount:0,successfulAppendCalls:0}}const gQ=class gQ{constructor(A,t,e){I(this,"maxChunkSize",20);I(this,"minConsecutiveErrorsBeforeEmit",5);I(this,"maxSecondsInBuffer",60);I(this,"logger");I(this,"timers",NA.create());I(this,"emitter");I(this,"mediaElement");I(this,"mediaSource",new AE);I(this,"trackContexts",new Map);I(this,"autoRecoverFromMediaErrors",!0);I(this,"quotaErrorCount",0);I(this,"recoveredFromErrorCount",0);I(this,"sourceOpenStartTime",Date.now());I(this,"sourceOpenEndTime",Date.now());I(this,"pendingTracksToAddSourceBuffers");I(this,"hasAddedInitialPosterFrame",!0);I(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)});I(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=[]),this.timers.unload(),this.logger.debug("Unloaded module")});I(this,"getStatistics",()=>{var t,e,g,B;const A={quotaErrorCount:this.quotaErrorCount,mediaSourceOpenTime:this.sourceOpenEndTime-this.sourceOpenStartTime,successfulAudioAppendsCalls:(t=this.trackContexts.get("audio"))==null?void 0:t.successfulAppendCalls,successfulVideoAppendCalls:(e=this.trackContexts.get("video"))==null?void 0:e.successfulAppendCalls};if(this.mediaElement instanceof HTMLVideoElement){const C=(B=(g=this.mediaElement).getVideoPlaybackQuality)==null?void 0:B.call(g);A.totalVideoFrames=C==null?void 0:C.totalVideoFrames,A.droppedVideoFrames=C==null?void 0:C.droppedVideoFrames}return A});I(this,"flushBuffers",()=>{this.trackContexts.forEach(A=>{A.pendingSamples=[],A.hasFirstSync=!1,A.state!=="uninitialized"&&this.mediaSource.isOpen()&&A.sourceBuffer.removeBuffer(0,Number.POSITIVE_INFINITY).catch(t=>{this.logger.error("Failed to remove buffer",t)})})});I(this,"setTrackContexts",(A=new Map)=>{this.logger.debug("setTrackContexts"),["audio","video"].forEach(e=>{var C,Q,o,a;const g=(Q=(C=A.get(e))==null?void 0:C.pendingSamples)!=null?Q:[],B=(o=A.get(e))==null?void 0:o.initSegments;for(;g.length>0&&!((a=g[0])!=null&&a.isSync);)g.shift();this.trackContexts.set(e,eE({pendingSamples:g,initSegments:B}))})});I(this,"setSourceBuffers",A=>r(this,null,function*(){if(this.mediaSource.isClosed()){this.pendingTracksToAddSourceBuffers=A;return}let t=!0;for(const e of A){const g=this.trackContexts.get(e.type);if(!g||g.state==="uninitialized"||g.mimeType!==e.mimeType){t=!1;break}}if(t){this.logger.debug("Already setup with the correct mime types");return}for(const e of A){let g=this.trackContexts.get(e.type);g||(g=eE({pendingSamples:[],initSegments:new tE}),this.trackContexts.set(e.type,g)),g.state==="initialized"?e.mimeType!==g.mimeType&&(yield g.sourceBuffer.changeType(e.mimeType)):this.trackContexts.set(e.type,du(g,{mimeType:e.mimeType,mediaSource:this.mediaSource,codec:e.codec}))}}));I(this,"getBuffer",A=>{const t=[];if(this.mediaSource.isClosed())return[];const e=this.trackContexts.get(A);if(!e||e.state==="uninitialized")return[];try{const g=e.sourceBuffer.buffered();if(!g)return[];for(let B=0;B<g.length;B++)t.push({start:g.start(B)*1e3,end:g.end(B)*1e3});return t}catch(g){return[]}});I(this,"init",({initSegment:A,mimeType:t})=>{this.logger.debug("Added init segment",{channel:A.channelId,renditionId:A.renditionId});const e=this.trackContexts.get(A.type);if(!e)throw RB(A.type,A.renditionId);e.state==="initialized"&&(e.mimeType=t);const g=ed({codec:A.codec,timescale:A.timescale,initData:A.data});g&&e.initSegments.set(A.channelId,A.renditionId,new Uint8Array(g))});I(this,"append",(A,t)=>r(this,null,function*(){var Q;const e=A[0];if(!e)return;const g=this.trackContexts.get(e.type),B=g==null?void 0:g.initSegments.get(e.channelId,e.renditionId);if(this.mediaSource.isClosed())return;if(!B)throw ac(e.renditionId,e.channelId);if(!g)throw RB(e.type,e.renditionId);if(g.state==="uninitialized")throw Ec(e.type,e.renditionId);if(t){const o=(e.timestamp+((Q=e.compositionTimeOffset)!=null?Q:0))/e.timescale;yield g.sourceBuffer.removeBuffer(o,Number.POSITIVE_INFINITY);const a=g.previousSample;if(a&&a.codec!==e.codec&&g.sourceBuffer.changeType)try{yield g.sourceBuffer.changeType(g.mimeType)}catch(c){}"fragmented"in e||(yield g.sourceBuffer.appendBuffer(B))}const C=Math.max(0,e.timestamp/e.timescale-this.maxSecondsInBuffer);C>0&&Date.now()-g.lastBufferCleanupTime>1e4&&(g.lastBufferCleanupTime=Date.now(),yield g.sourceBuffer.removeBuffer(0,C+10));try{let o=g.sequenceNumber;if("fragmented"in e)for(const a of A)"initData"in a&&(yield g.sourceBuffer.appendBuffer(a.data,a.initData));else{const a=Cd(A,o++);yield g.sourceBuffer.appendBuffer(a)}g.sequenceNumber=o,g.consecutiveQuotaExceededErrorCount=0,g.successfulAppendCalls++}catch(o){throw o instanceof DOMException&&(o.code===DOMException.QUOTA_EXCEEDED_ERR?(this.quotaErrorCount++,g.consecutiveQuotaExceededErrorCount++,this.logger.error("quota exceeded error",{error:o}),g.pendingSamples.unshift(...A)):this.mediaElement.error&&g.pendingSamples.unshift(...A)),o}}));I(this,"onFragment",({fragment:A,mimeType:t,codec:e,channelId:g,renditionId:B})=>{const C=A.mediaType(),Q=A.rawBytes(),o=A.header().rawBytes(),a=A.baseMediaDecodeTime(),c=A.timescale(),h=A.duration(),l=C==="video"?A.startsWithKeyframe():!0,m=A.compositionTimeOffset(0);if(C==="text"){this.logger.warn("Skipping unexpected text fragment");return}if(!e){this.logger.warn("Skipping fragment with no codec");return}const y=this.trackContexts.get(C);if(!y)throw RB(C);y.state==="initialized"&&t&&(y.mimeType=t,y.initSegments.set(g,B,o));const f={fragmented:!0,type:C,data:Q,initData:o,timestamp:a,duration:h,timescale:c,channelId:g,renditionId:B,isSync:l,codec:e,fragment:A,compositionTimeOffset:m};this.onCodedSample(f)});I(this,"onCodedSample",A=>{if(A.duration===0)return;const t=this.trackContexts.get(A.type);if(!t)throw RB(A.type,A.renditionId);if(!(!t.hasFirstSync&&!A.isSync)){if(this.hasAddedInitialPosterFrame&&A.isSync&&A.type==="video"){this.hasAddedInitialPosterFrame=!1;const e=D({},A);"fragment"in e?(e.fragment=e.fragment.clone(),e.fragment.updateBaseMediaDecodeTime(0),e.data=e.fragment.rawBytes()):e.timestamp=0,t.pendingSamples.push(e)}t.hasFirstSync=!0,t.pendingSamples.push(A),t.state!=="uninitialized"&&(t.isWorkingOnPendingSamples||lu(t,this.append,this.maxChunkSize).catch(e=>{if(t.isWorkingOnPendingSamples=!1,e instanceof Error){if(this.logger.error("append failed",{message:e.message,name:e.name}),e instanceof DOMException&&e.code===DOMException.QUOTA_EXCEEDED_ERR){if(t.consecutiveQuotaExceededErrorCount>=this.minConsecutiveErrorsBeforeEmit){const g=Pn(!1,e,t.consecutiveQuotaExceededErrorCount,A.type);this.emitter.emit("error",g)}}else{const g=Pn(!1,e,t.consecutiveQuotaExceededErrorCount,A.type);this.emitter.emit("error",g)}this.mediaElement.error&&this.onSourceEnded()}}))}});I(this,"onSourceOpen",()=>{this.logger.debug("source opened"),this.sourceOpenEndTime=Date.now(),this.pendingTracksToAddSourceBuffers&&(this.setSourceBuffers(this.pendingTracksToAddSourceBuffers),this.pendingTracksToAddSourceBuffers=void 0)});I(this,"onSourceEnded",()=>{const{error:A}=this.mediaElement;if(A){const t=/AUDIO_RENDERER/.test(A.message)||!this.autoRecoverFromMediaErrors,e=nc(t,A);if(this.logger.error("MediaElement error",{error:e}),this.emitter.emit("error",e),!e.isFatal()){this.logger.info("Re-opening MediaSource"),this.emitter.emit("recovered from media error",{error:e,count:this.recoveredFromErrorCount}),this.recoveredFromErrorCount++;const g=!this.mediaElement.paused,B=[];this.trackContexts.forEach((C,Q)=>{C.state==="initialized"&&B.push({type:Q,mimeType:C.mimeType,codec:C.codec})}),this.sourceOpenStartTime=Date.now(),this.pendingTracksToAddSourceBuffers=B,this.mediaElement.src="",this.setTrackContexts(this.trackContexts),this.mediaSource.attach(this.mediaElement),g&&this.mediaElement.play().catch(F)}}this.logger.debug("source ended")});this.logger=A,this.mediaElement=e,this.emitter=t}};I(gQ,"create",(A,t,e)=>{const g=new gQ(A,t,e);return g.setTrackContexts(),g.mediaSource.on("source ended",g.onSourceEnded),g.mediaSource.on("source open",g.onSourceOpen),g.mediaSource.attach(e),g});let fo=gQ;const iE=(i,A)=>{var Q;const t=i.renditionId!==A.renditionId,e=i.channelId!==A.channelId,g=((Q=i.timestamp)!=null?Q:0)>A.timestamp,B=i.type==="video"&&A.type==="video"&&"levelIdc"in i&&"levelIdc"in A&&i.levelIdc!==A.levelIdc;let C=!1;return i.type==="video"&&A.type==="video"&&"width"in i&&"width"in A&&(C=A.width!==i.width||A.height!==i.height),e||t||g||C||B},lu=(i,A,t)=>r(null,null,function*(){for(i.isWorkingOnPendingSamples=!0;i.pendingSamples.length>0;){const e=[];let g=0;for(let Q=0;Q<i.pendingSamples.length;Q++){g=Q;const o=i.pendingSamples[Q],a=i.pendingSamples[Q+1];if(o&&(e.push(o),a)){if(iE(o,a))break;const c=(o.timestamp+o.duration)/o.timescale;if(a.timestamp/a.timescale-c>.1)break}if(Q===t-1)break}const B=e[0];if(!B)break;const C=i.previousSample?iE(i.previousSample,B):!0;yield A(e,C),i.pendingSamples=i.pendingSamples.slice(g+1),i.previousSample=e[e.length-1]}i.isWorkingOnPendingSamples=!1}),sQ=class sQ{constructor(A,t){I(this,"logger");I(this,"emitter");I(this,"element");I(this,"pictureInPictureWindow");I(this,"unload",()=>{this.emitter.off("add picture in picture listener",this.onEnablePictureInPicture)});I(this,"onEnablePictureInPicture",A=>{this.element=A.element,A.element.addEventListener("leavepictureinpicture",()=>{this.pictureInPictureWindow=void 0,this.logger.debug("Leave picture in picture"),this.emitter.emit("exit picture in picture")}),A.element.addEventListener("enterpictureinpicture",t=>{this.pictureInPictureWindow=t.pictureInPictureWindow,this.logger.debug("Enter picture in picture"),this.emitter.emit("enter picture in picture",this)}),A.element.autopictureinpicture=!0});I(this,"getPictureInPictureSize",()=>this.pictureInPictureWindow);I(this,"isPictureInPictureActive",()=>this.isWebkitPresentationModeActive()||this.isStandardPictureInPictureActive());I(this,"isPictureInPictureSupported",()=>this.isWebkitPresentationModeSupported()||this.isStandardPictureInPictureSupported());I(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"))));I(this,"exitPictureInPicture",()=>this.isStandardPictureInPictureSupported()?this.exitStandardPictureInPicture():this.isWebkitPresentationModeSupported()?this.requestWebkitPresentationMode("inline"):Promise.reject(new Error("Picture in picture is not supported")));I(this,"getStatistics",()=>({isPictureInPictureActive:this.isPictureInPictureActive()}));I(this,"requestStandardPictureInPicture",()=>r(this,null,function*(){return yield this.element.requestPictureInPicture()}));I(this,"exitStandardPictureInPicture",()=>r(null,null,function*(){return yield document.exitPictureInPicture()}));I(this,"isStandardPictureInPictureSupported",()=>!!this.element&&!!this.element.requestPictureInPicture&&!!document.pictureInPictureEnabled);I(this,"isStandardPictureInPictureActive",()=>!!this.element&&!!document.pictureInPictureElement);I(this,"isWebkitPresentationModeActive",()=>!!this.element&&this.element.webkitPresentationMode==="picture-in-picture");I(this,"requestWebkitPresentationMode",A=>r(this,null,function*(){return this.element.webkitSetPresentationMode(A),Promise.resolve()}));I(this,"isWebkitPresentationModeSupported",()=>!!this.element&&!!this.element.webkitSetPresentationMode);this.emitter=A,this.logger=t,this.emitter.on("add picture in picture listener",this.onEnablePictureInPicture)}};I(sQ,"create",(A,t)=>new sQ(A,t));let po=sQ;const BQ=class BQ{constructor(A,t,e,g){I(this,"emitter");I(this,"logger");I(this,"clockSource");I(this,"state","buffering");I(this,"bufferFullness",0);I(this,"targetBufferTime");I(this,"lastBufferStateEvent","drained");I(this,"firstFrameTime");I(this,"currentTimeIsInRange",!1);I(this,"needsInputForAudioCount",0);I(this,"needsInputForVideoCount",0);I(this,"unload",()=>{this.emitter.off("buffer state",this.onBufferedStateChanged),this.emitter.off("needs user input",this.onNeedsUserInput)});I(this,"setTargetBufferTime",A=>{this.targetBufferTime=A,this.emitter.emit("target buffer time",A)});I(this,"getTargetBufferTime",()=>this.targetBufferTime);I(this,"getBufferFullness",()=>this.bufferFullness);I(this,"getLastBufferStateEvent",()=>this.lastBufferStateEvent);I(this,"getState",()=>this.state);I(this,"getFirstFrameTime",()=>this.firstFrameTime);I(this,"getStatistics",()=>({bufferTime:this.targetBufferTime,needsInputForAudioCount:this.needsInputForAudioCount,needsInputForVideoCount:this.needsInputForVideoCount}));I(this,"onBufferedStateChanged",({buffered:A,isPaused:t})=>{const e=this.clockSource.currentTime,g=A.some(c=>c.start<e&&e<c.end),B=A[A.length-1],C=B?B.end-B.start>=this.targetBufferTime:!1,Q=B?Math.max(0,B.end-e)/this.targetBufferTime:0,o=t?"paused":g?"playing":"buffering",a=this.state;this.currentTimeIsInRange!==g&&!g?(this.lastBufferStateEvent="drained",this.emitter.emit("buffer state event",this.lastBufferStateEvent)):g&&C&&this.lastBufferStateEvent==="drained"&&(this.lastBufferStateEvent="filled",this.emitter.emit("buffer state event",this.lastBufferStateEvent)),o==="playing"&&!this.firstFrameTime&&(this.firstFrameTime=Date.now()),this.currentTimeIsInRange=g,this.state=o,this.bufferFullness=g?Q:0,a!==o&&this.emitter.emit("playback state",o),this.emitter.emit("buffer fullness",this.bufferFullness)});I(this,"onNeedsUserInput",({forAudio:A,forVideo:t})=>{A&&this.needsInputForAudioCount++,t&&this.needsInputForVideoCount++});this.emitter=A,this.logger=t,this.clockSource=e,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)}};I(BQ,"create",(A,t,e,g)=>new BQ(A,t,e,g));let Fo=BQ;const Go=()=>({upgradesFromLevel:[],downgradesFromLevel:[],bufferingRanges:[],activeRanges:[],decodeRate:Number.MAX_SAFE_INTEGER}),uu=()=>({levels:{},levelDowngrades:[],levelUpgrades:[],bufferFullness:0,general:Go()}),CQ=class CQ{constructor(A,t,e){I(this,"minBufferFullnessLengthForRegression",6);I(this,"logger");I(this,"emitter");I(this,"timers",NA.create());I(this,"metrics",uu());I(this,"bufferFullness",new W(30));I(this,"bufferFullnessRegression");I(this,"currentLevel");I(this,"isSuspended",!1);I(this,"_fatalQosCount",0);I(this,"targetBufferTime",0);I(this,"renditionLevelSource");I(this,"qualityIndexOrder",[]);I(this,"hasAsserted",!1);I(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)});I(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()});I(this,"suspend",()=>{this.isSuspended=!0,this.timers.unload(),this.stopBuffering(),this.unsetActive()});I(this,"unsuspend",()=>{this.isSuspended=!1,this.currentLevel&&this.setActive()});I(this,"fatalQosGraceTime",()=>1e4*(this.fatalQosCount+1));I(this,"incrementFatalQosCount",()=>{this._fatalQosCount++});I(this,"getMetrics",()=>this.metrics);I(this,"getLevelStats",A=>{var e,g,B,C;const t=((g=(e=A.video)==null?void 0:e.bitRate)!=null?g:0)+((C=(B=A.audio)==null?void 0:B.bitRate)!=null?C:0);return this.metrics.levels[t]});I(this,"getBufferFullnessRegression",()=>this.bufferFullnessRegression);I(this,"getTargetBufferTime",()=>this.targetBufferTime);I(this,"activeRatios",()=>{const A=new Map,t=_i(this.metrics.general.activeRanges);if(Object.entries(this.metrics.levels).forEach(([e,g])=>{var o;const B=parseInt(e,10),C=t?_i(g.activeRanges)/t:0,Q=this.getQualityIndex(B).toString();A.set(Q,((o=A.get(Q))!=null?o:0)+C)}),!this.hasAsserted){const e=A.size?Math.abs(Array.from(A.values()).reduce((g,B)=>g+B,0)-1)<=.02:!0;e||(this.hasAsserted=!0,console.assert(e,`Active ratios should be close to 1 - actual: ${Array.from(A.values()).reduce((g,B)=>g+B,0)}`))}return A});I(this,"bufferingRatios",()=>{const A=new Map,t=_i(this.metrics.general.bufferingRanges);if(Object.entries(this.metrics.levels).forEach(([e,g])=>{var o;const B=parseInt(e,10),C=t?_i(g.bufferingRanges)/t:0,Q=this.getQualityIndex(B).toString();A.set(Q,((o=A.get(Q))!=null?o:0)+C)}),!this.hasAsserted){const e=Array.from(A.values()).reduce((g,B)=>g+B,0)<=1;e||(this.hasAsserted=!0,console.assert(e,`Buffering ratios should be less than 1 - actual: ${Array.from(A.values()).reduce((g,B)=>g+B,0)}`))}return A});I(this,"bufferingEventsLast",A=>this.metrics.general.bufferingRanges.filter(t=>t.start>=Date.now()-A).length);I(this,"timeSpentBufferingLast",A=>yn(this.metrics.general.bufferingRanges,A));I(this,"timeSpentActiveLast",A=>yn(this.metrics.general.activeRanges,A));I(this,"timeSpentPlayingInAtLeastLevelRatio",A=>{var o,a,c,h;const t=this.timeSpentBuffering(),e=this.timeActive(),g=this.bufferingRatios(),B=this.activeRatios(),C=((a=(o=A.video)==null?void 0:o.bitRate)!=null?a:0)+((h=(c=A.audio)==null?void 0:c.bitRate)!=null?h:0),Q=t/e;return Object.keys(this.metrics.levels).map(l=>parseInt(l,10)).filter(l=>l>=C).reduce((l,m)=>{var f,k;const y=this.getQualityIndex(m).toString();return((f=B.get(y))!=null?f:0)-((k=g.get(y))!=null?k:0)*Q+l},0)});I(this,"timeSpentBuffering",()=>_i(this.metrics.general.bufferingRanges));I(this,"timeActive",()=>_i(this.metrics.general.activeRanges));I(this,"getStatistics",()=>({timeSpentBuffering:this.timeSpentBuffering(),bufferingEventsCount:this.metrics.general.bufferingRanges.length,timeSpentRatio:[...this.activeRatios()].reduce((A,[t,e])=>(A[t]=e,A),{}),fatalQosCount:this.fatalQosCount}));I(this,"onRenditionLevelChanged",A=>{var B,C,Q,o,a,c,h,l,m,y,f,k,q,U;const t=((Q=(C=(B=A.from)==null?void 0:B.video)==null?void 0:C.bitRate)!=null?Q:0)+((c=(a=(o=A.from)==null?void 0:o.audio)==null?void 0:a.bitRate)!=null?c:0),e=((m=(l=(h=A.to)==null?void 0:h.video)==null?void 0:l.bitRate)!=null?m:0)+((k=(f=(y=A.to)==null?void 0:y.audio)==null?void 0:f.bitRate)!=null?k:0);this.logger.info("rendition level changed",{fromLevel:t,toLevel:e}),this.metrics.general.activeRanges.length===0&&this.setActive(),A.from&&A.to&&(t<e?this.metrics.general.upgradesFromLevel.push(Date.now()):this.metrics.general.downgradesFromLevel.push(Date.now()));let g=!1;if(A.from){const H=(q=this.metrics.levels[t])!=null?q:Go();t<e?H.upgradesFromLevel.push(Date.now()):H.downgradesFromLevel.push(Date.now()),Ze(H.activeRanges);const T=H.bufferingRanges[H.bufferingRanges.length-1];g=!!T&&!T.end,Ze(H.bufferingRanges),this.metrics.levels[t]=H}if(A.to){const H=(U=this.metrics.levels[e])!=null?U:Go();zi(H.activeRanges),g&&zi(H.bufferingRanges),this.metrics.levels[e]=H,this.currentLevel=e}});I(this,"onBufferFullness",A=>{this.bufferFullness.push(A),this.metrics.bufferFullness=A,this.bufferFullness.items().length>=this.minBufferFullnessLengthForRegression&&(this.bufferFullnessRegression=this.calculateLinearRegression())});I(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}});I(this,"onVideoDecodeRate",A=>{var e;if(this.metrics.general.decodeRate=A,!this.currentLevel)return;const t=this.metrics.levels[(e=this.currentLevel)!=null?e:0];t&&(t.decodeRate=A)});I(this,"onTargetBufferTime",A=>{this.targetBufferTime=A});I(this,"calculateLinearRegression",()=>Wr(this.bufferFullness.items().map((A,t)=>({x:t,y:A}))));I(this,"stopBuffering",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Ze(A.bufferingRanges)}Ze(this.metrics.general.bufferingRanges)});I(this,"startBuffering",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&zi(A.bufferingRanges)}zi(this.metrics.general.bufferingRanges)});I(this,"unsetActive",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Ze(A.activeRanges)}Ze(this.metrics.general.activeRanges)});I(this,"getQualityIndex",A=>{var e,g;if(!this.qualityIndexOrder.length){const C=((g=(e=this.renditionLevelSource)==null?void 0:e.getRenditionLevels())!=null?g:[]).map(Q=>{var o,a,c,h;return((a=(o=Q.video)==null?void 0:o.bitRate)!=null?a:0)+((h=(c=Q.audio)==null?void 0:c.bitRate)!=null?h:0)}).filter(Q=>Q>0);this.qualityIndexOrder=[...new Set(C)].sort((Q,o)=>o-Q)}let t=this.qualityIndexOrder.indexOf(A);return t===-1&&(this.qualityIndexOrder.push(A),this.qualityIndexOrder.sort((B,C)=>C-B),t=this.qualityIndexOrder.indexOf(A)),t});this.logger=t,this.emitter=A,this.renditionLevelSource=e}get fatalQosCount(){return this._fatalQosCount}setActive(){if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&zi(A.activeRanges)}zi(this.metrics.general.activeRanges)}};I(CQ,"create",(A,t,e)=>new CQ(A,t,e));let ko=CQ;const QQ=class QQ{constructor(A,t){I(this,"renditions",new Map);I(this,"renditionLevels",[]);I(this,"languages",[]);I(this,"emitter");I(this,"subscriptionSource");I(this,"renditionLevelChangeCount",0);I(this,"unload",()=>{this.emitter.off("renditions",this.onRenditions),this.emitter.off("subscription changed",this.onSubscriptionChanged)});I(this,"getRenditionLevels",A=>A?this.createRenditionLevels(A):this.renditionLevels);I(this,"getRenditionLevel",A=>{var Q;const t=A!=null?A:this.getCurrentSubscription(),e=A?this.createRenditionLevels(A):this.renditionLevels;if(!t.video)return e.length?e[0]:void 0;const g=t.video.bitRate||Number.MAX_SAFE_INTEGER,B=t.video.width||Number.MAX_SAFE_INTEGER,C=t.video.height||Number.MAX_SAFE_INTEGER;return(Q=e.filter(o=>o.video&&t.video?o.video.bitRate<=g&&o.video.width<=B&&o.video.height<=C:!0).pop())!=null?Q:e[0]});I(this,"setRenditions",(A,t)=>{this.renditions.set(A,t)});I(this,"getLanguages",()=>this.languages);I(this,"getVideoRendition",(A,t=this.getCurrentSubscription().channelId)=>{const e=this.getRendition(A,t);if(e&&Xe(e))return e});I(this,"getAudioRenditions",A=>{const t=this.renditions.get(A);return t==null?void 0:t.filter(g=>je(g))});I(this,"getVideoRenditions",A=>{const t=this.renditions.get(A);return t==null?void 0:t.filter(g=>Xe(g))});I(this,"getAudioRendition",(A,t=this.getCurrentSubscription().channelId)=>{const e=this.getRendition(A,t);if(e&&je(e))return e});I(this,"getRendition",(A,t=this.getCurrentSubscription().channelId)=>{var e;return(e=this.renditions.get(t))==null?void 0:e.find(g=>g.id===A)});I(this,"getStatistics",()=>{var t,e,g,B,C,Q,o,a,c,h;const A=this.getRenditionLevel();return{videoCodec:(t=A==null?void 0:A.video)==null?void 0:t.codec,audioCodec:(e=A==null?void 0:A.audio)==null?void 0:e.codec,videoRenditionId:(g=A==null?void 0:A.video)==null?void 0:g.id,audioRenditionId:(B=A==null?void 0:A.audio)==null?void 0:B.id,videoWidth:(C=A==null?void 0:A.video)==null?void 0:C.width,videoHeight:(Q=A==null?void 0:A.video)==null?void 0:Q.height,expectedVideoBitRate:(o=A==null?void 0:A.video)==null?void 0:o.bitRate,expectedAudioBitRate:(a=A==null?void 0:A.audio)==null?void 0:a.bitRate,frameRate:(c=A==null?void 0:A.video)==null?void 0:c.frameRate,language:(h=A==null?void 0:A.audio)==null?void 0:h.language,renditionLevelChangeCount:this.renditionLevelChangeCount}});I(this,"onRenditions",A=>{const t=this.subscriptionSource.getCurrentSubscription();this.renditions.set(A.channelId,A.renditions),this.updateRenditionLevels({to:t,from:t})});I(this,"onSubscriptionChanged",A=>{this.updateRenditionLevels(A)});I(this,"updateRenditionLevels",({to:A,from:t})=>{var a;const{channelId:e,initiator:g}=A,B=this.getRenditionLevel(t),C=new Set;((a=this.renditions.get(e))!=null?a:[]).filter(c=>c.codec!=="webvtt").forEach(c=>c.language?C.add(c.language):void 0),this.languages=Array.from(C),this.renditionLevels=this.createRenditionLevels(A);const o=this.getRenditionLevel(A);Ve(B,o)||(this.renditionLevelChangeCount++,this.emitter.emit("rendition level changed",{to:o,from:B,reason:g?"manual":"abr"}))});I(this,"createRenditionLevels",A=>{var c;const{video:t,audio:e,channelId:g}=A,B=(c=this.renditions.get(g))!=null?c:[],C=B.filter(Xe).filter(h=>t&&h.codec===t.codec),Q=B.filter(je).filter(h=>e&&h.codec===e.codec&&h.language===e.language),o=Math.max(C.length,Q.length),a=[];for(let h=0;h<o;h++){const l=C[Math.min(C.length-1,h)],m=Q[Math.min(Q.length-1,h)];a.push({audio:m,video:l})}return a});I(this,"getCurrentSubscription",()=>this.subscriptionSource.getCurrentSubscription());this.subscriptionSource=t,this.emitter=A,this.emitter.on("renditions",this.onRenditions),this.emitter.on("subscription changed",this.onSubscriptionChanged)}};I(QQ,"create",(A,t)=>new QQ(A,t));let Ro=QQ;const Rg=i=>JSON.parse(JSON.stringify(i)),wu=1e4,oQ=class oQ{constructor(A,t,e){I(this,"logger");I(this,"timers",new NA);I(this,"emitter");I(this,"targetSubscription");I(this,"currentSubscription");I(this,"_isSwitchingSubscription",!1);I(this,"pendingSubscriptionTimeoutId");I(this,"burstMs",0);I(this,"unload",()=>{this.logger.debug("Unloading module..."),this.timers.unload(),this.emitter.off("subscription changed",this.onSubscriptionChanged),this.logger.debug("Unloaded module")});I(this,"isSwitchingSubscription",()=>this._isSwitchingSubscription);I(this,"getTargetSubscription",()=>this.targetSubscription);I(this,"getCurrentSubscription",()=>this.currentSubscription);I(this,"enableBurst",A=>{this.burstMs=A});I(this,"setSize",A=>{this.targetSubscription.video.width=A.width,this.targetSubscription.video.height=A.height,this.scheduleSubscriptionChange()});I(this,"setVideoConstraint",A=>{this.targetSubscription.video=A,this.scheduleSubscriptionChange()});I(this,"setAudioConstraint",A=>{this.targetSubscription.audio=A,this.scheduleSubscriptionChange()});I(this,"setVideoBitRate",A=>{this.targetSubscription.video.bitRate=A,this.scheduleSubscriptionChange()});I(this,"setAudioBitRate",A=>{this.targetSubscription.audio.bitRate=A,this.scheduleSubscriptionChange()});I(this,"setChannelId",A=>{this.targetSubscription.channelId=A,this.scheduleSubscriptionChange()});I(this,"setLanguage",A=>{this.targetSubscription.audio.language=A,this.scheduleSubscriptionChange()});I(this,"setVideoCodec",A=>{this.targetSubscription.video.codec=A,this.scheduleSubscriptionChange()});I(this,"setAudioCodec",A=>{this.targetSubscription.audio.codec=A,this.scheduleSubscriptionChange()});I(this,"setBurst",A=>{A?this.targetSubscription.burstMs=A:delete this.targetSubscription.burstMs});I(this,"isNewSubscription",()=>{const A=["burstMs","meta","initiator","channelGroupId"];return!Ve(Sn(this.currentSubscription,A),Sn(this.targetSubscription,A))});I(this,"onSubscriptionChanged",({to:A,reset:t})=>{this.logger.debug("onSubscriptionChanged",{to:A,reset:t}),t?this.targetSubscription=Rg(this.currentSubscription):this.currentSubscription=Rg(A),this._isSwitchingSubscription=this.isNewSubscription()});I(this,"scheduleSubscriptionChange",()=>{this.targetSubscription=Rg(this.targetSubscription),this._isSwitchingSubscription=this.isNewSubscription();const A=this.currentSubscription.channelId,t=this.targetSubscription.channelId,e=A!==t;this._isSwitchingSubscription&&(e&&this.burstMs?this.setBurst(this.burstMs):this.setBurst(0),this.pendingSubscriptionTimeoutId&&(this.timers.clearTimeout(this.pendingSubscriptionTimeoutId),this.pendingSubscriptionTimeoutId=void 0),e&&this.timers.setTimeout(()=>{this.currentSubscription.channelId===A&&this.targetSubscription.channelId===t&&(this.logger.warn("Channel switch timeout",t),this.targetSubscription=Rg(this.currentSubscription),this.emitter.emit("channel switch timeout",t))},wu),this.pendingSubscriptionTimeoutId=this.timers.setTimeout(()=>this.emitter.emit("send signal",{type:"subscribe",subscription:this.getTargetSubscription()}),0))});this.logger=A,this.targetSubscription=t,this.currentSubscription=Rg(t),this.emitter=e,this.emitter.on("subscription changed",this.onSubscriptionChanged)}};I(oQ,"create",(A,t,e)=>new oQ(A,e,t));let Uo=oQ;const IE=5e3,Du=()=>un()||GB()||vr(),gE=()=>Du()?100:0,sE=i=>A=>A>i,nQ=class nQ{constructor(A,t,e,g,B){I(this,"emitter");I(this,"logger");I(this,"playbackSource");I(this,"bufferSource");I(this,"keyframeTimestamps",new W(10));I(this,"lastSeekTime",Date.now());I(this,"seekCooldownTime",1e3);I(this,"seekTimeoutTime",5e3);I(this,"seekKeyframeOvershoot",50);I(this,"syncMaxBehind");I(this,"syncMaxBehindMultiplierStep",1);I(this,"syncMaxBehindIncreaseEvery",2);I(this,"syncMaxBehindMaximumAllowed",2e3);I(this,"syncMaxBehindMultiplier",1);I(this,"timeshiftOnAudio",!1);I(this,"syncMaxAhead",150);I(this,"timeshiftSync",{enabled:!1,maxBehind:50,multiplier:1,maxBehindAllowed:600,overshoot:gE(),minOvershootAllowed:gE(),maxOvershootAllowed:500});I(this,"maxTimeSyncDifferenceTolerance",150);I(this,"timers",NA.create());I(this,"rtt",0);I(this,"channelSyncInfo",new Map);I(this,"driftAdjustmentsCount",0);I(this,"timeshiftDriftAdjustmentCount",0);I(this,"driftAdjustments",[]);I(this,"timeShiftAdjustments",[]);I(this,"timestampOffset");I(this,"currentChannelId");I(this,"highestSeenTimestamps",new Map);I(this,"isSuspended",!1);I(this,"isSyncAdjustmentActivated",!1);I(this,"load",()=>{this.timers.setInterval(this.onSync,100)});I(this,"unload",()=>{this.logger.debug("Unloading module..."),this.emitter.off("rtt",this.updateRtt),this.timers.unload(),this.logger.debug("Unloaded module")});I(this,"suspend",()=>{this.isSuspended=!0});I(this,"unsuspend",()=>{this.resetSyncState(),this.isSuspended=!1});I(this,"deactivateSyncAdjustments",()=>{this.isSyncAdjustmentActivated=!1});I(this,"activateSyncAdjustments",()=>{this.tryApplySyncInfo(0),this.lastSeekTime=Date.now(),this.isSyncAdjustmentActivated=!0});I(this,"reset",()=>{this.logger.info("Reset sync state"),this.currentChannelId=void 0,this.timestampOffset=void 0,this.resetSyncState(),this.highestSeenTimestamps.clear()});I(this,"getTimeshiftOffset",()=>{var A;return(A=this.timestampOffset)!=null?A:0});I(this,"getCurrentChannelId",()=>this.currentChannelId);I(this,"resetSyncState",()=>{this.timeshiftSync.multiplier=1,this.syncMaxBehindMultiplier=1,this.driftAdjustments=[],this.timeShiftAdjustments=[]});I(this,"getLiveEdgeTime",A=>{const t=this.channelSyncInfo.get(A);if(!t)return;const e=Date.now()-t.localTimestamp;return t.timestamp+e});I(this,"getLiveEdgeTimeLatencyAdjusted",A=>{const t=this.getLiveEdgeTime(A);if(t)return t+this.rtt/2});I(this,"getWallclockTime",A=>{const t=this.channelSyncInfo.get(A);if(!t)return;const e=Date.now()-t.localTimestamp;return t.wallclockTime+e});I(this,"getWallclockTimeLatencyAdjusted",A=>{const t=this.getWallclockTime(A);if(t)return t+this.rtt/2});I(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-IE);const t=A.type==="video"&&A.isSync;if(this.currentChannelId!==A.channelId){let B=Number.MAX_SAFE_INTEGER;console.assert(this.highestSeenTimestamps.size!==0,"no known timestamps"),this.highestSeenTimestamps.forEach(Q=>{B=Math.min(B,Q)});const C=A.timestamp/A.timescale*1e3;this.currentChannelId=A.channelId,this.timestampOffset=C-B}else(t||this.timeshiftOnAudio)&&this.tryTimeshiftSync();const e=this.timestampOffset*A.timescale/1e3;return A.timestamp-=e,t&&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});I(this,"processFragment",(A,t)=>{var C;this.currentChannelId||(this.currentChannelId=A);const e=t.mediaType();if(!e)throw new Error("Fragment must have a media type");this.timestampOffset||(this.timestampOffset=t.baseMediaDecodeTime()/t.timescale()*1e3-IE);const g=t.mediaType()==="video"&&t.startsWithKeyframe();this.currentChannelId!==A?(console.assert(this.highestSeenTimestamps.size!==0,"no known timestamps"),this.highestSeenTimestamps.forEach(Q=>{}),this.currentChannelId=A):(g||this.timeshiftOnAudio)&&this.tryTimeshiftSync();const B=this.timestampOffset*t.timescale()/1e3;return t.updateBaseMediaDecodeTime(t.baseMediaDecodeTime()-B),g&&this.keyframeTimestamps.push(t.baseMediaDecodeTime()/t.timescale()*1e3),this.highestSeenTimestamps.set(e,Math.max((C=this.highestSeenTimestamps.get(e))!=null?C:0,t.baseMediaDecodeTime()/t.timescale()*1e3)),t});I(this,"getStatistics",()=>({drift:this.drift,driftAdjustmentCount:this.driftAdjustmentsCount,timeshiftDriftAdjustmentCount:this.timeshiftDriftAdjustmentCount,seekTime:this.playbackSource.seekTime}));I(this,"updateRtt",A=>void(this.rtt=A));I(this,"isPlaybackSourceReadyToSeek",()=>!this.isSeeking()&&this.isSeekCooldownExpired()&&this.isSyncAdjustmentActivated);I(this,"isSeeking",()=>this.playbackSource.isSeeking?!this.isSeekTimeoutExpired():!1);I(this,"isAllowedToSync",()=>this.isPlaybackSourceReadyToSeek()&&!!this.currentChannelId&&!this.isSuspended&&!this.playbackSource.isPaused);I(this,"isSeekCooldownExpired",()=>Date.now()-this.lastSeekTime>this.seekCooldownTime);I(this,"isSeekTimeoutExpired",()=>Date.now()-this.lastSeekTime>this.seekTimeoutTime);I(this,"currentTimeshiftMaxBehind",()=>Math.min(this.timeshiftSync.maxBehind*this.timeshiftSync.multiplier,this.timeshiftSync.maxBehindAllowed));I(this,"currentSyncMaxBehind",()=>Math.min(this.syncMaxBehindMultiplier*this.syncMaxBehind,this.syncMaxBehindMaximumAllowed));I(this,"currentSyncMaxAhead",()=>this.playbackSource.seekTime>500?Math.max(this.syncMaxAhead*this.syncMaxBehindMultiplier,300):this.syncMaxAhead);I(this,"tryTimeshiftSync",()=>{var B;if(!this.timeshiftSync.enabled||!this.isAllowedToSync())return;const A=(B=this.drift)!=null?B:0;if(A>=this.syncMaxBehind)return;if(A<this.currentTimeshiftMaxBehind()){this.timeshiftSync.overshoot=0;return}if(!this.timestampOffset)return;const t=Date.now()-this.seekTimeoutTime*this.timeshiftSync.multiplier,e=this.timeShiftAdjustments.filter(sE(t)).length;if(e&&this.timeshiftSync.multiplier>2)return this.logger.debug("Too many diff timeShifts within sliding window",{timeShiftsCooldownMs:t,timeShiftsWithinCooldownTime:e}),!1;const g=A+this.timeshiftSync.overshoot;this.logger.info("Adjusting for drift using timeshift",{drift:A,syncAmount:g,currentTime:this.playbackSource.currentTime,rtt:this.rtt,overshoot:this.timeshiftSync.overshoot}),this.timestampOffset+=g,this.lastSeekTime=Date.now(),!this.playbackSource.isPaused&&(this.timeShiftAdjustments.push(this.lastSeekTime),this.timeshiftDriftAdjustmentCount++,this.timeshiftSync.multiplier++,this.timeshiftSync.overshoot=Math.max(this.timeshiftSync.minOvershootAllowed,Math.min(this.timeshiftSync.multiplier*A/2,this.timeshiftSync.maxOvershootAllowed)))});I(this,"onSync",()=>{var Q;if(!this.isAllowedToSync())return;const A=(Q=this.drift)!=null?Q:0;if(A<0&&-A<this.currentSyncMaxAhead()||A>0&&A<this.currentSyncMaxBehind()||Math.abs(A)<1||!this.isSeekCooldownExpired())return;const t=Date.now()-this.seekTimeoutTime*this.syncMaxBehindMultiplier,e=this.driftAdjustments.filter(sE(t)).length;if(e&&this.syncMaxBehindMultiplier>2)return this.logger.debug("Too many diff adjustments within sliding window",{adjustmentsCooldownMs:t,adjustmentsWithinCooldownTime:e}),!1;const g=this.playbackSource.seekTime,B=this.playbackSource.currentTime+A,C=this.findKeyframeCloseToTimestamp(B);if(C||this.keyframeTimestamps.isEmpty()){const o=C?C+this.seekKeyframeOvershoot:B;if(this.logger.info("Adjusting for drift using seek",{drift:A,currentTime:this.playbackSource.currentTime,targetCurrentTime:o,seekTime:g,rtt:this.rtt}),this.lastSeekTime=Date.now(),this.driftAdjustments.push(this.lastSeekTime),this.driftAdjustmentsCount++,this.playbackSource.currentTime=o+g,this.timeshiftSync.overshoot=Math.max(this.timeshiftSync.minOvershootAllowed,this.timeshiftSync.overshoot/2),this.driftAdjustmentsCount%this.syncMaxBehindIncreaseEvery===0&&!this.playbackSource.isPaused){const a=this.currentSyncMaxBehind;this.syncMaxBehindMultiplier+=this.syncMaxBehindMultiplierStep,a!==this.currentSyncMaxBehind&&this.logger.info("Increasing max drift behind allowed",{from:a,to:this.currentSyncMaxBehind})}}});I(this,"findKeyframeCloseToTimestamp",A=>{const t=this.keyframeTimestamps.items();for(const e of t)if(e>=A&&e<=A+200)return e});this.logger=t,this.emitter=A,this.playbackSource=e,this.bufferSource=g,this.timeshiftSync.enabled=B,this.syncMaxBehind=this.timeshiftSync.enabled?1e3:200,this.emitter.on("rtt",this.updateRtt)}updateChannelSyncInfo(A,t){const e=Date.now(),g=this.channelSyncInfo.get(A),B=this.getLiveEdgeTime(A);if(this.isSuspended)return;if(!g||!B){this.logger.info("Initial timing info",{syncInfo:t}),this.channelSyncInfo.set(A,V(D({},t),{localTimestamp:e,timeDifferences:new W(12)}));return}const C=t.wallclockTime-g.wallclockTime,Q=t.timestamp-g.timestamp,o=e-g.localTimestamp,a=Q-o;if(g.timeDifferences.push(a),this.logger.debug("Timing info",{rtt:this.rtt,channelId:A,syncInfo:t,localTimestamp:e,diffFromEstimated:a,timestampDelta:Q,wallclockDelta:C,localWallclockDelta:o}),Math.abs(a)>=this.bufferSource.getTargetBufferTime()*2){this.logger.info("Resetting sync info",{diffFromEstimated:a}),this.channelSyncInfo.set(A,V(D({},t),{localTimestamp:e,timeDifferences:new W(g.timeDifferences.maxSize+1)})),this.currentChannelId&&this.currentChannelId===A&&(this.reset(),this.emitter.emit("channel reset"));return}g.timeDifferences.isFull()&&this.tryApplySyncInfo(this.maxTimeSyncDifferenceTolerance)}tryApplySyncInfo(A){const t=this.getCurrentChannelId();if(!t)return;const e=this.channelSyncInfo.get(t);if(!e)return;const g=Wt(e.timeDifferences.items());Math.abs(g)>A&&(this.logger.info("Adjusting sync info",{averageDifference:g}),e.timestamp+=g,e.timeDifferences.clear())}get serverCurrentTime(){return this.channelCurrentTime-this.getTimeshiftOffset()}get channelCurrentTime(){const A=this.getCurrentChannelId();if(!A)return 0;const t=this.getLiveEdgeTime(A);return t?t-this.bufferSource.getTargetBufferTime():0}get drift(){return this.serverCurrentTime-this.playbackSource.currentTime}};I(nQ,"create",(A,t,e,g,B)=>new nQ(A,t,e,g,B));let No=nQ;const mu={enabled:!0,interval:3e4,includeErrors:!0,includeEvents:!0,includeStats:!0,maxRetries:10,maxErrorReports:50,maxEvents:50},bo=(i,A)=>V(D({},A),{type:i,timestamp:new Date().toISOString(),discriminator:"web"}),aQ=class aQ{constructor(A,t,e,g){I(this,"logger");I(this,"timers",new NA);I(this,"emitter");I(this,"options");I(this,"parentContext");I(this,"unsentLines",new W(100));I(this,"retries",0);I(this,"errorCount",0);I(this,"eventCount",0);I(this,"statsCount",0);I(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")});I(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)});I(this,"addStats",({isFinal:A,initiator:t}={isFinal:!1,initiator:"interval"},e={})=>{if(!this.options.includeStats)return;const g=this.parentContext.getStatistics(),B=bo("stats",V(D(D({},e),g),{isFinal:A,initiator:t,count:this.statsCount++}));this.unsentLines.push(B)});I(this,"addEvent",A=>{if(!this.options.includeEvents||this.eventCount>this.options.maxEvents)return;const t=this.parentContext.getStatistics(),e=bo("event",D(D({},t),A));this.eventCount++,this.unsentLines.push(e)});I(this,"getStatistics",()=>({errorCount:this.errorCount}));I(this,"send",A=>r(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 t=this.unsentLines.items().map(e=>JSON.stringify(e)).reverse().join(`
|
|
50
|
+
`);switch(A){case"beacon":navigator.sendBeacon(this.options.url,t);break;case"fetch":default:this.parentContext.connectionState==="connected"?this.emitter.emit("send signal",{type:"telemetry",body:t}):yield ca(new URL(this.options.url),{body:t,headers:{"Content-Type":"text/plain"}});break}this.retries=0,this.unsentLines.clear()}catch(t){this.retries++}}}));I(this,"onVisibilityChange",A=>{A==="hidden"&&(this.addStats({isFinal:!0,initiator:"visibilitychange"}),this.send("beacon"))});I(this,"onPageHide",A=>{this.addStats({isFinal:!0,initiator:"pagehide"},{persisted:A.persisted}),this.send("beacon")});I(this,"onRejection",A=>this.addError(A.reason));I(this,"onError",A=>this.addError(A.error));I(this,"addError",A=>{const{includeErrors:t,maxErrorReports:e}=this.options;if(t&&A instanceof x){if(this.errorCount++,this.errorCount>e)return;const g=this.parentContext.getStatistics();this.unsentLines.push(bo("error",D(D({},g),A.toStringifiable())))}});this.logger=A,this.emitter=t,this.options=D(D({},mu),e),this.parentContext=g}};I(aQ,"create",(A,t,e,g)=>new aQ(A,t,e,g));let rC=aQ;const EQ=class EQ{constructor(A,t,e){I(this,"logger");I(this,"element");I(this,"documentState");I(this,"timers",new NA);I(this,"unload",()=>{this.timers.unload()});I(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=t,this.documentState=e,this.timers.setInterval(this.unpause,100)}};I(EQ,"create",(A,t,e)=>new EQ(A,t,e));let cC=EQ;const Su=["minBufferTime","maxBufferTime","burstEnabled","sizeBasedResolutionCapEnabled","separateVideoSocketEnabled","videoCodecs"];function yu(i){return Su.includes(i)}class fu{constructor(A){I(this,"options");I(this,"overrides",new Map);this.options=A}getOptions(){return this.options}addOverrides(A,t){this.overrides.set(A,t)}set(A,t){this.options[A]=t}get(A,t){var e;if(t&&yu(A)){const g=(e=this.overrides.get(t))==null?void 0:e[A];if(typeof g!="undefined")return g}return this.options[A]}getOverride(A,t){var e;return(e=this.overrides.get(t))==null?void 0:e[A]}}const pu=6,Fu=i=>{let A=[i],t=0,e=0,g=!1;const B=(Q,o)=>{var k,q,U;Q.flags&&Gg(Q.flags)&&(t=(k=Q.compositionTimeOffset)!=null?k:0),Q.timestamp+=t,Q.compositionTimeOffset=((q=Q.compositionTimeOffset)!=null?q:0)-t;const a=Q.timestamp/Q.timescale,h=o.flags&&Gg(o.flags)?(U=o.compositionTimeOffset)!=null?U:0:t,m=(o.timestamp+h)/o.timescale,y=Math.max(0,Math.round((m-a)*Q.timescale));return y>0&&(e=y),V(D({},Q),{duration:y>0?y:e})};return(Q,o=!1)=>{if(Q.flags&&Gg(Q.flags)&&o&&(g=!g),!(o&&A.length<pu&&g)&&A.length>0){g=!1;let c=Q;for(let l=A.length-1;l>0;l--){const m=A[l];if(!m||!c)break;m.timestamp>=c.timestamp?A.splice(l,1):c=m}const h=A.map((l,m)=>B(l,A[m+1]||Q));return A=[Q],h}return A.push(Q),[]}},Gu=(i,A,t)=>{if(Xe(A))return D(V(D({},i),{type:"video",codec:A.codec,isSync:Gg(i.flags),data:i.payload,duration:0,width:A.width,height:A.height}),t);if(A.codec==="webvtt")throw new Error("WebVTT is not supported");return V(D({},i),{type:"audio",channels:A.channels,sampleRate:A.sampleRate,codec:A.codec,language:A.language,isSync:Gg(i.flags),data:i.payload,duration:0})};class ku{constructor(){I(this,"highEntropyValues");var A;(A=self.navigator.userAgentData)==null||A.getHighEntropyValues(["architecture","model","platformVersion","fullVersionList"]).then(t=>{this.highEntropyValues=t})}getUserAgentInformation(){var B,C,Q,o,a,c;const A=window.location.origin,e=!A||A=="null"?"":`${window.location.pathname}${window.location.search}`.substring(0,1e3),g={locationOrigin:window.location.origin,locationPath:e,ancestorOrigins:((B=window.location.ancestorOrigins)==null?void 0:B.length)>0?Array.from(window.location.ancestorOrigins):void 0,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory};if(self.navigator.userAgentData&&this.highEntropyValues){const l=[...(C=this.highEntropyValues.brands)!=null?C:[]];l.sort((U,H)=>U.brand.localeCompare(H.brand));const m=[...(Q=this.highEntropyValues.fullVersionList)!=null?Q:[]];m.sort((U,H)=>U.brand.localeCompare(H.brand));const y=m.map(U=>U.version),f=l.map(U=>U.brand),k=l.map(U=>U.version),q=parseInt((a=(o=this.highEntropyValues.platformVersion)==null?void 0:o.split(".")[0])!=null?a:"1");return D({userAgentLegacy:window.navigator.userAgent,ua:{browser:{brands:f,fullVersionBrands:y,majorVersions:k},device:this.highEntropyValues.model||"Other",os:{family:this.highEntropyValues.platform||"Other",version:(c=this.highEntropyValues.platformVersion)!=null?c:"1",major_version:Number.isFinite(q)?q:0}}},g)}else return D({userAgent:window.navigator.userAgent},g)}}const BE=(i,A)=>i&&typeof i=="object"&&A in i,CE=i=>!(typeof i!="object"||!BE(i,"channelId")||typeof i.channelId!="string"||!BE(i,"url")||typeof i.url!="string"||i.channelId.length===0||i.url.length===0),Ru=i=>{if(!CE(i))throw new x("Invalid options",{isFatal:!0,code:"invalid_options"});const A=D({},i);return Object.keys(A).forEach(t=>{const e=A;typeof e[t]=="undefined"&&delete e[t]}),A},Uu=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},oe=class oe extends it{constructor(t){super();I(this,"pictureInPicture");I(this,"drm");I(this,"browser",fQ());I(this,"options");I(this,"element");I(this,"playbackSource");I(this,"emitter",new it);I(this,"logger");I(this,"modules");I(this,"clientIp");I(this,"sessionId");I(this,"clientId",Fn());I(this,"_channels",[]);I(this,"createdAt",Date.now());I(this,"hasCalledConnect",!1);I(this,"latestEmittedLanguages",[]);I(this,"wakeLock");I(this,"pool",new xt(oe.MAX_POOL_SIZE));I(this,"userAgentInformation",new ku);I(this,"encryptedMediaExtensions");n(this,Yi,0);n(this,At,[]);I(this,"sampleProcessingSesssions",new Map);I(this,"sizes",new Map);I(this,"isSuspended",!0);I(this,"disconnectTimeout");n(this,Ti);I(this,"attach",t=>{var e;(e=this.wakeLock)==null||e.attach(t),t.appendChild(this.element)});I(this,"getOptions",()=>this.options.getOptions());I(this,"getThumbnailUrl",()=>{let t=this.options.get("edgeUrl")||this.options.get("url");t=t.replace("wss://","https://"),t=t.replace("ws://","http://"),t=t.endsWith("/")?t.slice(0,-1):t;const e=window.devicePixelRatio||1,g=Math.round(window.innerWidth*e),B=Math.round(window.innerHeight*e),C=this.options.get("authenticationToken"),Q=C?`&auth.token=${C}`:"";return`${t}/api/thumbnail?channelId=${this.channelId}${Q}&width=${g}&height=${B}`});I(this,"updateAuthenticationToken",t=>{this.logger.debug("Got new auth token",{token:t}),this.options.set("authenticationToken",t),this.emitter.emit("send signal",{type:"refresh auth",token:t})});I(this,"connect",()=>{this.hasCalledConnect||(this.play(),this._connect())});I(this,"_connect",()=>{var t,e;this.hasCalledConnect||(this.hasCalledConnect=!0,Object.values(this.modules).forEach(g=>{g&&"load"in g&&g.load()}),this.unsuspend(),this.playbackSource instanceof TQ&&((e=(t=this.playbackSource).load)==null||e.call(t)),this.modules.connection.connect())});I(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")}));I(this,"onConnectInfo",t=>r(this,null,function*(){var a;this.sessionId=Fn();const e=this.modules.subscription.getTargetSubscription(),g=t.channels.find(c=>c.channelId===e.channelId);if(this.emitter.emit("connect info",t),"timeshift"in t&&t.timeshift?(t.timeshift,this._channels=t.channels.map(c=>V(D({},c),{timeshift:t.timeshift})),this.emit("timeshift info",t.timeshift)):this._channels=t.channels,this.updateTextTracks((a=g==null?void 0:g.renditions)!=null?a:[]),!this.textTrack&&this.options.get("textTrack")&&(this.textTrack=this.options.get("textTrack")),yield Promise.all(t.channels.map(c=>r(this,null,function*(){c.overrides&&this.options.addOverrides(c.channelId,c.overrides),c.renditions=yield this.filterRenditions(c.renditions),this.modules.renditions.setRenditions(c.channelId,c.renditions)}))),!g)throw xn("external");const B=this.options.getOverride("sizeBasedResolutionCapEnabled",this.channelId);B!==void 0&&(this.modules.constraintCap.sizeBasedResolutionCapEnabled=B);const C=this.options.getOverride("minBufferTime",this.channelId),Q=this.options.getOverride("maxBufferTime",this.channelId);if((C||Q)&&(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 o=this.options.get("burstEnabled",this.channelId);return{video:this.targetSubscription.video,audio:this.targetSubscription.audio,burstMs:o?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}}));I(this,"emitLanguagesIfChanged",()=>{const t=this.modules.renditions.getLanguages(),e=this.latestEmittedLanguages;t.length==e.length&&t.every(B=>e.includes(B))||(this.logger.debug("Emitting new languages",{currentLanguages:t}),this.latestEmittedLanguages=t,this.emit("languages",this.latestEmittedLanguages))});I(this,"updateTextTracks",t=>{const e=t.filter(g=>g.codec==="webvtt");e.forEach(g=>{if(!s(this,At).find(C=>C.language===g.language)){if(this.modules.canvasModule){const C=this.modules.canvasModule.textTracks.addTextTrack(g.kind,g.label||g.language||"",g.language||"");s(this,At).push(C)}else if(this.mediaElement instanceof HTMLVideoElement){const C=this.mediaElement.addTextTrack(g.kind,g.label||g.language,g.language);s(this,At).push(C)}}});for(const g of s(this,At))e.find(C=>C.language===g.language)?g.mode==="disabled"&&(g.mode="hidden"):g.mode="disabled";this.emit("text tracks",this.textTracks)});I(this,"cleanupTextTracks",(t=this.currentTime-2e4)=>{s(this,At).forEach(e=>{if(e.cues)for(const g of e.cues)g.endTime*1e3<t-2e3&&e.removeCue(g)})});I(this,"filterRenditions",t=>r(this,null,function*(){const e=yield Promise.all(t.map(Q=>r(this,null,function*(){var c,h,l;if(je(Q))return!0;if(!Xe(Q)||!this.isSupportedVideoCodecProfile(Q.codec,Q.codecString))return!1;if(!this.willUseMediaSource()){const m=this.options.get("advanced"),y=(c=m.wasmDecodingConstraint.bitRate)!=null?c:Number.MAX_SAFE_INTEGER,f=(h=m.wasmDecodingConstraint.width)!=null?h:Number.MAX_SAFE_INTEGER,k=(l=m.wasmDecodingConstraint.height)!=null?l:Number.MAX_SAFE_INTEGER;return Q.bitRate<=y&&Q.width<=f&&Q.height<=k}const o=yield ld(Q);if(!o.supported||Q.codec=="av1"&&!o.smooth&&!o.powerEfficient)return!1;const a=this.options.getOverride("maxVideoBitRate",this.channelId);return a?a>=Q.bitRate:!0})));let g=t.filter((Q,o)=>e[o]);const B=g.filter(Q=>Q.codec==="h264").reverse()[0],C=g.filter(Q=>Q.codec==="av1").reverse()[0];return B&&C&&B.width>C.width&&B.height>C.height&&(g=g.filter(Q=>Q.codec!=="av1")),g}));I(this,"patchSubscription",(t,e)=>{const g=this.options.get("maxInitialBitRate"),B=Math.min(this.options.get("maxVideoBitRate"),g,e,this.targetSubscription.video.bitRate),C=Math.min(this.options.get("maxAudioBitRate"),g,e,this.targetSubscription.audio.bitRate),Q=this.options.get("media")==="audio"?[]:this.options.get("videoCodecs",this.channelId),o=this.supportedAudioCodecs(),a=t.renditions.filter(je),c=t.renditions.filter(Xe),h=o.find(f=>a.find(k=>k.codec===f)!==void 0),l=Q.find(f=>c.find(k=>k.codec===f)!==void 0),m=a.map(f=>f.language);if(this.logger.debug("supported and selected codecs",{audioCodecs:o,videoCodecs:Q,audioCodec:h,videoCodec:l}),l){const f=this.options.get("maxSize");this.modules.subscription.setVideoConstraint(D({codec:l,bitRate:this.abrEnabled?B:this.options.get("maxVideoBitRate")},f))}h&&(this.modules.subscription.setAudioConstraint({codec:h,bitRate:this.abrEnabled?C:this.options.get("maxAudioBitRate"),language:this.options.get("language")}),(!m.includes(this.options.get("language"))||this.language===void 0)&&this.modules.subscription.setLanguage(m[0])),this.alignSizeAndBitRate(this.targetSubscription);const y=this.modules.subscription.getTargetSubscription();this.emitter.emit("subscription changed",{to:y,from:this.modules.subscription.getCurrentSubscription()})});I(this,"isSupportedVideoCodecProfile",(t,e)=>{if(this.willUseMediaSource()){const g=Sg();return g?g.isTypeSupported(ze({codec:t,codecString:e})):!0}if(t==="h264"){const g=!!(e!=null&&e.startsWith("avc1.42")),B=!!(e!=null&&e.startsWith("avc1.66."));return g||B}return t!=="av1"});I(this,"supportedAudioCodecs",()=>{if(this.options.get("media")==="video")return[];const t=[];return this.willUseMediaSource()&&t.push("aac"),(this.browser.supportsMp4Opus&&this.options.get("mseOpusEnabled")||!this.willUseMediaSource())&&t.push("opus"),t});I(this,"initializeDecodingModule",()=>r(this,null,function*(){var g,B;const t=this.currentRenditionLevel,e=[];if(!t)throw new x("No currentRenditionLevel",{code:"no_current_rendition_level",isFatal:!1});if(t!=null&&t.video&&e.push({type:"video",mimeType:ze(t.video),codec:t.video.codec}),t!=null&&t.audio&&e.push({type:"audio",codec:t.audio.codec,mimeType:ze(t.audio)}),e.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(g=this.modules.mseModule)==null?void 0:g.setSourceBuffers(e);else{const C=yield ro.create(this.emitter,this.logger.createContext("DecoderModule"),e,this.playbackSource,this.pool);(B=this.modules.decoder)==null||B.unload(),this.modules.decoder=C,this.modules.decoder.load()}}));I(this,"unload",()=>r(this,null,function*(){var t,e,g;this.logger.debug("Unloading modules..."),yield Promise.all(Object.values(this.modules).map(B=>B==null?void 0:B.unload())),(t=this.wakeLock)==null||t.unload(),this.pool=new xt(oe.MAX_POOL_SIZE),(g=(e=this.playbackSource).unload)==null||g.call(e),this.element.remove(),this.emitter.reset(),this.encryptedMediaExtensions.unload(),this.reset(),this.logger.debug("Unloaded modules")}));I(this,"userInput",()=>{this.play()});I(this,"pause",()=>{this.options.get("pauseSupportEnabled")&&this.playbackState!=="paused"&&(this.playbackSource.pause(),this.hasCalledConnect&&this.suspend())});I(this,"registerDebugInstance",()=>{dd(this)});I(this,"play",()=>{var t;this.hasCalledConnect?this.unsuspend():this.playbackState!=="playing"&&(this._connect(),self.addEventListener("__vindral_register_debug__",this.registerDebugInstance),this.modules.timer.setInterval(()=>this.cleanupTextTracks(),oe.REMOVE_CUE_THRESHOLD)),(t=this.wakeLock)==null||t.enable(),this.playbackState==="paused"&&(this.resetModules(),this.emitter.emit("flush buffers"),this.cleanupTextTracks(Number.MAX_SAFE_INTEGER)),this.playbackSource.play()});I(this,"getStatistics",()=>{const t=Object.values(this.modules).reduce((g,B)=>B&&"getStatistics"in B?D(D({},g),B.getStatistics()):g,this.getRuntimeInfo()),e=Math.round(this.timeActive>0?(t.bytesReceived||0)*8/(this.timeActive/1e3):0);return V(D({},t),{averageBitRate:e})});I(this,"resetModules",()=>{Object.values(this.modules).forEach(t=>{t&&"reset"in t&&t.reset()}),this.sampleProcessingSesssions.clear(),this.playbackSource.currentTime=0,this.playbackSource.isActivated=!1});I(this,"getRuntimeInfo",()=>{const t=this.modules.canvasModule?this.options.get("iosMediaElementEnabled"):void 0;return D({uptime:Date.now()-this.createdAt,version:"4.1.5-6-g385d5a4e",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(),iosMediaElementEnabled:t},this.userAgentInformation.getUserAgentInformation())});I(this,"onMediaElementState",t=>{this.logger.info("media element state",{state:t}),this.options.get("pauseSupportEnabled")&&(t==="paused"?this.modules.documentState.isVisible&&(this.suspend(),this.modules.connection.disconnect()):(this.unsuspend(),this.modules.connection.getState()==="disconnected"&&this.modules.connection.unsuspend()))});I(this,"onBufferEvent",t=>{var g,B,C,Q;this.emit("buffer state event",t);const e=!this.playbackSource.isActivated||this.playbackSource.isPaused;if(t==="filled"&&e){const o=Math.max(this.currentTime,(B=(g=this.videoBufferedRanges[0])==null?void 0:g.start)!=null?B:0,(Q=(C=this.audioBufferedRanges[0])==null?void 0:C.start)!=null?Q:0);this.logger.info("Buffer filled - starting playback",{currentTime:o}),this.playbackSource.currentTime=o,this.modules.sync.activateSyncAdjustments(),this.playbackSource.isActivated=!0}else t==="drained"&&this.playbackSource.isPaused&&(this.playbackSource.isActivated=!1,this.modules.sync.deactivateSyncAdjustments())});I(this,"timeToFirstFrame",()=>{const t=this.modules.playback.getFirstFrameTime(),e=this.modules.connection.firstConnectionTime;if(e&&t)return t-e});this.options=new fu(D(D({},Ac),Ru(t)));const e=["localhost","127.0.0.1"];t.telemetryEnabled===void 0&&e.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}},B=UA.get();B.setLevel(this.options.get("logLevel")),B.setDebug(!1),this.logger=B;const C=po.create(this.emitter,this.logger.createContext("PictureInPictureModule")),Q=NA.create(),o=no.create(this.emitter,this.logger.createContext("ConnectionModule"),{reconnectHandler:this.options.get("reconnectHandler"),options:this.options,onConnectInfo:this.onConnectInfo}),a=Uo.create(this.logger.createContext("SubscriptionModule"),this.emitter,g),c=Ro.create(this.emitter,a),h=ko.create(this.emitter,this.logger.createContext("QualityOfServiceModule"),c),l=Fo.create(this.emitter,this.logger.createContext("PlaybackModule"),this,this.options.get("minBufferTime"));this.encryptedMediaExtensions=new $n(this.emitter,this.logger.createContext("EncryptedMediaExtensions"),t.drm),this.drm={setHeaders:w=>{this.encryptedMediaExtensions.headers=w},setQueryParams:w=>{this.encryptedMediaExtensions.queryParams=w}};const m=co.create(this.emitter),y=this.options.get("poster"),f=y===!0?this.getThumbnailUrl():y||void 0;let k,q,U;if(this.willUseMediaSource()){const w=new TQ({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:f});w.on("buffer state",G=>this.emitter.emit("buffer state",G)),w.on("needs user input",G=>this.emitter.emit("needs user input",G)),w.on("volume state",G=>this.emit("volume state",G)),w.on("media element state",G=>this.onMediaElementState(G)),this.element=w.element,this.playbackSource=w,$n.isSupported()&&this.encryptedMediaExtensions.attach(w.element),k=fo.create(this.logger.createContext("MseModule"),this.emitter,this.element),this.options.get("pauseSupportEnabled")||(q=cC.create(this.logger.createContext("UnpauseModule"),w,m)),this.options.get("pictureInPictureEnabled")&&this.emitter.emit("add picture in picture listener",{element:w.element})}else if(this.browser.platform.iosVersion>=15&&this.options.get("iosMediaElementEnabled")){const w=yo.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:f}),G=w.element();this.element=G.element,this.playbackSource=w,U=w,this.options.get("pictureInPictureEnabled")&&this.browser.platform.iosVersion>15&&this.emitter.emit("add picture in picture listener",{element:this.element}),this.options.get("pauseSupportEnabled")||(q=cC.create(this.logger.createContext("UnpauseModule"),G,m))}else{const w=So.create(this.emitter,this.logger.createContext("LegacyCanvasModule"),this.pool,this,this.options.get("muted")||this.options.get("media")==="video",this.options.get("volume"));this.element=w.element(),this.playbackSource=w,U=w,this.options.get("iosWakeLockEnabled")&&(this.wakeLock=new cd)}this.emitter.on("channel reset",this.resetModules),this.emitter.on("no data timeout",this.resetModules),this.emitter.on("media element state",w=>this.onMediaElementState(w)),this.emitter.on("volume state",w=>this.emit("volume state",w)),this.options.get("pauseSupportEnabled")||this.emitter.on("exit picture in picture",()=>Q.setTimeout(()=>this.play(),0)),this.emitter.on("constraint cap changed",w=>{this.logger.info("new cap set",{cap:w}),this.alignSizeAndBitRate(this.targetSubscription)}),this.pictureInPicture={enter:()=>C.requestPictureInPicture(),exit:()=>C.exitPictureInPicture(),isActive:()=>C.isPictureInPictureActive(),isSupported:()=>C.isPictureInPictureSupported()},this.emitter.on("error",w=>{if(w.type()==="external"&&this.emit("error",w),w.isFatal())return()=>void this.unload()});const H=this.browser.platform.isIOS&&!this.browser.platform.isIpadOS,T=No.create(this.emitter,this.logger.createContext("SyncModule"),this.playbackSource,l,this.willUseMediaSource()&&!H),z=uo.create(this.logger.createContext("JitterModule")),Y=(this.options.get("edgeUrl")||this.options.get("url")).replace("wss://","https://").replace("ws://","http://").replace("//lb.","//errors."),FA=new URL("/telemetry",Y).toString(),nA=rC.create(this.logger.createContext("TelemetryModule"),this.emitter,{url:FA,enabled:this.options.get("telemetryEnabled"),includeStats:!1,interval:5e3},this);this.modules={telemetry:nA,bufferTime:OQ.create(this.emitter,this.logger.createContext("BufferTimeModule"),h,this,{maxBufferTime:this.options.get("maxBufferTime"),minBufferTime:this.options.get("minBufferTime")}),incomingData:lo.create(this.emitter),adaptivity:WQ.create(this.emitter,this.logger.createContext("AdaptivityModule"),h,{cooldownTime:Math.max(this.options.get("minBufferTime"),2e3)}),constraintCap:Eo.create(this.emitter,this.element,c,this.options.get("abrEnabled")?this.options.get("sizeBasedResolutionCapEnabled"):!1),event:ho.create(this.emitter,this.logger.createContext("EventModule"),T),sync:T,jitter:z,documentState:m,connection:o,playback:l,pictureInPicture:C,timer:Q,subscription:a,renditions:c,qualityOfService:h,mseModule:k,unpause:q,canvasModule:U},this.modules.adaptivity.isEnabled=this.options.get("abrEnabled"),this.emitter.on("page active",w=>{var G;w&&typeof this.disconnectTimeout=="number"&&(this.modules.timer.clearInterval(this.disconnectTimeout),this.disconnectTimeout=void 0),w?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(),(G=this.modules.canvasModule)==null||G.unsuspend()):this.modules.connection.disconnect():(this.disconnectTimeout&&this.modules.timer.clearInterval(this.disconnectTimeout),this.disconnectTimeout=this.modules.timer.setInterval(()=>{const AA=this.playbackState==="paused"||this.muted;this.connectionState==="connected"&&AA&&(this.emitter.emit("flush buffers"),this.modules.connection.disconnect("Page inactive timeout"))},oe.DISCONNECT_TIMEOUT)))});let mA;this.emitter.on("context switch complete",()=>{mA||(mA=window.setTimeout(()=>{window.clearTimeout(mA),mA=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",w=>this.emit("needs user input",w)),this.emitter.on("event",w=>{switch(w.type){case"metadata":this.emit("metadata",w);break;case"channel switch":this.emit("channel switch",{channelId:w.channelId});break;case"language switch":this.emit("language switch",{language:w.language});break}}),this.emitter.on("buffer state event",this.onBufferEvent),this.emitter.on("playback state",w=>this.emit("playback state",w)),this.emitter.on("rendition level changed",({to:w})=>{w&&this.emit("rendition level",w)}),this.emitter.on("connection state",w=>{this.emit("connection state",w)}),this.emitter.on("recovered from media error",()=>{this.modules.adaptivity.reset(this.targetBufferTime*2)}),this.emitter.once("connect info",w=>{var iA,O,_;const AA=((O=(iA=w.telemetry)==null?void 0:iA.probability)!=null?O:1)>=Math.random();w.telemetry&&((_=this.modules.telemetry)==null||_.unload(),this.modules.telemetry=rC.create(this.logger.createContext("TelemetryModule"),this.emitter,V(D({},w.telemetry),{enabled:this.options.get("telemetryEnabled")&&AA}),this),this.modules.telemetry.load())}),this.emitter.on("adapt level",w=>{var R,L,Z,aA,P;this.logger.debug("adapt level",{direction:w});const G=this.modules.renditions.getRenditionLevels(),AA=this.modules.renditions.getRenditionLevel(),iA=G.findIndex(X=>X===AA),O=G.length-1;let _=iA;switch(w){case"upgrade":{const X=Math.min(iA+1,O),WA=G[X],dg=(R=this.modules.connection.estimatedBandwidth)!=null?R:he(),DB=((Z=(L=WA==null?void 0:WA.audio)==null?void 0:L.bitRate)!=null?Z:0)+((P=(aA=WA==null?void 0:WA.video)==null?void 0:aA.bitRate)!=null?P:0),Pi=dg*2>DB;WA&&Pi&&this.modules.adaptivity.isQoSOk(WA)&&(_=X)}break;case"downgrade":_=Math.max(iA-1,0);break;case"double downgrade":_=Math.max(iA-2,0);break;case"reconnect":if(iA===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 _=0}if(_===iA)return;const QA=G[_];this.alignSizeAndBitRate(V(D({},this.targetSubscription),{video:D(D({},this.targetSubscription.video),QA==null?void 0:QA.video),audio:D(D({},this.targetSubscription.audio),QA==null?void 0:QA.audio)})),this.emitter.emit("adapted level")}),this.emitter.on("text track data",w=>{const G=s(this,At).find(_=>_.language===w.language),iA=this.modules.sync.getTimeshiftOffset()/1e3,O=iA-s(this,Yi);if(E(this,Yi,iA),G){if(G.cues)for(const _ of G.cues)_.startTime-=O,_.endTime-=O;for(const _ of w.cues){const QA=new VTTCue(_.startTime-iA,_.endTime-iA,_.text);G.addCue(QA)}}}),this.emitter.on("received signal",w=>{var iA;const G=w,AA=this.modules.subscription.getCurrentSubscription();switch(this.logger.debug("received",D({},G)),G.type){case"client ip":this.clientIp=G.ip;break;case"renditions":this.updateTextTracks(G.renditions),E(this,Ti,this.filterRenditions(G.renditions).then(O=>{this.emitter.emit("renditions",{renditions:O,channelId:this.currentSubscription.channelId}),this.emit("rendition levels",this.modules.renditions.getRenditionLevels()),this.emitLanguagesIfChanged()}).finally(()=>{E(this,Ti,void 0)}));break;case"subscription changed":try{Uu(G.subscription)}catch(O){this.emitter.emit("error",new x("Subscription failed validation",{source:O instanceof Error?O:void 0,isFatal:!1,code:"subscription_failed_validation"}))}this.emitter.emit("subscription changed",{reset:G.reset,to:G.subscription,from:this.modules.subscription.getCurrentSubscription()}),G.reset&&AA.channelId!==G.subscription.channelId&&(this.emit("error",Vn(G.subscription.channelId)),this.emit("channel switch failed",{channelId:AA.channelId})),this.modules.sync.timeshiftOnAudio=!((iA=G.subscription.video)!=null&&iA.codec),this.modules.adaptivity.reset();break;case"timing info":this.modules.sync.updateChannelSyncInfo(G.timingInfo.channelId,G.timingInfo),this.emit("server wallclock time",G.timingInfo.wallclockTime);break}}),this.emitter.on("channel switch timeout",w=>{this.emit("error",Vn(w)),this.emit("channel switch failed",{channelId:this.currentSubscription.channelId})}),this.emitter.on("received data",w=>{const G=this.modules.subscription.getCurrentSubscription(),AA=Ed(w);if(!G){this.logger.warn("Received unwanted message",D({},AA));return}JA(V(D({},AA),{channelId:G.channelId}))}),this.emitter.on("received moq data",w=>{var _,QA,R;const G=w.payload.mediaType(),AA=w.channelId,iA=w.renditionId,O=this.modules.sync.processFragment(AA,w.payload);if(G!=="text"&&this.modules.jitter.recordSample({type:G,renditionId:iA,timestamp:O.baseMediaDecodeTime(),timescale:O.timescale()}),w.switchInfo.channelId&&(w.switchInfo.drmTransition&&this.emitter.emit("error",Zn("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:w.switchInfo.channelId,timestamp:O.baseMediaDecodeTime()/O.timescale()*1e3})),w.switchInfo.language&&this.modules.event.addEvent({type:"language switch",language:w.switchInfo.language,timestamp:O.baseMediaDecodeTime()/O.timescale()*1e3}),this.modules.incomingData.add(G,w.payload.rawBytes().byteLength),O.fragment().emsgs.forEach(L=>{if(!L.presentationTime)return;const Z=Kc(L.data);Z&&this.modules.event.addEvent({id:L.id,timestamp:L.presentationTime/L.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:Z.txx.value,type:"metadata"})}),this.modules.decoder){const L=(_=O.header().init().moov.traks[0])==null?void 0:_.mdia.minf.stbl.stsd,Z=(QA=L==null?void 0:L.avc1)==null?void 0:QA.avcC.bytes,aA=(R=L==null?void 0:L.codec)!=null?R:"h264";if(Z){const P=Z.buffer.slice(Z.byteOffset,Z.byteOffset+Z.byteLength);if(G==="text")throw new Error("Subtitles are not supported");this.emitter.emit("init segment",{initSegment:{channelId:AA,renditionId:iA,data:P,timescale:1e3,type:G,codec:aA},mimeType:G})}for(let P=0;P<O.samplesCount();P++){const X=O.sample(P);X&&this.emitter.emit("coded sample",V(D({},X),{renditionId:iA,channelId:AA,data:X.data.buffer.slice(X.data.byteOffset,X.data.byteOffset+X.data.byteLength)}))}}else this.emitter.emit("fragment",{mimeType:w.mimeType,codec:w.codec,fragment:O,channelId:AA,renditionId:iA})});const tt=this.options.get("container");tt&&this.attach(tt),this.logger.info("Created Vindral instance",{options:this.options});const JA=w=>r(this,null,function*(){const G=w.channelId;s(this,Ti)&&(yield s(this,Ti));const AA=this.modules.renditions.getRendition(w.renditionId,G);if(!od(w.flags)){if(nd(w.flags)){const O=new TextDecoder().decode(w.payload),_=this.modules.sync.getTimeshiftOffset();if(w.renditionId!==0){const QA=pn(O);if(QA&&QA.language!==void 0){const L=new aa().parse(QA.content||""),Z=_/1e3,aA=s(this,At).find(X=>X.language===QA.language),P=Z-s(this,Yi);if(E(this,Yi,Z),aA){if(aA.cues)for(const X of aA.cues)X.startTime-=P,X.endTime-=P;for(const X of L){const WA=new VTTCue(X.startTime-Z,X.endTime-Z,X.text);aA.addCue(WA)}}}}else this.modules.event.addEvent({timestamp:w.timestamp/w.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:O,type:"metadata"})}else if(AA!=null&&AA.codec){const iA=RQ(AA.codec);if(iA==="text")throw new Error("Subtitles are not supported");if(this.modules.incomingData.add(iA,w.payload.byteLength),Qd(w.flags)){const O=V(D({type:iA,data:w.payload,codec:AA.codec},w),{channelId:G}),_=id(O.codec,O.payload);_&&this.sizes.set(O.renditionId,_);const QA=ze({codec:AA.codec,codecString:AA.codecString});this.emitter.emit("init segment",{initSegment:O,mimeType:QA}),this.emit("initialized media")}else{const O=Gu(w,AA,this.sizes.get(w.renditionId));this.modules.jitter.recordSample(O);let _=this.sampleProcessingSesssions.get(iA);if(!_)_=Fu(this.modules.sync.processSample(O)),this.sampleProcessingSesssions.set(iA,_);else{const QA=_(this.modules.sync.processSample(O),this.isSwitchingRenditionLevel&&O.type==="video");let R=O;QA.forEach(L=>{this.modules.event.extractEvent(L,R),this.emitter.emit("coded sample",L),R=L})}}}}});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")),Ve(this.options.get("maxSize"),kB())||(this.maxSize=this.options.get("maxSize")),this.options.get("burstEnabled")&&a.enableBurst(this.targetBufferTime)}set volume(t){this.playbackSource.volume=t}get volume(){return this.playbackSource.volume}set muted(t){if(t===this.muted)return;const e=this.playbackSource.muted;this.playbackSource.muted=t,!t&&e&&!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(t){this.modules.constraintCap.sizeBasedResolutionCapEnabled=t}get abrEnabled(){return this.modules.adaptivity.isEnabled}set abrEnabled(t){this.modules.constraintCap.sizeBasedResolutionCapEnabled=t?this.options.get("sizeBasedResolutionCapEnabled"):!1,this.modules.adaptivity.isEnabled=t,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(t){this.modules.playback.getTargetBufferTime()!==t&&(this.modules.playback.setTargetBufferTime(t),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 t;if(this.playbackSource.currentTime!==0)return this.targetBufferTime+((t=this.modules.sync.drift)!=null?t: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(t){this.modules.subscription.setLanguage(t)}set textTrack(t){s(this,At).forEach(e=>{e.label===t?e.mode="showing":e.mode="hidden"}),this.emitter.emit("text track",t)}get textTracks(){return s(this,At).filter(t=>t.mode!=="disabled").map(t=>t.label)}get textTrack(){var t;return(t=s(this,At).find(e=>e.mode==="showing"))==null?void 0:t.label}get channelId(){var t,e;return(e=(t=this.modules)==null?void 0:t.subscription.getTargetSubscription().channelId)!=null?e:this.options.get("channelId")}set channelId(t){if(t===this.channelId)return;this.modules.subscription.setChannelId(t);const e=this.options.get("media")==="audio"?[]:this.options.get("videoCodecs"),g=this.modules.renditions.getAudioRenditions(t),B=this.modules.renditions.getVideoRenditions(t),C=this.targetSubscription.audio.language,Q=g==null?void 0:g.some(a=>a.language===C),o=e.find(a=>(B==null?void 0:B.find(c=>c.codec===a))!==void 0);o&&this.modules.subscription.setVideoCodec(o),this.logger.debug("Channel switch - started",{audioRenditions:g,targetSubscriptionLanguage:C,targetHasCurrentLanguage:Q}),this.alignSizeAndBitRate(this.targetSubscription)}get maxSize(){var g,B;const{width:t,height:e}=(B=(g=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:g.video)!=null?B:kB();return{width:t,height:e}}set maxSize(t){this.modules.constraintCap.setUserSpecifiedCap({video:{width:t.width,height:t.height}}),this.alignSizeAndBitRate(this.targetSubscription)}get maxVideoBitRate(){var t,e;return(e=(t=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:t.video.bitRate)!=null?e:he()}set maxVideoBitRate(t){this.modules.constraintCap.setUserSpecifiedCap({video:{bitRate:t}}),this.alignSizeAndBitRate(this.targetSubscription)}get maxAudioBitRate(){var t,e;return(e=(t=this.modules.constraintCap.getCurrentConstraintCap())==null?void 0:t.audio.bitRate)!=null?e:he()}set maxAudioBitRate(t){this.modules.constraintCap.setUserSpecifiedCap({audio:{bitRate:t}}),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 t,e,g,B;return(B=(g=(t=this.modules.mseModule)==null?void 0:t.getBuffer("video"))!=null?g:(e=this.modules.decoder)==null?void 0:e.getBuffer("video"))!=null?B:[]}get audioBufferedRanges(){var t,e,g,B;return(B=(g=(t=this.modules.mseModule)==null?void 0:t.getBuffer("audio"))!=null?g:(e=this.modules.decoder)==null?void 0:e.getBuffer("audio"))!=null?B:[]}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 t;return(t=this.modules)!=null&&t.canvasModule?this.modules.canvasModule.audioNode:void 0}get drmStatistics(){var t;return(t=this.encryptedMediaExtensions)==null?void 0:t.getStatistics()}get uptime(){return Date.now()-this.createdAt}suspend(){this.isSuspended||(Object.values(this.modules).forEach(t=>{t&&"suspend"in t&&t.suspend()}),this.isSuspended=!0)}unsuspend(){this.isSuspended&&(Object.values(this.modules).forEach(t=>{t&&"unsuspend"in t&&t.unsuspend()}),this.isSuspended=!1)}alignSizeAndBitRate(t){const e=this.modules.constraintCap.constrainSubscription(V(D({},t),{video:D({},t.video),audio:D({},t.audio)})),g=this.modules.constraintCap.getUserSpecifiedCap();!this.abrEnabled&&g&&(e.audio.bitRate=g.audio.bitRate,e.video.bitRate=g.video.bitRate,e.video.width=g.video.width,e.video.height=g.video.height);const B=this.modules.renditions.getRenditionLevel(e);if(B){if(B.video&&(this.modules.subscription.setVideoBitRate(B.video.bitRate),this.modules.subscription.setSize(B.video)),B.audio)this.modules.subscription.setAudioBitRate(B.audio.bitRate),this.modules.subscription.setLanguage(B.audio.language);else if(e.audio.language){let C=this.modules.renditions.getAudioRenditions(e.channelId);!this.abrEnabled&&g&&(C=C==null?void 0:C.filter(h=>h.bitRate<g.audio.bitRate));const Q=e.audio.language,o=C==null?void 0:C.some(h=>h.language===Q),a=C==null?void 0:C.find(h=>h.language),c=(C==null?void 0:C.length)&&C[0]||void 0;o||(a?(this.logger.debug("Randomizing language since target did not have current language"),this.modules.subscription.setAudioBitRate(a.bitRate),this.modules.subscription.setLanguage(a.language)):(this.logger.debug("Randomizing audio rendition since target did not have current language"),c!=null&&c.bitRate&&this.modules.subscription.setAudioBitRate(c.bitRate),this.modules.subscription.setLanguage(c==null?void 0:c.language)))}}}get currentSubscription(){return this.modules.subscription.getCurrentSubscription()}get targetSubscription(){return this.modules.subscription.getTargetSubscription()}willUseMediaSource(){return this.browser.supportsMediaSource&&this.options.get("mseEnabled")}};Yi=new WeakMap,At=new WeakMap,Ti=new WeakMap,I(oe,"MAX_POOL_SIZE",10),I(oe,"DISCONNECT_TIMEOUT",15*1e3),I(oe,"REMOVE_CUE_THRESHOLD",1e3*10);let hC=oe;const QE={bar:"_bar_qm7bl_1",hidden:"_hidden_qm7bl_47"},Ug={"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"},Nu={"icon-button":"_icon-button_5fg7v_1"},oE={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>
|