@vindral/web-sdk 4.1.2-7-gc4e751c6 → 4.1.2-9-g04c36ea5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/legacy.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(u,D){typeof exports=="object"&&typeof module!="undefined"?D(exports):typeof define=="function"&&define.amd?define(["exports"],D):(u=typeof globalThis!="undefined"?globalThis:u||self,D(u.Vindral={}))})(this,(function(u){"use strict";var Dw=Object.create;var gn=Object.defineProperty,Sw=Object.defineProperties,mw=Object.getOwnPropertyDescriptor,yw=Object.getOwnPropertyDescriptors;var EQ=Object.getOwnPropertySymbols;var vE=Object.prototype.hasOwnProperty,KE=Object.prototype.propertyIsEnumerable;var Tt=(u,D)=>(D=Symbol[u])?D:Symbol.for("Symbol."+u),Ce=u=>{throw TypeError(u)},sn=Math.pow,rQ=(u,D,p)=>D in u?gn(u,D,{enumerable:!0,configurable:!0,writable:!0,value:p}):u[D]=p,S=(u,D)=>{for(var p in D||(D={}))vE.call(D,p)&&rQ(u,p,D[p]);if(EQ)for(var p of EQ(D))KE.call(D,p)&&rQ(u,p,D[p]);return u},V=(u,D)=>Sw(u,yw(D)),qE=(u,D)=>gn(u,"name",{value:D,configurable:!0});var YE=(u,D)=>{var p={};for(var k in u)vE.call(u,k)&&D.indexOf(k)<0&&(p[k]=u[k]);if(u!=null&&EQ)for(var k of EQ(u))D.indexOf(k)<0&&KE.call(u,k)&&(p[k]=u[k]);return p};var Hi=u=>{var D;return[,,,Dw((D=u==null?void 0:u[Tt("metadata")])!=null?D:null)]},TE=["class","method","getter","setter","accessor","field","value","get","set"],dB=u=>u!==void 0&&typeof u!="function"?Ce("Function expected"):u,fw=(u,D,p,k,y)=>({kind:TE[u],name:D,metadata:k,addInitializer:G=>p._?Ce("Already initialized"):y.push(dB(G||null))}),He=(u,D)=>rQ(D,Tt("metadata"),u[3]),qi=(u,D,p,k)=>{for(var y=0,G=u[D>>1],L=G&&G.length;y<L;y++)D&1?G[y].call(p):k=G[y].call(p,k);return k},PA=(u,D,p,k,y,G)=>{var L,Z,z,QA,q,_=D&7,ot=!!(D&8),hA=!!(D&16),DA=_>3?u.length+1:_?ot?1:2:0,mB=TE[_+5],yB=_>3&&(u[DA-1]=[]),mQ=u[DA]||(u[DA]=[]),VA=_&&(!hA&&!ot&&(y=y.prototype),_<5&&(_>3||!hA)&&mw(_<4?y:{get[p](){return s(this,G)},set[p](pA){return a(this,G,pA)}},p));_?hA&&_<4&&qE(G,(_>2?"set ":_>1?"get ":"")+p):qE(y,p);for(var Ti=k.length-1;Ti>=0;Ti--)QA=fw(_,p,z={},u[3],mQ),_&&(QA.static=ot,QA.private=hA,q=QA.access={has:hA?pA=>pw(y,pA):pA=>p in pA},_^3&&(q.get=hA?pA=>(_^1?s:d)(pA,y,_^4?G:VA.get):pA=>pA[p]),_>2&&(q.set=hA?(pA,dg)=>a(pA,y,dg,_^4?G:VA.set):(pA,dg)=>pA[p]=dg)),Z=(0,k[Ti])(_?_<4?hA?G:VA[mB]:_>4?void 0:{get:VA.get,set:VA.set}:y,QA),z._=1,_^4||Z===void 0?dB(Z)&&(_>4?yB.unshift(Z):_?hA?G=Z:VA[mB]=Z:y=Z):typeof Z!="object"||Z===null?Ce("Object expected"):(dB(L=Z.get)&&(VA.get=L),dB(L=Z.set)&&(VA.set=L),dB(L=Z.init)&&yB.unshift(L));return _||He(u,y),VA&&gn(y,p,VA),hA?_^4?G:VA:y},I=(u,D,p)=>rQ(u,typeof D!="symbol"?D+"":D,p),Bn=(u,D,p)=>D.has(u)||Ce("Cannot "+p),pw=(u,D)=>Object(D)!==D?Ce('Cannot use the "in" operator on this value'):u.has(D),s=(u,D,p)=>(Bn(u,D,"read from private field"),p?p.call(u):D.get(u)),n=(u,D,p)=>D.has(u)?Ce("Cannot add the same private member more than once"):D instanceof WeakSet?D.add(u):D.set(u,p),a=(u,D,p,k)=>(Bn(u,D,"write to private field"),k?k.call(u,p):D.set(u,p),p),d=(u,D,p)=>(Bn(u,D,"access private method"),p);var ft=(u,D,p,k)=>({set _(y){a(u,D,y,p)},get _(){return s(u,D,k)}});var r=(u,D,p)=>new Promise((k,y)=>{var G=z=>{try{Z(p.next(z))}catch(QA){y(QA)}},L=z=>{try{Z(p.throw(z))}catch(QA){y(QA)}},Z=z=>z.done?k(z.value):Promise.resolve(z.value).then(G,L);Z((p=p.apply(u,D)).next())}),aA=function(u,D){this[0]=u,this[1]=D},Qe=(u,D,p)=>{var k=(L,Z,z,QA)=>{try{var q=p[L](Z),_=(Z=q.value)instanceof aA,ot=q.done;Promise.resolve(_?Z[0]:Z).then(hA=>_?k(L==="return"?L:"next",Z[1]?{done:hA.done,value:hA.value}:hA,z,QA):z({value:hA,done:ot})).catch(hA=>k("throw",hA,z,QA))}catch(hA){QA(hA)}},y=L=>G[L]=Z=>new Promise((z,QA)=>k(L,Z,z,QA)),G={};return p=p.apply(u,D),G[Tt("asyncIterator")]=()=>G,y("next"),y("throw"),y("return"),G},Cn=u=>{var D=u[Tt("asyncIterator")],p=!1,k,y={};return D==null?(D=u[Tt("iterator")](),k=G=>y[G]=L=>D[G](L)):(D=D.call(u),k=G=>y[G]=L=>{if(p){if(p=!1,G==="throw")throw L;return L}return p=!0,{done:!1,value:new aA(new Promise(Z=>{var z=D[G](L);z instanceof Object||Ce("Object expected"),Z(z)}),1)}}),y[Tt("iterator")]=()=>y,k("next"),"throw"in D?k("throw"):y.throw=G=>{throw G},"return"in D&&k("return"),y},EA=(u,D,p)=>(D=u[Tt("asyncIterator")])?D.call(u):(u=u[Tt("iterator")](),D={},p=(k,y)=>(y=u[k])&&(D[k]=G=>new Promise((L,Z,z)=>(G=y.call(u,G),z=G.done,Promise.resolve(G.value).then(QA=>L({value:QA,done:z}),Z)))),p("next"),p("return"),D);var Ct=(u,D,p)=>{if(D!=null){typeof D!="object"&&typeof D!="function"&&Ce("Object expected");var k,y;p&&(k=D[Tt("asyncDispose")]),k===void 0&&(k=D[Tt("dispose")],p&&(y=k)),typeof k!="function"&&Ce("Object not disposable"),y&&(k=function(){try{y.call(this)}catch(G){return Promise.reject(G)}}),u.push([p,k,D])}else p&&u.push([p]);return D},Qt=(u,D,p)=>{var k=typeof SuppressedError=="function"?SuppressedError:function(L,Z,z,QA){return QA=Error(z),QA.name="SuppressedError",QA.error=L,QA.suppressed=Z,QA},y=L=>D=p?new k(L,D,"An error was suppressed during disposal"):(p=!0,L),G=L=>{for(;L=u.pop();)try{var Z=L[1]&&L[1].call(L[2]);if(L[0])return Promise.resolve(Z).then(G,z=>(y(z),G()))}catch(z){y(z)}if(p)throw D};return G()};var Wt,zi,at,kg,Rg,Ft,Et,lA,Ot,Ee,je,Ug,ze,_i,$i,Ng,Qn,_e,$e,tt,rt,Ai,ti,bg,tA,ei,Vt,ct,Gt,FA,ce,he,uC,AI,Lg,Jg,uA,PE,xE,WE,OE,wC,DC,VE,lB,SC,ZE,XE,As,ts,es,is,vA,WA,gA,II,de,Zt,ii,jE,on,kt,gI,sI,Is,gs,BI,ss,Bs,Rt,CI,Cs,Qs,QI,Ii,zE,nn,ht,oI,os,nI,ns,as,Es,aI,yC,gi,_E,an,ue,rs,Ut,si,Bi,Ci,Nt,cs,Qi,bt,fC,IA,uB,cQ,vi,hQ,qe,EI,rI,Xt,pC,OA,ZA,oi,FC,jt,cI,cA,$E,Ar,tr,er,ir,Ir,gr,sr,Br,Cr,hI,ds,ls,SA,us,dI,lI,ws,GC,Qr,kC,wI,DI,we,ni,RC,ai,dt,LA,Ds,Ss,et,ms,ys,mI,fs,UC,or,Ei,ps,yI,Fs,fI,Gs,ri,De,rg,mE,pI,ks,FI,ci,Se,me,ye,Oo,hi,yE,GI,GA,kI,RI,Vo,UI,wB,fE,pE,FE,GE,zt,XA,di,li,NI,Lt,dQ,cg,kE,RE,UE,NE,lt,Rs,ui,bI,LI,mA,nr,ar,JI,lQ,uQ,wQ,DB,it,Us,wi,MI,Ns,JA,Ki,Yi,fe,_t,HI,Di,$t,qI,vI,NC,Er,Ae,te,pe,bs,Ls,bC,LC,rr,ee,KI,Js,jA,Jt,Si,It,Ms,JC,Hs,En,ut,mi,ie,Mt,qs,rn,vs,Fe,Ks,Ys,Ts,MC,cr,Ps,YI,xs,TI,Ws,cn,Os,Ht,Vs,Zs,qC,hr,vC,Ge,yi,Xs,js,zs,fi,hn,dr,KC,_s,ke,xI,bE,pi,Fi,Gi,Re,_o,WI,DQ,ki,$s,YC,lr,AB,TC,ur,PC,VI,ZI,tB,eB,LE,JE,ME,XI,jI,Ri,UA,wt,Dt,Ue,zI,iB,IB,Ie,KA,SQ,SB,wr,dn,NA,YA,St,Ui,nA,Ne,gB,sB,xC,_I,TA,Dr,$I,BB,Ag,Sr,mr,yr,fr,ln,ge,Ni,WC,pr,tg,be,eg,vt,ig,se,Ig,gg,sg,OC,VC,ZC,Fr,Je,CB,Kt,bA,bi,gt,Gr,hg,kr,_C,$,QB,oB,nB,Me,Qg,Rr,Ur,$C,Li,zA,Ji,og,Nr,br;const D=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")}};class p{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}}function k(i,A){if(!i)throw new Error(A)}const y=()=>{};class G{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(y)}static resolved(A){const t=new G;return t.resolve(A),t}static fromPromise(A){const t=new G;return t.promise=A,A.then(e=>{t.pending=!1,t.resolved=e},e=>{t.pending=!1,t.reject(e)}),t}}class L{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 Z(i){const A=new z(i);return[A,A]}class z{constructor(A){n(this,Wt);n(this,zi,new G);n(this,at);n(this,kg,!1);a(this,Wt,new L(A))}isFull(){return s(this,Wt).isFull()}close(){var A;(A=s(this,at))==null||A.resolve(),a(this,kg,!0)}abort(A){var t,e;(t=s(this,at))==null||t.promise.catch(y),(e=s(this,at))==null||e.reject(A)}push(A){return r(this,null,function*(){var t;s(this,Wt).isFull()&&(yield s(this,zi).promise),s(this,Wt).push(A),(t=s(this,at))==null||t.resolve(),a(this,at,new G)})}pop(){return r(this,null,function*(){var A;for(;!(s(this,kg)&&s(this,Wt).isEmpty());){const t=s(this,Wt).pop();if(t)return s(this,zi).resolve(),a(this,zi,new G),t;s(this,at)||a(this,at,new G),yield(A=s(this,at))==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}}Wt=new WeakMap,zi=new WeakMap,at=new WeakMap,kg=new WeakMap;function QA(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 q(i){return typeof BigInt=="function"?BigInt(i):i}class _{constructor(A,t=0){n(this,Rg);n(this,Ft);n(this,Et);I(this,"position",()=>s(this,Et));I(this,"peekBit",()=>this.getBit(s(this,Ft),s(this,Et)));I(this,"readBit",()=>{const A=this.peekBit();return ft(this,Et)._++,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,Et)._++)?1:0);return t});I(this,"remainingBits",()=>s(this,Ft).byteLength*8-s(this,Et));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,Et)._++)===0;)A++;let t=1<<A;for(let e=A-1;e>=0;e--)t|=this.getBit(s(this,Ft),ft(this,Et)._++)<<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});a(this,Rg,A),a(this,Ft,new Uint8Array(s(this,Rg))),a(this,Et,t)}bytes(){return s(this,Ft)}}Rg=new WeakMap,Ft=new WeakMap,Et=new WeakMap;function ot(){const i=self.MediaSource,A=self.ManagedMediaSource;return i!=null?i:A}const hA=new RegExp("(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"),DA=navigator.userAgent.toLowerCase(),mB=hA.test(DA),yB=()=>{const i=document.createElement("video");return i.canPlayType("application/vnd.apple.mpegURL")!==""||i.canPlayType("audio/mpegurl")!==""},mQ=()=>{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},VA=()=>DA.indexOf("CrKey")!==-1,Ti=()=>navigator.platform==="MacIntel"&&navigator.maxTouchPoints===0,pA=()=>navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,dg=()=>DA.indexOf("iphone")>=0&&DA.indexOf("like iphone")<0||DA.indexOf("ipad")>=0&&DA.indexOf("like ipad")<0||DA.indexOf("ipod")>=0&&DA.indexOf("like ipod")<0||pA(),Lr=()=>{var i,A;return pA()?!1:(A=(i=ot())==null?void 0:i.isTypeSupported('audio/mp4; codecs="opus"'))!=null?A:!1},Jr=()=>/^(?!.*chrome).*safari/i.test(DA);function Mr(){var i,A;if(/(iPhone|iPod|iPad)/i.test(DA))return(A=(i=DA==null?void 0:DA.match(/OS [\d_]+/i))==null?void 0:i[0])==null?void 0:A.substring(3).split("_").map(t=>parseInt(t))[0]}function Hr(){var i,A;if(/^((?!chrome|android).)*safari/i.test(DA))return(A=(i=DA.match(/version\/([\d.]+)/))==null?void 0:i[1])==null?void 0:A.split(".").map(t=>parseInt(t))[0]}const yQ=()=>{var t,e;const i=!!ot();let A=!1;return i&&(A=Lr()),{isMobile:mB,supportsMp4Opus:A,supportsMediaSource:i,supportsHls:yB(),supportsWebAssembly:mQ(),platform:{iosVersion:(t=Mr())!=null?t:Number.MAX_SAFE_INTEGER,safariVersion:(e=Hr())!=null?e:Number.MAX_SAFE_INTEGER,isIpadOS:pA(),isMacOS:Ti(),isIOS:dg()}}},fQ=(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 Pi{constructor(A){n(this,lA);n(this,Ot);n(this,Ee);a(this,Ot,A),a(this,Ee,new DataView(A.buffer,A.byteOffset,A.byteLength)),a(this,lA,0)}position(){return s(this,lA)}byteOffset(){return s(this,Ot).byteOffset+s(this,lA)}buffer(){return s(this,Ot)}remaining(){return s(this,Ot).length-s(this,lA)}readUint8(){const A=s(this,Ee).getUint8(s(this,lA));return a(this,lA,s(this,lA)+1),A}readUint24(){const A=s(this,Ee).getUint32(s(this,lA))>>8&16777215;return a(this,lA,s(this,lA)+3),A}readUint16(){const A=s(this,Ee).getUint16(s(this,lA));return a(this,lA,s(this,lA)+2),A}readUint32(){const A=s(this,Ee).getUint32(s(this,lA));return a(this,lA,s(this,lA)+4),A}readUint64(){const A=fQ(s(this,Ot),s(this,lA),s(this,lA)+7);return a(this,lA,s(this,lA)+8),A}readBytes(A){const t=s(this,Ot).subarray(s(this,lA),s(this,lA)+A);return a(this,lA,s(this,lA)+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))}}lA=new WeakMap,Ot=new WeakMap,Ee=new WeakMap;class qr{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}}}class xi{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 Wi=i=>i.reduce((A,t)=>A+t,0)/i.length,oe=i=>({last:i[i.length-1]||0,average:i.length===0?0:Wi(i),max:i.length===0?0:Math.max(...i),min:i.length===0?0:Math.min(...i)}),vr=i=>{let A=0,t=0,e=0,g=0,B=0;for(let E=0;E<i.length;E++){const{x:c,y:h}=i[E];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=Math.pow((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:E=>C*(i.length+E)+Q}};class Kr{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 L(A)}get total(){return this._total}get average(){return this.rates.isEmpty()?0:Wi(this.rates.items())}get minMaxAverage(){return oe(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 $A{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,un=FQ*1e3,GQ=(i,A,t)=>i%A===0?i/A:(i/A).toFixed(t),Yr=(i,A=1)=>i>=un?`${GQ(i,un,A)} Gbit/s`:i>=FQ?`${GQ(i,FQ,A)} Mbit/s`:i>=pQ?`${GQ(i,pQ,A)} Kbit/s`:`${i} bit/s`,Tr=({width:i,height:A})=>`${i}x${A}`,Pr=i=>i%1e3===0?`${i/1e3} kHz`:i>1e3?`${(i/1e3).toFixed(1)} kHz`:`${i} Hz`,wn=["off","error","warn","info","debug","trace"],xr={OFF:"off"},re=class re{constructor({context:A,logLevel:t,debug:e}){n(this,je,new Map);n(this,Ug,"");n(this,ze,!1);n(this,_i,"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)=>{});a(this,Ug,A),a(this,_i,t),a(this,ze,e||!1),this.setLevel(t),this.setDebug(s(this,ze))}setDebug(A){a(this,ze,A);for(const[t,e]of s(this,je))e.setDebug(A);A?(this.table=console.table.bind(console),this.count=console.count.bind(console)):(this.table=()=>{},this.count=()=>{})}setLevel(A){a(this,_i,A);for(const[e,g]of s(this,je))g.setLevel(A);const t=wn.indexOf(A);for(const[e,g]of wn.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,Ug)):this[g]=()=>{})}createContext(A){const t=s(this,je).get(A);if(!t){const e=new re({context:`${A}`,logLevel:s(this,_i),debug:s(this,ze)});return s(this,je).set(A,e),e}return t}static get(){return s(re,$i)||a(re,$i,new re({context:"Vindral",logLevel:"off"})),s(re,$i)}};je=new WeakMap,Ug=new WeakMap,ze=new WeakMap,_i=new WeakMap,$i=new WeakMap,n(re,$i);let kA=re;function xA(i){const A=kA.get().createContext(i.context);return function(e,g){const B=String(g.name);function C(...Q){i.enter&&A[i.enter](`Enter '${B}'`,S({},Q));try{const o=e.call(this,...Q);return o instanceof Promise?o.then(E=>{i.return&&A[i.return](`Return '${B}'`,E)}).catch(E=>{i.error&&A[i.error](`Error '${B}'`,E)}):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 Dn(){return typeof Symbol.dispose!="symbol"&&Object.defineProperty(Symbol,"dispose",{value:Symbol.for("dispose")}),Symbol.dispose}class Wr{constructor(A,t){n(this,Ng);I(this,"value");I(this,"unlocker");this.value=A,this.unlocker=t}unlocked(){var A;return(A=this.unlocker)==null?void 0:A.promise}[Dn()](){d(this,Ng,Qn).call(this)}[Symbol.dispose](){d(this,Ng,Qn).call(this)}}Ng=new WeakSet,Qn=function(){this.unlocker.resolve(this.value)};class Or{constructor(A){n(this,_e);n(this,$e,new G);a(this,_e,A),s(this,$e).resolve(A)}unsafeValue(){return s(this,_e)}isLocked(){return s(this,$e).pending}lock(){return r(this,null,function*(){const A=new G;A.promise.then(e=>{a(this,_e,e)}).catch(y);const t=s(this,$e).promise.then(()=>A);return a(this,$e,A),yield t,new Wr(s(this,_e),A)})}}_e=new WeakMap,$e=new WeakMap;class HA{constructor(A){n(this,tt);n(this,rt);a(this,tt,A),a(this,rt,new G)}isClosed(){var A;return!((A=s(this,rt))!=null&&A.pending)}current(){return s(this,tt)}value(){var A;return[s(this,tt),(A=s(this,rt))==null?void 0:A.promise]}update(A){var t;if(!((t=s(this,rt))!=null&&t.pending))throw new Error("ObservableValue is closed");a(this,tt,A instanceof Function?A(s(this,tt)):A),s(this,rt).resolve(s(this,tt)),a(this,rt,new G)}close(){var A;(A=s(this,rt))==null||A.resolve(s(this,tt)),a(this,rt,void 0)}waitFor(A){return r(this,null,function*(){if(A(s(this,tt)))return s(this,tt);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 Qe(this,null,function*(){for(;;){const[A,t]=this.value();if(yield A,!t)return;yield new aA(t)}})}}tt=new WeakMap,rt=new WeakMap;const Sn=(i,A)=>{const t=S({},i);return typeof t!="object"||A.forEach(e=>{delete t[e]}),t},Ke=(i,A=Date.now())=>{const t=i.length;if(t>0){const e=t-1,g=i[e];g.end||(g.end=A)}},Oi=(i,A=Date.now())=>{Ke(i),i.push({start:A})},Vi=i=>i.reduce((A,t)=>{var e;return A+(((e=t.end)!=null?e:Date.now())-t.start)},0),mn=(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),lC=class lC{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(lC,"create",()=>new lC);let RA=lC;function yn(i){try{return i()}catch(A){return A}}const fn=i=>{try{return JSON.parse(i)}catch(A){return}},pn=()=>{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("")},Ye=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))}),Vr=(i,A)=>r(null,null,function*(){throw yield i,new Error(A)});function Fn(i){return!(typeof i.edges[0]=="string"||i.channels[0]&&!("catalog"in i.channels[0]))}function Gn(i){return i.tracks.filter(A=>!!A.codec).filter(A=>RQ(A.codec||"")).map((A,t)=>{const e=A.codec,g=A.bitrate;k(e,"codec is required"),k(g!=null,"bitrate is required");const B=RQ(e);if(k(B,"codec is required"),D(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 D(B)==="text"?{track:A,id:t,bitRate:0,codec:B,kind:"subtitles",codecString:e,label:A.label,language:A.language}:(k(A.width,"width is required"),k(A.height,"width is required"),k(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)}function RQ(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"}const Te=i=>"width"in i&&typeof i.width=="number",Pe=i=>"sampleRate"in i&&typeof i.sampleRate=="number",xe=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"}},ne=()=>Number.MAX_SAFE_INTEGER,fB=()=>({width:Number.MAX_SAFE_INTEGER,height:Number.MAX_SAFE_INTEGER}),kn=i=>!(typeof i!="object"||i===null||!("type"in i)),Zr=i=>i?{Authorization:`Bearer ${i}`}:void 0,Xr=(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){}},jr=i=>typeof i=="object"&&i!==null&&"message"in i;class zr extends Error{constructor({status:t,url:e,body:g}){const B=fn(g),C=jr(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 _r=i=>typeof i.status=="number",$r=()=>{if(!(typeof window=="undefined"||typeof document=="undefined"))return Xr(window.location,document)},Ac=i=>{const A=$r();if(!A||i.searchParams.has("parentOrigin"))return i;const t=new URL(i.toString());return t.searchParams.append("parentOrigin",A),t},Rn=(i,A)=>r(null,null,function*(){const t=Ac(i),e=yield fetch(t.toString(),S({mode:"cors"},A));if(!e.ok)throw new zr({status:e.status,url:t,body:yield e.text()});return e}),UQ=(i,A)=>r(null,null,function*(){return yield(yield Rn(i,S({},A))).json()}),Un=(i,A)=>r(null,null,function*(){return Rn(i,S({method:"POST"},A))});function tc(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 Nn={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 bn{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(Nn.lbConnect(A),this.baseUrl),C=this.getAuthToken(g),Q=yield UQ(B,{headers:this.getHeaders(C)});if(tc(Q)){const o=Q.channels.map(E=>{const c=this.toChannel(E,g),h=Gn(E.catalog);return V(S(S({},E),c),{renditions:h})});return V(S({},Q),{channels:o})}else{const o=Q.channels.map(E=>{const c=this.toChannel(E,g);return S(S({},E),c)});return V(S({},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 UQ(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 UQ(e,{headers:this.getHeaders(g)}),C=Array.isArray(B)?B:B.channels;return this.toChannels(C,t,g)})}getHeaders(A){var e;return(e=Zr(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(Nn.thumbnails(t,e),this.baseUrl),Q=B.map(o=>new URL(`?channelId=${A.channelId}&width=${o.width}&height=${o.height}${ec(t,e)}`,C).toString());return{channelId:A.channelId,name:A.name,isLive:A.isLive,thumbnailUrls:Q}}}const ec=(i,A)=>A?i.channelGroupId?`&channelGroupId=${i.channelGroupId}&auth.token=${A}&auth.type=jwt`:`&auth.token=${A}&auth.type=jwt`:"";class Ln extends $A{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 ic={sizeBasedResolutionCapEnabled:!0,pictureInPictureEnabled:!0,abrEnabled:!0,burstEnabled:!1,mseEnabled:!0,mseOpusEnabled:!1,muted:!1,minBufferTime:1500,maxBufferTime:1500,logLevel:xr.OFF,maxSize:fB(),maxVideoBitRate:ne(),maxAudioBitRate:ne(),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},Jn="connection_failed",Mn="connection_failed_will_not_attempt_again",Hn="authentication_error",qn="authentication_expired",vn="channel_not_found",Kn="no_incoming_data_error",Yn="connection_inactivity",Ic="missing_init_segment",gc="no_track_context",sc="invalid_track_context_state",Tn="disconnected_by_edge",Bc="decoder_error",Cc="audio_player_error",Qc="media_source_error",oc="webgl_context_lost_error",nc="access_forbidden",ac="channel_switch_failed",Ec="drm_error";class W 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(S({},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 rc=(i,A)=>new W("MediaElement Error",{isFatal:i,code:"media_element_error",source:A},{mediaErrorCode:A.code}),Pn=(i,A)=>new W("Decoder Error",{isFatal:i,code:Bc,source:A,type:"internal"}),xn=(i,A)=>new W("Audio Player Error",{isFatal:i,code:Cc,source:A,type:"internal"}),cc=(i,A)=>new W(`No init segment for rendition id ${i} for channel ${A}`,{isFatal:!1,code:Ic,type:"internal"}),Wn=(i,A,t,e)=>new W("MediaSource Error",{isFatal:i,code:Qc,source:A,type:"internal"},{type:e,consecutiveErrorsCount:t}),pB=(i,A)=>new W(`No track context for ${i}${A?`, rendition id ${A}`:""}`,{isFatal:!1,code:gc,type:"internal"}),hc=(i,A)=>new W(`Track context is in an invalid state for ${i}${A?`, rendition id ${A}`:""}`,{isFatal:!1,code:sc,type:"internal"}),dc=()=>new W("Web Audio Context resume timeout",{isFatal:!1,code:"web_audio_context_resume_timeout"}),lg=i=>new W("Disconnected From Edge Server",{type:"external",source:i,isFatal:!1,code:Tn}),FB=i=>new W("Authentication Failed",{isFatal:!0,code:Hn,source:i}),lc=i=>new W("Authentication Expired",{isFatal:!0,code:qn,source:i}),uc=(i,A)=>new W("Connection closed due to inactivity",{isFatal:!1,code:Yn,source:A,type:i}),On=(i,A)=>new W("Channel not found",{isFatal:!1,code:vn,source:A,type:i}),wc=i=>new W("No Incoming Data",{isFatal:!1,code:Kn,source:i}),Dc=i=>new W("Connection attempt failed",{isFatal:!1,code:Jn,source:i}),Vn=()=>new W("Connection failed - no more reconnect attempts",{isFatal:!0,code:Mn}),Sc=i=>new W("WebGL Context Lost",{isFatal:!1,code:oc,source:i,type:"internal"}),Zn=i=>new W(i,{isFatal:!0,code:nc}),Xn=i=>new W(`Channel switch to '${i}' failed`,{isFatal:!1,code:ac}),jn=(i,A=!1,t)=>new W(i,{isFatal:A,code:Ec,source:t}),zn=(i,A)=>i&&typeof i=="object"&&A in i,_n=i=>!(typeof i!="object"||!zn(i,"channelId")||typeof i.channelId!="string"||!zn(i,"url")||typeof i.url!="string"||i.channelId.length===0||i.url.length===0),mc=i=>{if(!_n(i))throw new W("Invalid options",{isFatal:!0,code:"invalid_options"});const A=S({},i);return Object.keys(A).forEach(t=>{const e=A;typeof e[t]=="undefined"&&delete e[t]}),A},$n={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"'}]},yc={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}},Aa=(i,A)=>r(null,null,function*(){return navigator.requestMediaKeySystemAccess(i,[A]).catch(()=>{})}),ta=(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(S({},c),{robustness:Q,contentType:B?`${g==="audioCapabilities"?"audio/mp4":"video/mp4"}; codecs="${B}"`:c.contentType}));if(!(yield Aa(i,{initDataTypes:A,[g]:o})))break;C=o}return C}),fc=(i,A,t,e)=>r(null,null,function*(){const{keySystem:g,supportedConfig:B}=yc[i],{initDataTypes:C,videoCapabilities:Q,audioCapabilities:o}=B,E=e==null?void 0:e[i],c=(E==null?void 0:E.videoRobustness)||$n[i],h=(E==null?void 0:E.audioRobustness)||$n[i],[l,m]=yield Promise.all([ta(g,C,Q,c,"videoCapabilities",A),ta(g,C,o,h,"audioCapabilities",t)]);return!l&&!m?void 0:yield Aa(g,{initDataTypes:C,videoCapabilities:l,audioCapabilities:m})}),pc=(i,A,t,e)=>r(null,null,function*(){let g;for(const B of i)if(g=yield fc(B,A,t,e),g)return{keySystem:B,mediaKeySystemAccess:g}});class GB{constructor(A,t,e,g){I(this,"keySystem");I(this,"licenseServerUrl");I(this,"certificate");I(this,"headers",{});I(this,"queryParams",{});n(this,Ai);n(this,ti);a(this,Ai,t),this.keySystem=A,this.licenseServerUrl=e,this.certificate=g}get statistics(){return{keySystem:s(this,Ai).keySystem,licenseServerUrl:this.licenseServerUrl,mediaKeySystemConfiguration:s(this,Ai).getConfiguration()}}getMediaKeys(){return r(this,null,function*(){return s(this,ti)?s(this,ti):(a(this,ti,yield s(this,Ai).createMediaKeys()),s(this,ti))})}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:S({"Content-Type":"application/octet-stream"},this.headers)});if(!e.ok)throw new Error(`Failed to fetch license: ${e.statusText}`);return yield e.arrayBuffer()})}}Ai=new WeakMap,ti=new WeakMap;function ea(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 Fc(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 Gc(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 kc extends GB{constructor(t,e){super("clearkey",t,"");n(this,bg);a(this,bg,e)}handleLicenseRequest(t){const e=new Uint8Array(t),g=String.fromCharCode(...e),B=JSON.parse(g),C=[];for(let E=0;E<B.kids.length;E++){const c=B.kids[E];if(c){const h=ea(c).toLowerCase(),l=s(this,bg)[h];l&&C.push({kty:"oct",alg:"A128KW",kid:c,k:Fc(l)})}}const Q=JSON.stringify({keys:C,type:B.type});return new TextEncoder().encode(Q)}}bg=new WeakMap;class Rc extends GB{constructor(A,t,e){super("fairplay",A,t,e)}}const Uc=i=>{var Q,o,E,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 f=(Q=h[m])==null?void 0:Q.childNodes[0],U=(o=l[m])==null?void 0:o.childNodes[0];f!=null&&f.nodeValue&&U&&U.nodeValue&&(g[f.nodeValue]=U.nodeValue)}}const B=t.getElementsByTagName("Challenge")[0];let C;return B&&((E=B.childNodes[0])!=null&&E.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 Nc extends GB{constructor(A,t){super("playready",A,t)}requestLicense(A){return r(this,null,function*(){k(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=Uc(A),g=yield fetch(t,{method:"POST",headers:S(S({},e.headers),this.headers),body:e.message});if(!g.ok)throw new Error(`Failed to fetch license: ${g.statusText}`);return yield g.arrayBuffer()})}}class bc extends GB{constructor(A,t){super("widevine",A,t)}}const Lc=5e3;class ia{constructor(A,t,e={}){n(this,uA);n(this,tA);n(this,ei);n(this,Vt);n(this,ct,new G);n(this,Gt);n(this,FA);n(this,ce,new Map);n(this,he);n(this,uC,yQ());n(this,AI);n(this,Lg,A=>{if(s(this,tA).info("Received DRM data",{drmData:A}),window.clearTimeout(s(this,AI)),s(this,FA)){const t=d(this,uA,XE).call(this,A)[s(this,FA).keySystem];t&&(s(this,FA).licenseServerUrl=t)}s(this,ct).resolve(A)});n(this,Jg,A=>{s(this,tA).info("Encrypted event received",{event:A}),d(this,uA,PE).call(this,A)});n(this,wC,A=>{var B,C;s(this,tA).debug("Session message received",{event:A});const t=A.target,e=A.message;if(!s(this,ce).get(t)){s(this,tA).error("No active session found for event",{event:A});return}s(this,tA).debug("Requesting license for session",{sessionId:t.sessionId,licenseServerUrl:(B=s(this,FA))==null?void 0:B.licenseServerUrl}),(C=s(this,FA))==null||C.requestLicense(e).then(Q=>{s(this,tA).debug("License received for session",{sessionId:t.sessionId}),t.update(Q).catch(o=>{d(this,uA,lB).call(this,{message:"Failed to update session with license",isFatal:!1,error:o})})}).catch(Q=>{d(this,uA,lB).call(this,{message:"Failed to request license",isFatal:!1,error:Q})})});n(this,DC,A=>{const t=A.target;s(this,tA).debug("Key status changed for session",{sessionId:t.sessionId}),t.keyStatuses.forEach((e,g)=>{const B=ea(window.btoa(String.fromCharCode(...new Uint8Array(g))));s(this,tA).debug("Key status",{base64kid:B,status:e})})});n(this,SC,A=>r(this,null,function*(){const t=d(this,uA,ZE).call(this,A);s(this,tA).debug("Prioritized key system list",{keySystemList:t});const e=yield pc(t,A.videoCodec,A.audioCodec,{widevine:s(this,Gt).widevine,playready:s(this,Gt).playready});if(!e)return s(this,tA).warn("No supported key system found"),null;s(this,tA).debug("Supported key system found",e.mediaKeySystemAccess.getConfiguration());const{keySystem:g,mediaKeySystemAccess:B}=e;let C=null;return g==="clearkey"?(k(A.clearkeys,"No clearkeys found"),C=new kc(B,A.clearkeys)):g==="playready"?(k(A.playreadyLicenseUrl,"No playreadyLicenseUrl found"),C=new Nc(B,A.playreadyLicenseUrl)):g==="widevine"?(k(A.widevineLicenseUrl,"No widevineLicenseUrl found"),C=new bc(B,A.widevineLicenseUrl)):g==="fairplay"&&(k(A.fairplayLicenseUrl,"No fairplayLicenseUrl found"),k(A.fairplayCertificate,"No fairplayCertificate found"),C=new Rc(B,A.fairplayLicenseUrl,A.fairplayCertificate)),C&&(C.headers=s(this,Gt).headers||{},C.queryParams=s(this,Gt).queryParams||{}),C}));a(this,ei,A),a(this,tA,t),a(this,Gt,e),s(this,ei).on("received drm data",s(this,Lg))}static isSupported(){return!!navigator.requestMediaKeySystemAccess}attach(A){a(this,Vt,A),s(this,tA).info("Media element attached"),s(this,Vt).addEventListener("encrypted",s(this,Jg))}getStatistics(){var A,t;return!s(this,ct).resolved&&!((A=s(this,FA))!=null&&A.statistics)?null:S(S({},s(this,ct).resolved),(t=s(this,FA))==null?void 0:t.statistics)}unload(){var A;s(this,tA).info("Unloading EncryptedMediaExtensions"),s(this,ei).off("received drm data",s(this,Lg)),(A=s(this,Vt))==null||A.removeEventListener("encrypted",s(this,Jg)),s(this,ce).forEach((t,e)=>{e.close()}),s(this,ce).clear(),a(this,he,void 0),a(this,FA,void 0)}set headers(A){s(this,Gt).headers=A,s(this,FA)&&(s(this,FA).headers=A)}set queryParams(A){s(this,Gt).queryParams=A,s(this,FA)&&(s(this,FA).queryParams=A)}onChannelSwitch(){if(!s(this,ct).resolved){s(this,tA).debug("DRM is not used, skipping channel switch handling");return}Jr()&&s(this,uC).platform.safariVersion<18&&d(this,uA,lB).call(this,{message:"DRM channel switch not supported on Safari < 18",isFatal:!0}),window.clearTimeout(s(this,AI));const A=s(this,ct).resolved;a(this,ct,new G),a(this,AI,window.setTimeout(()=>{s(this,ct).resolve(A)},Lc))}}tA=new WeakMap,ei=new WeakMap,Vt=new WeakMap,ct=new WeakMap,Gt=new WeakMap,FA=new WeakMap,ce=new WeakMap,he=new WeakMap,uC=new WeakMap,AI=new WeakMap,Lg=new WeakMap,Jg=new WeakMap,uA=new WeakSet,PE=function(A){return r(this,null,function*(){try{yield d(this,uA,xE).call(this),s(this,tA).debug("Media keys initialization completed"),yield d(this,uA,WE).call(this,A.initData,A.initDataType)}catch(t){d(this,uA,lB).call(this,{message:"Failed to handle encrypted event",isFatal:!0,error:t})}})},xE=function(){return r(this,null,function*(){var t;s(this,tA).debug("Initializing media keys");const A=yield s(this,ct).promise;if((t=s(this,Vt))!=null&&t.mediaKeys){s(this,tA).debug("Media keys already set on media element");return}if(s(this,he)){s(this,tA).debug("Media keys initialization already in progress, waiting for completion"),yield s(this,he);return}a(this,he,r(this,null,function*(){const e=yield s(this,SC).call(this,A);s(this,tA).debug("CDM obtained",{cdm:e}),k(s(this,Vt),"No media element found"),k(e,"No CDM found");const g=yield e.getMediaKeys();e.certificate&&(yield d(this,uA,VE).call(this,g,e.certificate)),s(this,tA).debug("Setting media keys on media element"),yield s(this,Vt).setMediaKeys(g),a(this,FA,e)})),yield s(this,he)})},WE=function(A,t){return r(this,null,function*(){k(s(this,FA),"No CDM manager found");const e=yield s(this,FA).getMediaKeys();if(!A||!d(this,uA,OE).call(this,A)){s(this,tA).debug("Duplicate initData, no need to create new session",{initData:A});return}const g=e.createSession();s(this,tA).debug("Creating new session",{session:g}),g.addEventListener("keystatuseschange",s(this,DC)),g.closed.then(B=>{s(this,tA).info("Session is closed",{reason:B})}),g.addEventListener("message",s(this,wC)),s(this,ce).set(g,A),s(this,tA).debug("Generating request for session",{session:g,initDataType:t,initData:A}),yield g.generateRequest(t,A)})},OE=function(A){for(const[t,e]of s(this,ce))if(Gc(A,e))return!1;return!0},wC=new WeakMap,DC=new WeakMap,VE=function(A,t){return r(this,null,function*(){try{s(this,tA).debug("Setting server certificate",{certificate:t}),(yield A.setServerCertificate(t))||s(this,tA).warn("Server certificates are not supported by the CDM.")}catch(e){s(this,tA).error("Failed to set server certificate",{error:e})}})},lB=function(A){const{message:t,isFatal:e,error:g}=A;s(this,tA).error(t,{error:g}),s(this,ei).emit("error",jn(t,e,g))},SC=new WeakMap,ZE=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},XE=function(A){return{fairplay:A.fairplayLicenseUrl,playready:A.playreadyLicenseUrl,widevine:A.widevineLicenseUrl,clearkey:void 0}};const Jc=7,Mc=8,Hc=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},qc=i=>Hc(new DataView(i,0))!==0,Ia=(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}}},vc=i=>i&31,Kc=(i,A)=>{const t=new DataView(i,0);let e=Ia(t);for(;e;){const{position:g,nalPrefixSize:B}=e,C=Ia(t,g+4),Q=C?C.position-g-B:void 0;if(!A(new DataView(i,g+B,Q),B))return;e=C}},ga=i=>{const A=[],t=[];if(!qc(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 Kc(i,e=>{const g=e.byteOffset+e.byteLength;switch(vc(e.getUint8(0))){case Mc:t.push(e.buffer.slice(e.byteOffset,g));break;case Jc:A.push(e.buffer.slice(e.byteOffset,g));break}return!0}),{sequenceParameterSets:A,pictureParameterSets:t}},Yc=i=>{var f;const A=new DataView(i),t=A.getUint8(1),e=A.getUint8(2),g=A.getUint8(3),B=new _(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 b=0;b<(C!=3?8:12);b++)if(B.readBit()){const N=b<6?16:64;let v=0,T=8,P=8;for(let X=0;X<N;X++)P!=0&&(v=B.readSignedExpGolomb(),P=(T+v+256)%256),T=P==0?T:P}}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(),E=B.readUnsignedExpGolomb(),c=B.readBit();c===0&&B.readBit(),B.readBit();let h=o+1,l=E+1;if(l*=2-c,l*=16,h*=16,B.readBit()){const U=C==1?1:0,Y=1<<(C==1||C==2?1:0),N=2-c<<U,v=B.readUnsignedExpGolomb()*Y,T=B.readUnsignedExpGolomb()*Y,P=B.readUnsignedExpGolomb()*N,X=B.readUnsignedExpGolomb()*N;h-=v+T,l-=P+X}let m={numerator:1,denumerator:1};return B.readBit()&&B.readBit()&&(m=(f=Tc[B.readBits(8)])!=null?f:{numerator:0,denumerator:0}),{width:h,height:l,pixelAspectRatio:m,profileIdc:t,constraintFlags:e,levelIdc:g}},Tc=[{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}],Pc=184549376;function xc(i){const A=new Pi(i),t=Wc(A);(t.flags&Pc)!==0&&Oc(A);const e=Vc(A);if(String.fromCharCode(...e.frameId)==="TXXX"){const B=new Pi(A.readBytes(e.size));return{header:t,txx:Zc(B)}}}function Wc(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 Oc(i){const A=i.readUint32();return i.readBytes(A-4),{}}function Vc(i){const A=i.readBytes(4),t=i.readUint32(),e=i.readUint16();return{frameId:A,size:t,flags:e}}function Zc(i){const A=i.readUint8(),t=i.readUtf8String(),e=i.readUtf8String();return{encoding:A,description:t,value:e}}function sa(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 Xc(i,A){const t=sa(A),e=new Pi(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 Pt(i){const A=i.readUint8(),t=i.readUint24();return{version:A,flags:t}}const tI=class tI{constructor({timescale:A,presentationTime:t,presentationTimeDelta:e,schemeIdUri:g,value:B,eventDuration:C,id:Q,data:o}){I(this,"type",tI.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}=Pt(A);switch(t){case 1:{const e=A.readUint32(),g=A.readUint64(),B=A.readUint32(),C=A.readUint32(),Q=A.readUtf8String(),o=A.readUtf8String(),E=A.remaining(),c=A.readBytes(E);return new tI({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(),E=A.remaining(),c=A.readBytes(E);return new tI({timescale:B,presentationTimeDelta:C,schemeIdUri:e,value:g,eventDuration:Q,id:o,data:c})}default:throw new Error(`unsupported version ${t}`)}}};I(tI,"type","emsg");let kB=tI;const Mg=class Mg{constructor(A){I(this,"type",Mg.type);I(this,"data");this.data=A}static decodeData(A){const t=A.readRemaining();return new Mg(t)}};I(Mg,"type","mdat");let RB=Mg;const Hg=class Hg{constructor(A,t,e){I(this,"type",Hg.type);I(this,"extra");I(this,"byteOffset");I(this,"baseMediaDecodeTime");this.extra=A,this.byteOffset=t,this.baseMediaDecodeTime=e}static decodeData(A){const t=Pt(A),e=A.byteOffset();let g=0;return t.version===1?g=A.readUint64():g=A.readUint32(),new Hg(t,e,g)}};I(Hg,"type","tfdt");let UB=Hg;const rA=class rA{constructor(A,t,e){I(this,"type",rA.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=rA.FLAG_SAMPLE_FLAG_IS_NON_SYNC|rA.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}=Pt(A),e=A.readUint32();let g,B;t&rA.TRUN_DATA_OFFSET&&(g=A.readUint32()),t&rA.TRUN_FIRST_SAMPLE_FLAGS&&(B=A.readUint32());const C=new rA(e,g,B);for(let Q=0;Q<e;Q++)t&rA.SAMPLE_DURATION&&C.sampleDurations.push(A.readUint32()),t&rA.SAMPLE_SIZE&&C.sampleSizes.push(A.readUint32()),t&rA.SAMPLE_FLAGS&&C.sampleFlags.push(A.readUint32()),t&rA.SAMPLE_CTS&&C.sampleCts.push(A.readUint32());return C}};I(rA,"TRUN_DATA_OFFSET",1),I(rA,"TRUN_FIRST_SAMPLE_FLAGS",4),I(rA,"SAMPLE_DURATION",256),I(rA,"SAMPLE_SIZE",512),I(rA,"SAMPLE_FLAGS",1024),I(rA,"SAMPLE_CTS",2048),I(rA,"FLAG_SAMPLE_FLAG_IS_NON_SYNC",65536),I(rA,"FLAG_SAMPLE_DEPENDS_NO",33554432),I(rA,"FLAG_SAMPLE_DEPENDS_YES",16777216),I(rA,"type","trun");let ug=rA;const jc=1,zc=2,_c=8,$c=16,Ah=32,qg=class qg{constructor(A,t,e,g){I(this,"type",qg.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=Pt(A);let e,g,B;return A.readUint32(),(t.flags&jc)>0&&A.readUint64(),(t.flags&zc)>0&&A.readUint32(),(t.flags&_c)>0&&(e=A.readUint32()),(t.flags&$c)>0&&(g=A.readUint32()),(t.flags&Ah)>0&&(B=A.readUint32()),new qg(t,e,g,B)}};I(qg,"type","tfhd");let NB=qg;const vg=class vg{constructor(A,t,e){I(this,"type",vg.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=nt(A);B instanceof NB&&(t=B),B instanceof UB&&(e=B),B instanceof ug&&(g=B)}return new vg(t,e,g)}};I(vg,"type","traf");let bB=vg;const Kg=class Kg{constructor(A){I(this,"type",Kg.type);I(this,"traf");this.traf=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=nt(A);e instanceof bB&&(t=e)}if(!t)throw new Error("No traf found");return new Kg(t)}};I(Kg,"type","moof");let LB=Kg;const Yg=class Yg{constructor(){I(this,"type",Yg.type)}static decodeData(A){return new Yg}};I(Yg,"type","mvhd");let JB=Yg;const Tg=class Tg{constructor(A){I(this,"type",Tg.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){Pt(A),A.readUint32();const t=String.fromCharCode(...A.readBytes(4));return new Tg(t)}};I(Tg,"type","hdlr");let MB=Tg;const eI=class eI{constructor(A,t,e,g){I(this,"type",eI.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}=Pt(A);if(t===1){const Q=A.readUint64(),o=A.readUint64(),E=A.readUint32(),c=A.readUint64();return new eI(Q,o,E,c)}const e=A.readUint32(),g=A.readUint32(),B=A.readUint32(),C=A.readUint32();return new eI(e,g,B,C)}};I(eI,"type","mdhd");let HB=eI;const Pg=class Pg{constructor(A,t,e,g){I(this,"type",Pg.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){Pt(A);const t=A.readUint32();let e,g,B,C;for(let Q=0;Q<t;Q++)for(;A.remaining()>0;){const o=nt(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 Pg(g,C,B,e)}};I(Pg,"type","stsd");let qB=Pg;const xg=class xg{constructor(A){I(this,"type",xg.type);I(this,"stsd");this.stsd=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=nt(A);e instanceof qB&&(t=e)}if(!t)throw new Error("No stsd found");return new xg(t)}};I(xg,"type","stbl");let vB=xg;const Wg=class Wg{constructor(A){I(this,"type",Wg.type);I(this,"stbl");this.stbl=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=nt(A);e instanceof vB&&(t=e)}if(!t)throw new Error("No stbl found");return new Wg(t)}};I(Wg,"type","minf");let KB=Wg;const Og=class Og{constructor(A,t,e){I(this,"type",Og.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=nt(A);B instanceof MB&&(t=B),B instanceof KB&&(e=B),B instanceof HB&&(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 Og(t,e,g)}};I(Og,"type","mdia");let YB=Og;const Vg=class Vg{constructor(A,t,e,g,B,C,Q,o){I(this,"type",Vg.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=Pt(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 E=A.readUint16();A.readUint16();const c=A.readUint16();return A.readUint16(),new Vg(e,g,B,C,Q,o,E,c)}};I(Vg,"type","tkhd");let TB=Vg;const Zg=class Zg{constructor(A,t){I(this,"type",Zg.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=nt(A);g instanceof TB&&(t=g),g instanceof YB&&(e=g)}if(!t)throw new Error("No tkhd found");if(!e)throw new Error("No mdia found");return new Zg(t,e)}};I(Zg,"type","trak");let PB=Zg;const Xg=class Xg{constructor(A,t){I(this,"type",Xg.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=nt(A);g instanceof PB&&e.push(g),g instanceof JB&&(t=g)}if(!t)throw new Error("No mvhd found");return new Xg(t,e)}};I(Xg,"type","moov");let xB=Xg;const jg=class jg{constructor(A,t,e,g,B,C,Q,o){I(this,"type",jg.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,E=[];for(let l=0;l<o;l++){const m=A.readBytes(A.readUint16());E.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 jg(e,g,B,C,Q,E,h,t)}};I(jg,"type","avcC");let bQ=jg;const zg=class zg{constructor(A,t,e,g,B){I(this,"type",zg.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=nt(A);switch(Q.type){case"avcC":C=Q;break}}if(!C)throw new Error("no avcC");return new zg(C,t,e,g,B)}};I(zg,"type","avc1");let LQ=zg;const _g=class _g{constructor(){I(this,"type",_g.type)}static decodeData(A){return new _g}};I(_g,"type","dOps");let JQ=_g;const $g=class $g{constructor(A,t,e){I(this,"type",$g.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=Xc(JQ,A);return new $g(B,e,g)}};I($g,"type","Opus");let MQ=$g;const iI=class iI{constructor(A,t){I(this,"type",iI.type);I(this,"ntpTimestamp");I(this,"mediaTime");this.ntpTimestamp=A,this.mediaTime=t}date(){const[A,t]=this.ntpTimestamp,e=A*1e3+t/sn(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}=Pt(A);A.readUint32();const e=A.readUint32(),g=A.readUint32();if(t===1){const C=A.readUint64();return new iI([e,g],C)}const B=A.readUint32();return new iI([e,g],B)}};I(iI,"type","prft");let WB=iI;class th{constructor(A,t){n(this,As);n(this,ts);a(this,As,A),a(this,ts,t.readBytes(A.size))}data(){return s(this,ts)}get type(){return s(this,As).type}}As=new WeakMap,ts=new WeakMap;const eh={moov:xB,trak:PB,tkhd:TB,mvhd:JB,moof:LB,traf:bB,tfhd:NB,tfdt:UB,trun:ug,mdat:RB,mdia:YB,hdlr:MB,minf:KB,stbl:vB,mdhd:HB,stsd:qB,prft:WB,avc1:LQ,avcC:bQ,Opus:MQ,emsg:kB};function nt(i){const A=sa(i),t=eh[A.type],e=new Pi(i.readBytes(A.size));if(!t){const B=new th(A,e);return e.readRemaining(),B}const g=t.decodeData(e);return e.readRemaining(),g}function ih(i){if(i.byteLength<8)throw new Error("Buffer too small");const A=new Pi(i),t=new Map;for(;A.remaining()>0;){const B=nt(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 xB))throw new Error("moov atom not found");return{ftyp:e,moov:g}}function Ih(i){if(i.byteLength<8)throw new Error("Buffer too small");const A=new Pi(i),t=new Map,e=[];for(;A.remaining()>0;){const Q=nt(A);Q instanceof kB&&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 LB))throw new Error("moof atom not found");if(!B||!(B instanceof RB))throw new Error("mdat atom not found");if(C&&!(C instanceof WB))throw new Error("invalid prft found");return{moof:g,mdat:B,prft:C,emsgs:e}}class gh{constructor(A){n(this,es);n(this,is);a(this,es,A),a(this,is,ih(A))}rawBytes(){return s(this,es)}init(){return s(this,is)}}es=new WeakMap,is=new WeakMap;const Wo=class Wo{constructor(A,t){n(this,vA);n(this,WA);n(this,gA);a(this,vA,t),a(this,WA,A),a(this,gA,Ih(t))}clone(){return new Wo(s(this,WA),new Uint8Array(s(this,vA).buffer.slice(s(this,vA).byteOffset,s(this,vA).byteOffset+s(this,vA).byteLength)))}updateBaseMediaDecodeTime(A){const t=new DataView(s(this,vA).buffer,s(this,vA).byteOffset,s(this,vA).byteLength);if(s(this,gA).moof.traf.tfdt)if(s(this,gA).moof.traf.tfdt.baseMediaDecodeTime=A,s(this,gA).moof.traf.tfdt.extra.version===1){const e=Math.floor(A/4294967296),g=(A&4294967295)>>>0;t.setUint32(s(this,gA).moof.traf.tfdt.byteOffset-s(this,vA).byteOffset,e),t.setUint32(s(this,gA).moof.traf.tfdt.byteOffset-s(this,vA).byteOffset+4,g)}else t.setUint32(s(this,gA).moof.traf.tfdt.byteOffset-s(this,vA).byteOffset,A)}producerReferenceTime(){if(s(this,gA).prft)return s(this,gA).prft.date()}duration(){const A=s(this,gA).moof.traf.trun,t=s(this,gA).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,gA).moof.traf.tfdt)==null?void 0:t.baseMediaDecodeTime;if(!A)throw new Error("no baseMediaDecodeTime");return A}startsWithKeyframe(){var e;const A=s(this,gA).moof.traf.trun,t=(A==null?void 0:A.firstSampleFlags)||(A==null?void 0:A.sampleFlags[0])||((e=s(this,gA).moof.traf.tfhd)==null?void 0:e.defaultSampleFlags);return t?(t&ug.FLAG_SAMPLE_DEPENDS_NO)!==0:!1}compositionTimeOffset(A){var t;return(t=s(this,gA).moof.traf.trun)==null?void 0:t.sampleCts[A]}timescale(){const A=s(this,WA).init().moov.traks[0];if(!A)throw new Error("no tracks");return A.mdia.mdhd.timescale}mediaType(){var t;const A=(t=s(this,WA).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,WA)}fragment(){return s(this,gA)}samplesCount(){var A;return((A=s(this,gA).moof.traf.trun)==null?void 0:A.samplesCount)||0}sample(A){var m,f,U,b,Y,N,v,T,P,X,yA,BA,fA,Bt,w;const t=(m=s(this,WA).init().moov.traks[0])==null?void 0:m.mdia.minf.stbl.stsd.codec,e=((f=s(this,gA).moof.traf.trun)==null?void 0:f.samplesCount)||0,g=(U=s(this,gA).moof.traf.tfdt)==null?void 0:U.baseMediaDecodeTime;if(A>=e||typeof g=="undefined"||!t)return;const B=((b=s(this,gA).moof.traf.trun)==null?void 0:b.sampleDurations[A])||0,C=((Y=s(this,gA).moof.traf.trun)==null?void 0:Y.sampleDurations.slice(0,A).reduce((R,x)=>R+x,0))||0,Q=g+C,o=((N=s(this,WA).init().moov.traks[0])==null?void 0:N.mdia.mdhd.timescale)||1e3,E=((v=s(this,gA).moof.traf.trun)==null?void 0:v.sampleSizes[A])||s(this,gA).mdat.data.byteLength,c=((T=s(this,gA).moof.traf.trun)==null?void 0:T.sampleSizes.slice(0,A).reduce((R,x)=>R+x,0))||0,h=s(this,gA).mdat.data.subarray(c,c+E),l=((P=s(this,gA).moof.traf.trun)==null?void 0:P.is_sync_sample(A))||!1;if(this.mediaType()==="video"){const R=((X=s(this,WA).init().moov.traks[0])==null?void 0:X.tkhd.width)||0,x=((yA=s(this,WA).init().moov.traks[0])==null?void 0:yA.tkhd.height)||0;return{type:"video",codec:t,width:R,height:x,duration:B,isSync:l,timescale:o,timestamp:Q,data:h}}return{type:"audio",codec:t,channels:((fA=(BA=s(this,WA).init().moov.traks[0])==null?void 0:BA.mdia.minf.stbl.stsd.opus)==null?void 0:fA.channelCount)||0,sampleRate:((w=(Bt=s(this,WA).init().moov.traks[0])==null?void 0:Bt.mdia.minf.stbl.stsd.opus)==null?void 0:w.sampleRate)||0,duration:B,isSync:l,timestamp:Q,data:h,timescale:o}}rawBytes(){return s(this,vA)}};vA=new WeakMap,WA=new WeakMap,gA=new WeakMap;let HQ=Wo;class Ba{constructor(A){n(this,II);a(this,II,new gh(A))}header(){return s(this,II)}createFragment(A){return new HQ(s(this,II),A)}}II=new WeakMap;function H(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 iA={ftyp:H("ftyp"),mvhd:H("mvhd"),moov:H("moov"),trak:H("trak"),tkhd:H("tkhd"),mdia:H("mdia"),mdhd:H("mdhd"),hdlr:H("hdlr"),minf:H("minf"),vmhd:H("vmhd"),smhd:H("smhd"),dinf:H("dinf"),dref:H("dref"),stbl:H("stbl"),stsd:H("stsd"),avc1:H("avc1"),av01:H("av01"),av1C:H("av1C"),avcC:H("avcC"),esds:H("esds"),colr:H("colr"),nclx:H("nclx"),mvex:H("mvex"),trex:H("trex"),udta:H("udta"),meta:H("meta"),ilst:H("ilst"),moof:H("moof"),mfhd:H("mfhd"),traf:H("traf"),tfhd:H("tfhd"),tfdt:H("tfdt"),trun:H("trun"),mdat:H("mdat"),mp4a:H("mp4a"),Opus:H("Opus"),prft:H("prft"),dOps:H("dOps"),emsg:H("emsg")},sh=1e3,wg=H("iso6"),Ca=new Uint8Array([0,0,2,0]),Bh=[wg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([97,118,99,49]),new Uint8Array([109,112,52,49])],Ch=[wg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([97,118,48,49]),new Uint8Array([109,112,52,49])],Qh=[wg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([109,112,52,49])];class Qa{constructor(){I(this,"writer",new qr);I(this,"moofOffset",0)}}const dA=(i,A,t)=>{i.writer.writeUint32(t+8),i.writer.writeBytes(A)},wA=(i,A,t,e,g)=>{dA(i,A,t+4),i.writer.writeUint8(e),i.writer.writeUint24(g)},qQ=(i,A)=>{dA(i,iA.ftyp,wg.byteLength+Ca.byteLength+A.reduce((t,e)=>t+e.byteLength,0)),i.writer.writeBytes(wg),i.writer.writeBytes(Ca),A.forEach(t=>i.writer.writeBytes(t))},oh=Math.pow(2,32),nh=2208988800,ah=(i,A,t,e)=>{wA(i,iA.prft,20,1,0);const B=t/1e3,C=Math.floor(B),o=(B-C)*1e3*1e3*oh/1e6;i.writer.writeUint32(A),i.writer.writeUint32(C+nh),i.writer.writeUint32(o),i.writer.writeUint64(e)},Eh=(i,A,t)=>{wA(i,iA.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)},oa=i=>"sequenceParameterSets"in i,vQ=i=>"sequenceHeader"in i,We=i=>i.type=="video",Dg=i=>i.type=="audio",rh=(i,A,t)=>{const e=i.writer.position();wA(i,iA.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(Dg(A)?1:0),i.writer.writeUint16(Dg(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])),We(A)?(i.writer.writeUint32(A.width*65536),i.writer.writeUint32(A.height*65536)):Dg(A)&&(i.writer.writeUint32(0),i.writer.writeUint32(0)),i.writer.writeUint32At(e,i.writer.position()-e)},ch=(i,A)=>{wA(i,iA.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)},hh=(i,A)=>{const t=i.writer.position();wA(i,iA.hdlr,0,0,0),i.writer.writeUint32(0),i.writer.writeBytes(H(We(A)?"vide":"soun")),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeBytes(H(We(A)?"VideoHandler\0":"SoundHandler\0")),i.writer.writeUint32At(t,i.writer.position()-t)},dh=i=>{const A=i.writer.position();dA(i,iA.dinf,0),wA(i,iA.dref,16,0,0),i.writer.writeUint32(1),wA(i,H("url "),0,0,1),i.writer.writeUint32At(A,i.writer.position()-A)},lh=(i,A)=>{const t=i.writer.position();dA(i,iA.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)},uh=(i,A)=>{var Q,o;const t=i.writer.position();dA(i,iA.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)},wh=(i,A)=>{const t=i.writer.position(),e=vQ(A)?iA.av01:iA.avc1;dA(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),oa(A)?lh(i,A):vQ(A)&&(uh(i,A),A.parsedSequenceHeader.colorConfig&&(dA(i,H("colr"),11),i.writer.writeBytes(iA.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&&(dA(i,H("pasp"),8),i.writer.writeUint32(A.pixelAspectRatio.numerator),i.writer.writeUint32(A.pixelAspectRatio.denumerator)),A.bitrate&&(dA(i,H("btrt"),12),i.writer.writeUint32(0),i.writer.writeUint32(A.bitrate),i.writer.writeUint32(A.bitrate)),i.writer.writeUint32At(t,i.writer.position()-t)},OB=(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();wA(i,iA.esds,0,0,0),OB(i,3,21+t+5+1),i.writer.writeUint16(A.trackId),i.writer.writeUint8(0),OB(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&&(OB(i,5,A.decoderConfig.byteLength),i.writer.writeBytes(A.decoderConfig)),OB(i,6,1),i.writer.writeUint8(2),i.writer.writeUint32At(e,i.writer.position()-e)},Sh=i=>{switch(i){case"aac":case"mp3":return"mp4a";case"opus":return"Opus"}},mh=(i,A)=>{const t=i.writer.position();dA(i,H("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)},yh=(i,A)=>{const t=i.writer.position();switch(dA(i,H(Sh(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":mh(i,A);break}A.bitrate&&(dA(i,H("btrt"),12),i.writer.writeUint32(0),i.writer.writeUint32(A.bitrate),i.writer.writeUint32(A.bitrate)),i.writer.writeUint32At(t,i.writer.position()-t)},fh=(i,A)=>{const t=i.writer.position();dA(i,iA.stbl,0);const e=i.writer.position();wA(i,iA.stsd,0,0,0),i.writer.writeUint32(1),We(A)?wh(i,A):Dg(A)&&yh(i,A),i.writer.writeUint32At(e,i.writer.position()-e),wA(i,H("stts"),4,0,0),i.writer.writeUint32(0),wA(i,H("stsc"),4,0,0),i.writer.writeUint32(0),wA(i,H("stsz"),8,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),wA(i,H("stco"),4,0,0),i.writer.writeUint32(0),i.writer.writeUint32At(t,i.writer.position()-t)},ph=(i,A)=>{const t=i.writer.position();dA(i,iA.minf,0),We(A)?(wA(i,iA.vmhd,8,0,1),i.writer.writeUint32(0),i.writer.writeUint32(0)):Dg(A)&&(wA(i,iA.smhd,4,0,0),i.writer.writeUint16(0),i.writer.writeUint16(0)),dh(i),fh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Fh=(i,A)=>{const t=i.writer.position();dA(i,iA.mdia,0),ch(i,A),hh(i,A),ph(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Gh=(i,A,t)=>{const e=i.writer.position();dA(i,iA.trak,0),rh(i,A,t),Fh(i,A),i.writer.writeUint32At(e,i.writer.position()-e)},kh=(i,A)=>{wA(i,iA.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)},Rh=(i,A)=>{const t=i.writer.position();dA(i,iA.mvex,0),A.forEach(e=>kh(i,e)),i.writer.writeUint32At(t,i.writer.position()-t)},Uh=(i,A,t,e)=>{const g=i.writer.position();dA(i,iA.moov,0),Eh(i,0,t),A.forEach(B=>Gh(i,B,t)),Rh(i,A),i.writer.writeUint32At(g,i.writer.position()-g)},Nh=(i,A)=>{const t=i.writer.position();wA(i,iA.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)},bh=(i,A)=>{const t=i.writer.position();wA(i,iA.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)},Lh=(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();wA(i,iA.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,Jh=(i,A)=>{const t=i.writer.position();dA(i,iA.traf,0),Nh(i,A),bh(i,A),Lh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Mh=(i,A)=>{wA(i,iA.mfhd,4,0,0),i.writer.writeUint32(A)},Hh=(i,A)=>{const t=i.writer.position();dA(i,iA.moof,0),Mh(i,A.sequenceNumber),Jh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},qh=(i,A)=>{const t=A.samples.reduce((e,g)=>e+g.data.byteLength,0);dA(i,iA.mdat,t),A.samples.forEach(e=>i.writer.writeBytes(e.data))},VB=(i,A)=>{const t=new Qa,e=i.filter(B=>We(B)&&oa(B)).length>0;return i.filter(B=>We(B)&&vQ(B)).length>0?qQ(t,Ch):e?qQ(t,Bh):qQ(t,Qh),Uh(t,i,sh),t.writer.buffer()},ZB=i=>{var t;const A=new Qa;return((t=i.samples[0])==null?void 0:t.producerReferenceTime)!==void 0&&ah(A,i.trackId,i.samples[0].producerReferenceTime,i.timestamp),A.moofOffset=A.writer.position(),Hh(A,i),qh(A,i),A.writer.buffer()},vh=(i,A)=>{const t=i.map(C=>V(S({},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 ZB({trackId:1,timestamp:e,sequenceNumber:A,defaultSize:g.byteLength,defaultFlags:33554432,defaultDuration:B,samples:t})},Kh=(i,A,t,e)=>VB([{type:"audio",codec:"aac",decoderConfig:i,channelCount:A,sampleRate:t,timescale:e,duration:0,trackId:1}]),na=i=>{const{sequenceParameterSets:A,pictureParameterSets:t}=ga(i),e=A[0],g=t[0];if(!e||!g)throw new Error("No sps or pps provided");return Yc(e)},Yh=(i,A)=>{const t=i.map(Q=>V(S({},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 ZB({trackId:1,timestamp:g,sequenceNumber:A,defaultSize:B.byteLength,defaultFlags:e?33554432:16842752,defaultDuration:C,samples:t})},Th=(i,A)=>{const{sequenceParameterSets:t,pictureParameterSets:e}=ga(i),g=na(i);return VB([{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}])},Ph=(i,A,t)=>VB([{type:"audio",trackId:1,channelCount:A,timescale:t,codec:"opus",decoderConfig:i,duration:0,sampleRate:48e3}]),xh=(i,A)=>{const t=i.map(C=>V(S({},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 ZB({trackId:1,timestamp:e,sequenceNumber:A,defaultSize:g.byteLength,defaultFlags:33554432,defaultDuration:B,samples:t})},aa=i=>{const A=new _(i);return A.peekBit()===1&&A.readBits(32),Vh(A),td(A)},Wh=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]},Oh=i=>{let A=0;for(;A<100&&i.readBit()===0;)A++;return A>=32?0:i.readBits(A)+(1<<A)-1},Vh=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?Wh(i):[0,A];return{headerLength:1+B+Q,type:g,obuSize:o}},Zh=i=>{const A=i.readBits(32),t=i.readBits(32),e=i.readBit()!==0;let g=0;return e&&(g=Oh(i)+1),{timescale:t,equalPictureInterval:e,numUnitsInDisplayTick:A,numTicksPerPicture:g}},Ea=2,YQ=2,Xh=1,jh=2,zh=2,_h=13,$h=0,Ad=2,ra=0,td=i=>{const A=i.readBits(3),e=i.readBit()!==0,g=i.readBit()!==0;let B,C=!1,Q=!1,o=!1,E=0,c=0;const h=[];if(g)i.readBits(5);else{if(Q=i.readBit()!==0,Q&&(B=Zh(i),C=i.readBit()!==0,C))throw new Error("Not implemented");o=i.readBit()!==0;const MA=i.readBits(5)+1;for(let F=0;F<MA;F++){const K=i.readBits(12),AA=i.readBits(5);let CA=0;if(AA>7&&(CA=i.readBit()),C)throw new Error("decoderModelInfoPresentFlag==1");o&&i.readBit()!==0&&i.readBits(4),h.push({tier:CA,operatingPointIdc:K,seqLevelIdx:AA})}}const l=i.readBits(4)+1,m=i.readBits(4)+1,f=i.readBits(l)+1,U=i.readBits(m)+1;let b=!1;g?b=!1:b=i.readBit()!==0,b&&(E=i.readBits(4)+2,c=i.readBits(3)+1);const Y=i.readBit()!==0,N=i.readBit()!==0,v=i.readBit()!==0;let T=!1,P=!1,X=!1,yA=!1,BA=!1,fA=!1,Bt=!1,w=Ea,R=YQ,x=0;g||(T=i.readBit()!==0,P=i.readBit()!==0,X=i.readBit()!==0,yA=i.readBit()!==0,BA=i.readBit()!==0,BA&&(fA=i.readBit()!==0,Bt=i.readBit()!==0),i.readBit()!==0?w=Ea:w=i.readBit(),w>0?i.readBit()>0?R=YQ:R=i.readBit():R=YQ,BA?x=i.readBits(3):x=0);const eA=i.readBit()!==0,O=i.readBit()!==0,j=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:f,maxFrameHeight:U,frameIdNumbersPresentFlag:b,deltaFrameIdLength:E,additionalFrameIdLength:c,use_128x128Superblock:Y,enableFilterIntra:N,enableIntraEdgeFilter:v,enableInterintraCompound:T,enableMaskedCompound:P,enableWarpedMotion:X,enableDualFilter:yA,enableOrderHint:BA,enableJntComp:fA,enableRefFrameMvs:Bt,seqForceScreenContentTools:w,seqForceIntegerMv:R,orderHintBits:x,enableSuperres:eA,enableCdef:O,enableRestoration:j,colorConfig:ed(i,A),filmGrainParamsPresent:i.readBit()!==0}},ed=(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=jh,o=zh,E=Ad,c=!1,h=0,l=0,m=ra,f=!1;return C&&(Q=i.readBits(8),o=i.readBits(8),E=i.readBits(8)),g?(c=i.readBit()!==0,h=1,l=1,m=ra,f=!1,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:E,numPlanes:B,separateUvDeltaQ:f,subsamplingX:h,subsamplingY:l,transferCharacteristics:o}):Q===Xh&&o==_h&&E==$h?(c=!0,h=0,l=0,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:E,numPlanes:B,separateUvDeltaQ:f,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)),f=i.readBit()!==0,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:E,numPlanes:B,separateUvDeltaQ:f,subsamplingX:h,subsamplingY:l,transferCharacteristics:o})},id=i=>{const A=aa(i);if(A)return{width:A.maxFrameWidth,height:A.maxFrameHeight}},Id=(i,A)=>{const t=i.map(Q=>V(S({},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 ZB({trackId:1,timestamp:g,sequenceNumber:A,defaultSize:B.byteLength,defaultFlags:e?33554432:16842752,defaultDuration:C,samples:t})},gd=(i,A)=>{const t=aa(i);if(!t)throw new Error("Failed to parse sequence header");return VB([{type:"video",parsedSequenceHeader:t,sequenceHeader:new Uint8Array(i),width:t.maxFrameWidth,height:t.maxFrameHeight,timescale:A,duration:0,trackId:1}])},sd=(i,A,t)=>{switch(i){case"h264":return Cd(A,t);case"av1":return Qd(A,t);case"opus":return od(A,t);case"aac":return nd(A,t);default:throw new Error(`Failed to initialize ${i} segment`)}},Bd=(i,A)=>{switch(i){case"h264":return na(A);case"av1":return id(A)}},Cd=(i,A)=>Th(i,A),Qd=(i,A)=>gd(i,A),od=(i,A)=>Ph(new Uint8Array(i),2,A),nd=(i,A)=>Kh(new Uint8Array(i),2,A,A),ad=(i,A)=>{if(!i[0])throw new Error("At least one sample must be provided");switch(i[0].codec){case"h264":return Yh(i,A);case"opus":return xh(i,A);case"aac":return vh(i,A);case"av1":return Id(i,A);default:throw new Error(`Unsupported codec ${i[0].codec}`)}},Sg=i=>!!(i&1),Ed=i=>!!(i&2),rd=i=>!!(i&4),cd=i=>!!(i&8),hd=i=>!!(i&16),dd=i=>{const A=new DataView(i,0),t=A.getUint8(0),e=A.getUint16(1),g=A.getUint8(3),B=A.getUint8(4),C=fQ(new Uint8Array(i),5,12),Q=A.getUint32(13),o=hd(g)?A.getInt16(17):void 0,E=i.slice(e);return{version:t,renditionId:B,flags:g,timestamp:C,timescale:Q,payload:E,compositionTimeOffset:o}},ld="data:video/mp4;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAGF21kYXTeBAAAbGliZmFhYyAxLjI4AABCAJMgBDIARwAAArEGBf//rdxF6b3m2Ui3lizYINkj7u94MjY0IC0gY29yZSAxNDIgcjIgOTU2YzhkOCAtIEguMjY0L01QRUctNCBBVkMgY29kZWMgLSBDb3B5bGVmdCAyMDAzLTIwMTQgLSBodHRwOi8vd3d3LnZpZGVvbGFuLm9yZy94MjY0Lmh0bWwgLSBvcHRpb25zOiBjYWJhYz0wIHJlZj0zIGRlYmxvY2s9MTowOjAgYW5hbHlzZT0weDE6MHgxMTEgbWU9aGV4IHN1Ym1lPTcgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0xNiBjaHJvbWFfbWU9MSB0cmVsbGlzPTEgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz02IGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTI1MCBrZXlpbnRfbWluPTI1IHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NDAgcmM9Y3JmIG1idHJlZT0xIGNyZj0yMy4wIHFjb21wPTAuNjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCB2YnZfbWF4cmF0ZT03NjggdmJ2X2J1ZnNpemU9MzAwMCBjcmZfbWF4PTAuMCBuYWxfaHJkPW5vbmUgZmlsbGVyPTAgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAAAFZliIQL8mKAAKvMnJycnJycnJycnXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXiEASZACGQAjgCEASZACGQAjgAAAAAdBmjgX4GSAIQBJkAIZACOAAAAAB0GaVAX4GSAhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGagC/AySEASZACGQAjgAAAAAZBmqAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZrAL8DJIQBJkAIZACOAAAAABkGa4C/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmwAvwMkhAEmQAhkAI4AAAAAGQZsgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGbQC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm2AvwMkhAEmQAhkAI4AAAAAGQZuAL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGboC/AySEASZACGQAjgAAAAAZBm8AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZvgL8DJIQBJkAIZACOAAAAABkGaAC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmiAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpAL8DJIQBJkAIZACOAAAAABkGaYC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmoAvwMkhAEmQAhkAI4AAAAAGQZqgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGawC/AySEASZACGQAjgAAAAAZBmuAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZsAL8DJIQBJkAIZACOAAAAABkGbIC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm0AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZtgL8DJIQBJkAIZACOAAAAABkGbgCvAySEASZACGQAjgCEASZACGQAjgAAAAAZBm6AnwMkhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AAAAhubW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAABDcAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAzB0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAA+kAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAALAAAACQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAPpAAAAAAABAAAAAAKobWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAB1MAAAdU5VxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACU21pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAhNzdGJsAAAAr3N0c2QAAAAAAAAAAQAAAJ9hdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAALAAkABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAALWF2Y0MBQsAN/+EAFWdCwA3ZAsTsBEAAAPpAADqYA8UKkgEABWjLg8sgAAAAHHV1aWRraEDyXyRPxbo5pRvPAyPzAAAAAAAAABhzdHRzAAAAAAAAAAEAAAAeAAAD6QAAABRzdHNzAAAAAAAAAAEAAAABAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAAIxzdHN6AAAAAAAAAAAAAAAeAAADDwAAAAsAAAALAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAAiHN0Y28AAAAAAAAAHgAAAEYAAANnAAADewAAA5gAAAO0AAADxwAAA+MAAAP2AAAEEgAABCUAAARBAAAEXQAABHAAAASMAAAEnwAABLsAAATOAAAE6gAABQYAAAUZAAAFNQAABUgAAAVkAAAFdwAABZMAAAWmAAAFwgAABd4AAAXxAAAGDQAABGh0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAACAAAAAAAABDcAAAAAAAAAAAAAAAEBAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAQkAAADcAABAAAAAAPgbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAC7gAAAykBVxAAAAAAALWhkbHIAAAAAAAAAAHNvdW4AAAAAAAAAAAAAAABTb3VuZEhhbmRsZXIAAAADi21pbmYAAAAQc21oZAAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAADT3N0YmwAAABnc3RzZAAAAAAAAAABAAAAV21wNGEAAAAAAAAAAQAAAAAAAAAAAAIAEAAAAAC7gAAAAAAAM2VzZHMAAAAAA4CAgCIAAgAEgICAFEAVBbjYAAu4AAAADcoFgICAAhGQBoCAgAECAAAAIHN0dHMAAAAAAAAAAgAAADIAAAQAAAAAAQAAAkAAAAFUc3RzYwAAAAAAAAAbAAAAAQAAAAEAAAABAAAAAgAAAAIAAAABAAAAAwAAAAEAAAABAAAABAAAAAIAAAABAAAABgAAAAEAAAABAAAABwAAAAIAAAABAAAACAAAAAEAAAABAAAACQAAAAIAAAABAAAACgAAAAEAAAABAAAACwAAAAIAAAABAAAADQAAAAEAAAABAAAADgAAAAIAAAABAAAADwAAAAEAAAABAAAAEAAAAAIAAAABAAAAEQAAAAEAAAABAAAAEgAAAAIAAAABAAAAFAAAAAEAAAABAAAAFQAAAAIAAAABAAAAFgAAAAEAAAABAAAAFwAAAAIAAAABAAAAGAAAAAEAAAABAAAAGQAAAAIAAAABAAAAGgAAAAEAAAABAAAAGwAAAAIAAAABAAAAHQAAAAEAAAABAAAAHgAAAAIAAAABAAAAHwAAAAQAAAABAAAA4HN0c3oAAAAAAAAAAAAAADMAAAAaAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAACMc3RjbwAAAAAAAAAfAAAALAAAA1UAAANyAAADhgAAA6IAAAO+AAAD0QAAA+0AAAQAAAAEHAAABC8AAARLAAAEZwAABHoAAASWAAAEqQAABMUAAATYAAAE9AAABRAAAAUjAAAFPwAABVIAAAVuAAAFgQAABZ0AAAWwAAAFzAAABegAAAX7AAAGFwAAAGJ1ZHRhAAAAWm1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALWlsc3QAAAAlqXRvbwAAAB1kYXRhAAAAAQAAAABMYXZmNTUuMzMuMTAw",XB=()=>"wakeLock"in navigator&&window.navigator.userAgent.indexOf("Samsung")===-1;class ud{constructor(){I(this,"enabled",!1);I(this,"wakeLockVideo");I(this,"_wakeLock",null);I(this,"handleVisibilityChange",()=>{this._wakeLock!==null&&document.visibilityState==="visible"&&this.enable()});XB()&&(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(!XB()){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",ld),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 XB()?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;XB()?(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 wd=/\r\n|\r|\n/;class ca{constructor(A){n(this,de);n(this,Zt);a(this,de,A),a(this,Zt,0)}skipEmptyLines(){let A=0;for(;s(this,de)[s(this,Zt)]==="";)ft(this,Zt)._++,A++;return A}readLine(){return s(this,de)[ft(this,Zt)._++]}takeUntilEmptyLine(){const A=[];for(;s(this,de)[s(this,Zt)]!=="";){const t=this.readLine();if(t===void 0)break;A.push(t)}return A}linesLeft(){return s(this,de).length-s(this,Zt)}}de=new WeakMap,Zt=new WeakMap;class ha{constructor(){n(this,ii)}parse(A){const t=[],e=A.split(wd),g=new ca(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,ii,jE).call(this,g);t.push(C),g.skipEmptyLines()}return t}}ii=new WeakSet,jE=function(A){A.skipEmptyLines();const t=A.takeUntilEmptyLine(),e=new ca(t);let g=e.readLine(),B;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,E]=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,ii,on).call(this,C),l=d(this,ii,on).call(this,o);return{id:B,startTime:h,endTime:l,text:c}},on=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};class TQ extends $A{constructor({type:t,autoplay:e,muted:g,logger:B,poster:C}){super();I(this,"element");I(this,"logger");I(this,"seekTimes",new L(10));I(this,"seekStartTime");I(this,"_userProvidedMuted");I(this,"timers",new RA);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(y)});I(this,"play",()=>{this.element.muted=this._userProvidedMuted,this._play().catch(t=>{if(t instanceof Error){const e=new W("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:Wi(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 Dd=["minBufferTime","maxBufferTime","burstEnabled","sizeBasedResolutionCapEnabled","separateVideoSocketEnabled","videoCodecs"];function Sd(i){return Dd.includes(i)}class md{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&&Sd(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 yd=i=>{const A=window;A.vindralInstances=A.vindralInstances||{},A.vindralInstances[i.getStatistics().clientId.substring(0,8)]=i},fd=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 Pe(i)?A={type:"media-source",audio:{contentType:xe(i),bitrate:i.bitRate,channels:i.channels.toString(),samplerate:i.sampleRate}}:A={type:"media-source",video:{contentType:xe(i),bitrate:i.bitRate,width:i.width,height:i.height,framerate:i.frameRate[0]/i.frameRate[1]}},navigator.mediaCapabilities.decodingInfo(A)},pd=.15,Fd=.2,da=.4,Gd=.5,kd=.6,PQ=15,Rd={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,mC=class mC{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),E=this.qualityOfServiceSource.timeActive()-this.qualityOfServiceSource.timeSpentBuffering(),c=o*E/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,{slope:C}=g,Q=g.predict(PQ),o=C<0,E=g.predict(PQ)<da&&g.slope<0,c=g.predict(PQ)>kd,h=this.qualityOfServiceSource.timeSpentBufferingLast(30*1e3),l=this.qualityOfServiceSource.timeSpentActiveLast(30*1e3),m=h/l;if(t<.15&&m>.8){this.adaptLevel("reconnect");return}if(e.decodeRate<=1){this.adaptLevel("downgrade");return}E||t<pd?o&&t<da&&Q<Fd&&this.adaptLevel(A.playbackState==="buffering"?"double downgrade":"downgrade"):t>Gd&&c&&!this.tooMuchTimeBuffering(B)&&!this.tooManyBufferingEvents(B)&&this.adaptLevel("upgrade")});I(this,"onAdaptedLevel",()=>{this.reset()});I(this,"adaptLevel",A=>this.emitter.emit("adapt level",A));this.qualityOfServiceSource=e,this.config=S(S({},Rd),g),this.emitter=A,this.logger=t}tooMuchTimeBuffering(A){return this.qualityOfServiceSource.timeSpentBufferingLast(A)/this.qualityOfServiceSource.timeSpentActiveLast(A)>this.config.maxBufferingRatio.last10Seconds}tooManyBufferingEvents(A){return this.qualityOfServiceSource.timeSpentBufferingLast(A)>this.config.maxBufferingEvents.last10Seconds}};I(mC,"create",(A,t,e,g={})=>new mC(A,t,e,g));let WQ=mC;const Ud={minBufferTime:1500,maxBufferTime:1500,cooldownTime:3e4,maxBufferingEvents:{last30Seconds:3},maxBufferingRatio:{last30Seconds:.15}},le=class le{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,E=Math.ceil(Math.max((e-t)/(le.BUFFER_TIME_MAX_STEPS-1),le.BUFFER_TIME_STEP_SIZE));(o>this.config.maxBufferingRatio.last30Seconds||C>this.config.maxBufferingEvents.last30Seconds)&&(this.targetBufferTimeTarget.targetBufferTime=Math.min(e,this.targetBufferTimeTarget.targetBufferTime+E),this.bufferTimeAdjustmentCount++,this.reset())});this.qualityOfServiceSource=e,this.targetBufferTimeTarget=g,this.config=S(S({},Ud),B),this.emitter=A,this.logger=t}updateConfig(A){this.config=S(S({},this.config),A)}};I(le,"BUFFER_TIME_STEP_SIZE",500),I(le,"BUFFER_TIME_MAX_STEPS",3),I(le,"create",(A,t,e,g,B={})=>new le(A,t,e,g,B));let OQ=le;var jB=(i=>(i[i.StreamHeaderGroup=4]="StreamHeaderGroup",i[i.FetchHeader=5]="FetchHeader",i[i.StreamHeaderTrack=60]="StreamHeaderTrack",i))(jB||{});const qA={Normal:0,ObjectDoesNotExist:1,GroupDoesNotExist:2,EndOfGroup:3,EndOfTrackAndGroup:4};function la(i){switch(i){case qA.Normal:case qA.ObjectDoesNotExist:case qA.GroupDoesNotExist:case qA.EndOfGroup:case qA.EndOfTrackAndGroup:return}throw new Error("Unknown object status "+i)}class Nd{constructor(A,t,e,g,B,C){n(this,kt);n(this,gI);n(this,sI);n(this,Is);n(this,gs);n(this,BI,new G);n(this,ss,0);n(this,Bs);a(this,kt,A),a(this,gI,t),a(this,sI,e),a(this,Is,g),a(this,gs,B),a(this,Bs,C)}endStatus(){return s(this,BI).promise}groupId(){return s(this,gI)}subscribeId(){return s(this,sI)}next(){return r(this,null,function*(){if(!s(this,BI).pending)return{done:!0,value:void 0};if(yield s(this,kt).isDone())return{done:!0,value:void 0};const A=s(this,ss)===0?s(this,gI):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===qA.EndOfTrackAndGroup||g===qA.EndOfGroup)&&s(this,BI).resolve(g),ft(this,ss)._++,{done:!1,value:{subscribeId:s(this,sI),trackAlias:s(this,Is),groupId:A,subGroupId:q(0),objectId:t,subscriberPriority:s(this,gs),streamId:s(this,Bs),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,gI=new WeakMap,sI=new WeakMap,Is=new WeakMap,gs=new WeakMap,BI=new WeakMap,ss=new WeakMap,Bs=new WeakMap;class bd{constructor(A,t,e,g,B){n(this,Ii);n(this,Rt);n(this,CI);n(this,Cs);n(this,Qs);n(this,QI);a(this,Rt,A),a(this,CI,t),a(this,Cs,e),a(this,Qs,g),a(this,QI,B)}streamId(){return s(this,QI)}groups(){return d(this,Ii,zE).call(this)}subscribeId(){return s(this,CI)}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,Ii,nn).call(this)}[Symbol.asyncDispose](){return d(this,Ii,nn).call(this)}}Rt=new WeakMap,CI=new WeakMap,Cs=new WeakMap,Qs=new WeakMap,QI=new WeakMap,Ii=new WeakSet,zE=function(){return Qe(this,null,function*(){for(;!(yield new aA(s(this,Rt).isDone()));){const A=yield new aA(s(this,Rt).readBigVarInt()),t=new Nd(s(this,Rt),A,s(this,CI),s(this,Cs),s(this,Qs),s(this,QI));if(yield t,(yield new aA(Promise.race([t.endStatus(),s(this,Rt).closed()])))===qA.EndOfTrackAndGroup)return}})},nn=function(){return s(this,Rt).close().catch(()=>{})};class Ld{constructor(A,t,e,g,B,C,Q){n(this,gi);n(this,ht);n(this,oI);n(this,os);n(this,nI);n(this,ns);n(this,as);n(this,Es,!1);n(this,aI);n(this,yC,kA.get().createContext("GroupReader"));a(this,ht,A),a(this,oI,t),a(this,os,e),a(this,nI,g),a(this,ns,B),a(this,as,C),a(this,aI,Q)}streamId(){return s(this,aI)}groupId(){return s(this,nI)}subscribeId(){return s(this,oI)}next(){return r(this,null,function*(){try{if((yield s(this,ht).isDone())||s(this,Es))return{done:!0,value:void 0};const A=yield s(this,ht).readBigVarInt(),t=yield s(this,ht).readVarInt();let e=0,g=new Uint8Array;return t>0?g=yield s(this,ht).read(t):e=yield s(this,ht).readVarInt(),la(e),e===qA.EndOfGroup&&a(this,Es,!0),{done:!1,value:{subscribeId:s(this,oI),trackAlias:s(this,os),groupId:s(this,nI),subGroupId:s(this,ns),subscriberPriority:s(this,as),streamId:s(this,aI),objectId:A,objectStatus:e,payload:g}}}catch(A){return s(this,yC).info("Error reading object",{error:A}),{done:!0,value:void 0}}})}return(){return r(this,null,function*(){return yield s(this,ht).close().catch(()=>{}),{done:!0,value:void 0}})}groups(){return d(this,gi,_E).call(this)}[Symbol.asyncIterator](){return this}[pt()](){return d(this,gi,an).call(this)}[Symbol.asyncDispose](){return d(this,gi,an).call(this)}}ht=new WeakMap,oI=new WeakMap,os=new WeakMap,nI=new WeakMap,ns=new WeakMap,as=new WeakMap,Es=new WeakMap,aI=new WeakMap,yC=new WeakMap,gi=new WeakSet,_E=function(){return Qe(this,null,function*(){yield this})},an=function(){return s(this,ht).close().catch(()=>{})};function ua(i,A){return r(this,null,function*(){const t=yield i.readVarInt();switch(t){case jB.StreamHeaderGroup:{const e=yield i.readBigVarInt(),g=yield i.readBigVarInt(),B=yield i.readBigVarInt(),C=yield i.readBigVarInt(),Q=yield i.readUnsigned8();return new Ld(i,e,g,B,C,Q,A)}case jB.StreamHeaderTrack:{const e=yield i.readBigVarInt(),g=yield i.readBigVarInt(),B=yield i.readUnsigned8();return new bd(i,e,g,B,A)}default:throw new Error("Unexpected message type "+t)}})}class Jd{constructor(A,t){n(this,ue);n(this,rs);a(this,ue,A),a(this,rs,t)}start(A){s(this,ue).addEventListener("message",t=>{if(typeof t.data=="object"&&t.data instanceof ArrayBuffer){const e=new Uint8Array(t.data);e[0]==s(this,rs)&&A.enqueue(e.subarray(1))}}),s(this,ue).addEventListener("error",()=>A.error(new Error("WebSocket error"))),s(this,ue).addEventListener("close",()=>yn(()=>A.close()))}cancel(A){s(this,ue).close(void 0,A)}}ue=new WeakMap,rs=new WeakMap;class Md{constructor(A){n(this,Ut);n(this,si,null);n(this,Bi,null);n(this,Ci,null);a(this,Ut,A)}start(A){a(this,si,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])}}}),a(this,Bi,()=>yn(()=>A.close())),a(this,Ci,()=>A.error(new Error("WebSocket error"))),s(this,Ut).addEventListener("message",s(this,si)),s(this,Ut).addEventListener("error",s(this,Ci)),s(this,Ut).addEventListener("close",s(this,Bi))}cancel(A){s(this,si)&&s(this,Ut).removeEventListener("message",s(this,si)),s(this,Ci)&&s(this,Ut).removeEventListener("error",s(this,Ci)),s(this,Bi)&&s(this,Ut).removeEventListener("close",s(this,Bi))}}Ut=new WeakMap,si=new WeakMap,Bi=new WeakMap,Ci=new WeakMap;class zB{constructor(A,t){n(this,IA);n(this,Nt);n(this,cs);n(this,Qi);n(this,bt,0);n(this,fC,new TextDecoder);a(this,Nt,A),a(this,cs,t),a(this,Qi,t.getReader())}readUnsigned8(){return r(this,null,function*(){return yield d(this,IA,vi).call(this,1),d(this,IA,qe).call(this,1)[0]})}readString(){return r(this,null,function*(){const A=yield this.readVarInt(),t=yield this.read(A);return s(this,fC).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,IA,vi).call(this,1);const A=(d(this,IA,hQ).call(this,1)[0]&192)>>6;switch(s(this,Nt)[s(this,bt)]=d(this,IA,hQ).call(this,1)[0]&63,A){case 0:return q(d(this,IA,qe).call(this,1)[0]);case 1:{yield d(this,IA,vi).call(this,2);const t=d(this,IA,qe).call(this,2),e=new DataView(t.buffer,t.byteOffset,t.byteLength);return q(e.getUint16(0))}case 2:{yield d(this,IA,vi).call(this,4);const t=d(this,IA,qe).call(this,4),e=new DataView(t.buffer,t.byteOffset,t.byteLength);return q(e.getUint32(0))}case 3:{yield d(this,IA,vi).call(this,8);const t=d(this,IA,qe).call(this,8),e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(typeof e.getBigUint64!="undefined")return q(e.getBigUint64(0));const g=fQ(t,0,7);return q(g)}default:throw new Error("Invalid VarInt size")}})}read(A){return r(this,null,function*(){return yield d(this,IA,vi).call(this,A),d(this,IA,qe).call(this,A)})}readAll(){return r(this,null,function*(){for(;yield d(this,IA,cQ).call(this););return d(this,IA,qe).call(this,d(this,IA,uB).call(this))})}isDone(){return r(this,null,function*(){return d(this,IA,uB).call(this)>0?!1:(yield d(this,IA,cQ).call(this))==0})}closed(){return r(this,null,function*(){return s(this,Qi).closed})}close(){return r(this,null,function*(){return s(this,Qi).releaseLock(),s(this,cs).cancel()})}}Nt=new WeakMap,cs=new WeakMap,Qi=new WeakMap,bt=new WeakMap,fC=new WeakMap,IA=new WeakSet,uB=function(){return s(this,Nt).length-s(this,bt)},cQ=function(){return r(this,null,function*(){const{value:A,done:t}=yield s(this,Qi).read();if(t)return Promise.resolve(0);if(d(this,IA,uB).call(this)===0)a(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),a(this,Nt,B)}return a(this,bt,0),Promise.resolve(A.length)})},vi=function(A){return r(this,null,function*(){for(;d(this,IA,uB).call(this)<A;)if((yield d(this,IA,cQ).call(this))===0)throw new Error("Read failed")})},hQ=function(A){return s(this,Nt).subarray(s(this,bt),s(this,bt)+A)},qe=function(A){const t=d(this,IA,hQ).call(this,A);return a(this,bt,s(this,bt)+t.length),t};class wa{constructor(A){n(this,EI,new Uint8Array(8));n(this,rI);n(this,Xt);n(this,pC,new TextEncoder);a(this,rI,A),a(this,Xt,s(this,rI).getWriter())}writeString(A){return r(this,null,function*(){const t=s(this,pC).encode(A);return yield this.writeVarInt(t.length),this.write(t)})}write(A){return s(this,Xt).write(A)}writeUnsigned8(A){return s(this,Xt).write(_B(A,s(this,EI)))}writeVarInt(A){return s(this,Xt).write(ka(A,s(this,EI)))}writeBigVarInt(A){return s(this,Xt).write(Ra(A,s(this,EI)))}flush(){return r(this,null,function*(){})}close(){return r(this,null,function*(){s(this,Xt).releaseLock(),yield s(this,rI).close()})}}EI=new WeakMap,rI=new WeakMap,Xt=new WeakMap,pC=new WeakMap;const Da={OPEN:1},hs=class hs{constructor(A){n(this,OA,0);n(this,ZA,new Uint8Array(hs.DEFAULT_BUFFER_SIZE));n(this,oi);n(this,FC,new TextEncoder);a(this,oi,A)}writeString(A){return r(this,null,function*(){const t=s(this,FC).encode(A);return yield this.writeVarInt(t.length),this.write(t)})}ensureBufferSpace(A){if(s(this,ZA).length-s(this,OA)>=A)return;const t=new Uint8Array(s(this,ZA).length+A);t.set(s(this,ZA)),a(this,ZA,t)}write(A){return this.ensureBufferSpace(A.length),s(this,ZA).set(A,s(this,OA)),a(this,OA,s(this,OA)+A.byteLength),Promise.resolve()}writeUnsigned8(A){return this.ensureBufferSpace(1),_B(A,s(this,ZA).subarray(s(this,OA))),a(this,OA,s(this,OA)+1),Promise.resolve()}writeVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return this.ensureBufferSpace(8),a(this,OA,s(this,OA)+ka(A,s(this,ZA).subarray(s(this,OA))).byteLength),Promise.resolve()}writeBigVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return this.ensureBufferSpace(8),a(this,OA,s(this,OA)+Ra(A,s(this,ZA).subarray(s(this,OA))).byteLength),Promise.resolve()}flush(){if(s(this,oi).readyState!==Da.OPEN)throw new Error("Writer is not open");return s(this,oi).send(s(this,ZA).subarray(0,s(this,OA))),a(this,OA,0),a(this,ZA,new Uint8Array(hs.DEFAULT_BUFFER_SIZE)),Promise.resolve()}close(){return s(this,oi).close(),Promise.resolve()}};OA=new WeakMap,ZA=new WeakMap,oi=new WeakMap,FC=new WeakMap,I(hs,"DEFAULT_BUFFER_SIZE",1024);let mg=hs;const Sa=Math.pow(2,6)-1,ma=Math.pow(2,14)-1,ya=Math.pow(2,30)-1,Hd=Number.MAX_SAFE_INTEGER,qd=typeof BigInt=="function"?sn(q(2),q(62))-q(1):q(Number.MAX_SAFE_INTEGER);function _B(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<=Sa)return _B(i,A);if(i<=ma)return fa(i|16384,A);if(i<=ya)return pa(i|2147483648,A);if(i<=Hd)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<Sa)return _B(Number(i),A);if(i<ma)return fa(Number(i)|16384,A);if(i<=ya)return pa(Number(i)|2147483648,A);if(i<=qd)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 J=(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))(J||{});function $B(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 VQ(i,A){return r(this,null,function*(){yield i.writeVarInt(A.length);for(const t of A)yield i.writeString(t)})}const AC=q(2);function Zi(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 Xi(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 vd(i){return r(this,null,function*(){return{type:J.Announce,namespace:yield $B(i),params:yield Zi(i)}})}function Kd(i,A){return r(this,null,function*(){yield VQ(i,A.namespace),yield Xi(i,A.params)})}function Yd(i){return r(this,null,function*(){return{type:J.AnnounceOk,namespace:yield $B(i)}})}function Td(i,A){return r(this,null,function*(){yield VQ(i,A.namespace)})}const Pd={Subscriber:2},tC={Role:q(0)},Ua={Draft07:4278190087};function Na(i){return r(this,null,function*(){const A=yield i.readVarInt();switch(A){case Ua.Draft07:return{type:"known",value:A};default:return{type:"unknown",value:A}}})}function xd(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 Xi(i,A.parameters)})}function Wd(i){return r(this,null,function*(){const A=[],t=yield i.readVarInt();for(let g=0;g<t;g++)A.push(yield Na(i));const e=yield Zi(i);if(!e.has(tC.Role))throw new Error("Role parameter is required");return{type:J.ClientSetup,supportedVersions:A,parameters:e}})}function Od(i,A){return r(this,null,function*(){yield i.writeVarInt(A.selectedVersion.value),yield Xi(i,A.parameters)})}function Vd(i){return r(this,null,function*(){const A=yield Na(i);if(A.type!=="known")throw new Error("Expected known version");const t=yield Zi(i);if(!t.has(tC.Role))throw new Error("Role parameter is required");return{type:J.ServerSetup,selectedVersion:A,parameters:t}})}const Zd={"latest-group":1,"latest-object":2,"absolute-start":3,"absolute-range":4};function Xd(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 jd(i,A){return r(this,null,function*(){const t=Zd[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 ba(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 La(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 $B(i),g=yield i.readString(),B=yield i.readUnsigned8(),C=yield ba(i),Q=yield Xd(i),o=yield Zi(i);if(Q.type==="absolute-range"){const E=Q.start.group>Q.end.group,c=Q.start.group===Q.end.group&&Q.start.object>Q.end.object;if(E||c)throw new Error("Invalid filter range")}return{type:J.Subscribe,id:A,trackAlias:t,namespace:e,name:g,subscriberPriority:B,groupOrder:C,filterType:Q,params:o}})}function _d(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.trackAlias),yield VQ(i,A.namespace),yield i.writeString(A.name),yield i.writeUnsigned8(A.subscriberPriority),yield La(i,A.groupOrder),yield jd(i,A.filterType),yield Xi(i,A.params)})}const ZQ={TrackEnded:3,Expired:6};function $d(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:J.SubscribeDone,id:A,errorCode:t,reason:e,finalInfo:B}})}function Al(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 tl(i){return r(this,null,function*(){return{type:J.SubscribeError,id:yield i.readBigVarInt(),errorCode:yield i.readBigVarInt(),reason:yield i.readString(),trackAlias:yield i.readBigVarInt()}})}function el(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 il(i){return r(this,null,function*(){const A=yield i.readBigVarInt(),t=yield i.readBigVarInt(),e=yield ba(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 Zi(i);return{type:J.SubscribeOk,id:A,groupOrder:e,expires:t,largestInfo:B,params:C}})}function Il(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.expires),yield La(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 Xi(i,A.params)})}function gl(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 Zi(i),o=t>g,E=t===g&&e>B;if(o||E)throw new Error("Invalid filter range");return{type:J.SubscribeUpdate,id:A,start:{group:t,object:e},end:{group:g,object:B},subscriberPriority:C,params:Q}})}function sl(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 Xi(i,A.params)})}function Bl(i){return r(this,null,function*(){return{type:J.Unsubscribe,id:yield i.readBigVarInt()}})}function Cl(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id)})}class Ja{constructor(A){n(this,cA);n(this,jt);n(this,cI,new Uint8Array);a(this,jt,A)}write(A){return r(this,null,function*(){yield s(this,jt).writeVarInt(A.type);const t=new mg({close:()=>{},readyState:Da.OPEN,send:e=>{a(this,cI,new Uint8Array(e))}});switch(A.type){case J.Subscribe:yield d(this,cA,tr).call(this,t,A);break;case J.Announce:yield d(this,cA,Br).call(this,t,A);break;case J.SubscribeOk:yield d(this,cA,er).call(this,t,A);break;case J.SubscribeUpdate:yield d(this,cA,Ir).call(this,t,A);break;case J.SubscribeError:yield d(this,cA,ir).call(this,t,A);break;case J.SubscribeDone:yield d(this,cA,gr).call(this,t,A);break;case J.Unsubscribe:yield d(this,cA,sr).call(this,t,A);break;case J.ClientSetup:yield d(this,cA,$E).call(this,t,A);break;case J.ServerSetup:yield d(this,cA,Ar).call(this,t,A);break;case J.AnnounceOk:yield d(this,cA,Cr).call(this,t,A);break;default:throw new Error(`Unknown message type: ${A.type}`)}yield t.flush(),yield s(this,jt).writeVarInt(s(this,cI).byteLength),yield s(this,jt).write(s(this,cI)),yield s(this,jt).flush()})}close(){return r(this,null,function*(){return s(this,jt).close()})}}jt=new WeakMap,cI=new WeakMap,cA=new WeakSet,$E=function(A,t){return r(this,null,function*(){yield xd(A,t)})},Ar=function(A,t){return r(this,null,function*(){yield Od(A,t)})},tr=function(A,t){return r(this,null,function*(){yield _d(A,t)})},er=function(A,t){return r(this,null,function*(){yield Il(A,t)})},ir=function(A,t){return r(this,null,function*(){yield el(A,t)})},Ir=function(A,t){return r(this,null,function*(){yield sl(A,t)})},gr=function(A,t){return r(this,null,function*(){yield Al(A,t)})},sr=function(A,t){return r(this,null,function*(){yield Cl(A,t)})},Br=function(A,t){return r(this,null,function*(){yield Kd(A,t)})},Cr=function(A,t){return r(this,null,function*(){yield Td(A,t)})};class Ql{constructor(A,t){n(this,hI);n(this,ds);n(this,ls);a(this,hI,A),a(this,ds,new Ja(A)),a(this,ls,t)}write(A){return r(this,null,function*(){yield s(this,hI).write(s(this,ls)),yield s(this,ds).write(A)})}close(){return s(this,hI).close()}}hI=new WeakMap,ds=new WeakMap,ls=new WeakMap;function ol(i){return r(this,null,function*(){return{type:J.AnnounceError,namespace:yield $B(i),errorCode:yield i.readBigVarInt(),reason:yield i.readString()}})}function nl(i,A,t){return r(this,null,function*(){return{type:J.Unknown,messageType:A,payload:yield i.read(t)}})}class Ma{constructor(A){n(this,SA);a(this,SA,A)}cancel(){return s(this,SA).close()}read(){return r(this,null,function*(){const A=yield s(this,SA).readVarInt(),t=yield s(this,SA).readVarInt();switch(A){case J.ServerSetup:return Vd(s(this,SA));case J.ClientSetup:return Wd(s(this,SA));case J.Subscribe:return zd(s(this,SA));case J.SubscribeOk:return il(s(this,SA));case J.SubscribeDone:return $d(s(this,SA));case J.SubscribeError:return tl(s(this,SA));case J.SubscribeUpdate:return gl(s(this,SA));case J.Unsubscribe:return Bl(s(this,SA));case J.Announce:return vd(s(this,SA));case J.AnnounceOk:return Yd(s(this,SA));case J.AnnounceError:return ol(s(this,SA))}return nl(s(this,SA),q(A),t)})}}SA=new WeakMap;const uI=class uI{constructor(A,t){n(this,GC);n(this,us);n(this,dI);n(this,lI,new G);n(this,ws,new G);a(this,us,A),a(this,dI,t),s(this,lI).resolve()}write(A){return r(this,null,function*(){const t=yield d(this,GC,Qr).call(this);try{yield s(this,us).write(A)}finally{t.resolve()}})}markPostHandshake(){s(this,ws).resolve()}postHandshake(){return s(this,ws).promise}read(){return r(this,null,function*(){return s(this,dI).read()})}cancel(){return s(this,dI).cancel()}static wrapWebsocket(A){const t=new ReadableStream(new Jd(A,s(uI,kC))),e=new Ma(new zB(new Uint8Array([]),t)),g=new Ql(new mg(A),new Uint8Array([0]));return new uI(g,e)}static wrapWebTransport(A){const t=A.writable,e=A.readable;return new uI(new Ja(new wa(t)),new Ma(new zB(new Uint8Array,e)))}};us=new WeakMap,dI=new WeakMap,lI=new WeakMap,ws=new WeakMap,GC=new WeakSet,Qr=function(){const A=new G,t=s(this,lI).promise.then(()=>A);return a(this,lI,A),t},kC=new WeakMap,n(uI,kC,0);let eC=uI;function Ha(i,A){return r(this,null,function*(){yield i.write({type:J.ClientSetup,supportedVersions:[{type:"known",value:Ua.Draft07}],parameters:new Map([[tC.Role,{type:tC.Role,payload:new Uint8Array([A])}]])});const t=yield i.read();if(i.markPostHandshake(),t.type!==J.ServerSetup)throw new Error("Expected server setup message");if(t.selectedVersion.type!=="known")throw new Error("Expected known version")})}class al{constructor(A){I(this,"announce");n(this,wI,new G);this.announce=A}onOk(A){s(this,wI).resolve(A)}onError(A){const t=new Error(A.reason);return s(this,wI).reject(t),t}ok(){return s(this,wI).promise}}wI=new WeakMap;function El(i){const A=new al(i);return new rl(A)}class rl{constructor(A){I(this,"state");this.state=A}}const SI=class SI{constructor(A){I(this,"subscribe");n(this,DI,new G);n(this,we,new G);n(this,ni,new G);n(this,RC,Date.now());n(this,ai,new G);n(this,dt);switch(this.subscribe=A,A.filterType.type){case"absolute-start":a(this,dt,{startGroup:A.filterType.start.group});break;case"absolute-range":a(this,dt,{startGroup:A.filterType.start.group,endGroup:A.filterType.end.group});break}}onUpdate(A){a(this,dt,{startGroup:A.start.group}),A.end.group>q(0)&&(s(this,dt).endGroup=A.end.group-q(1))}onError(A){const t=new Error(A.reason);return s(this,DI).reject(t),s(this,we).reject(t),t}onDone(A){A.finalInfo&&(s(this,dt)||a(this,dt,{startGroup:q(0)}),s(this,dt).endGroup=A.finalInfo.group),s(this,we).resolve(A)}onUnsubscribe(A){s(this,ni).resolve(A)}onOk(A){const t=Math.max(0,Date.now()-s(this,RC)),e=Number(A.expires);if(e>0){const g=Math.max(SI.minGraceTime,Math.min(e/10,SI.maxGraceTime));Promise.race([Ye(e-g-t),this.done().catch(y)]).then(()=>s(this,ai).resolve(this.expiryState())).catch(y)}s(this,DI).resolve(A)}done(){return s(this,we).promise}ok(){return s(this,DI).promise}range(){return s(this,dt)}close(){s(this,ai).promise.catch(y),s(this,ai).reject(new Error("Subscription closed"))}expiryState(){return s(this,we).resolved&&s(this,we).resolved.errorCode!==ZQ.Expired?"done":s(this,ni).pending?"active":"unsubscribed"}unsubscribed(){return s(this,ni).promise}isUnsubscribed(){return s(this,ni).resolved}expiryNotification(){return s(this,ai).promise}};DI=new WeakMap,we=new WeakMap,ni=new WeakMap,RC=new WeakMap,ai=new WeakMap,dt=new WeakMap,I(SI,"maxGraceTime",15e3),I(SI,"minGraceTime",3e3);let iC=SI;class cl{constructor(A){n(this,LA);n(this,Ds,!1);a(this,LA,A)}write(A){return r(this,null,function*(){s(this,Ds)||(yield s(this,LA).writeVarInt(jB.StreamHeaderGroup),yield s(this,LA).writeBigVarInt(A.subscribeId),yield s(this,LA).writeBigVarInt(A.trackAlias),yield s(this,LA).writeBigVarInt(A.groupId),yield s(this,LA).writeBigVarInt(A.subGroupId),yield s(this,LA).writeUnsigned8(A.subscriberPriority),a(this,Ds,!0)),yield s(this,LA).writeBigVarInt(A.objectId),yield s(this,LA).writeVarInt(A.payload.length),A.payload.length>0?yield s(this,LA).write(A.payload):yield s(this,LA).writeVarInt(A.objectStatus),yield s(this,LA).flush()})}close(){return r(this,null,function*(){yield s(this,LA).close()})}}LA=new WeakMap,Ds=new WeakMap;class hl{constructor(A,t,e,g){n(this,UC);n(this,Ss);n(this,et);n(this,ms);n(this,ys);n(this,mI);n(this,fs);a(this,Ss,t),a(this,et,A),a(this,ms,e),a(this,ys,g),a(this,fs,kA.get().createContext(`SubscriptionWriter:${A.subscribe.name}`))}finalInfo(){return s(this,mI)}run(){return r(this,null,function*(){yield Promise.race([d(this,UC,or).call(this).catch(A=>s(this,fs).error("error writing subscription",A)),s(this,et).unsubscribed(),s(this,et).done(),s(this,et).expiryNotification().catch(y)])})}done(A,t){return r(this,null,function*(){if(s(this,et).isUnsubscribed())return;const e={type:J.SubscribeDone,id:s(this,et).subscribe.id,errorCode:A,reason:t,finalInfo:s(this,mI)};s(this,et).onDone(e),yield s(this,ys).push(e)})}[pt()](){return this.done(ZQ.TrackEnded,"Track ended")}[Symbol.asyncDispose](){return this.done(ZQ.TrackEnded,"Track ended")}}Ss=new WeakMap,et=new WeakMap,ms=new WeakMap,ys=new WeakMap,mI=new WeakMap,fs=new WeakMap,UC=new WeakSet,or=function(){return r(this,null,function*(){try{for(var C=EA(s(this,Ss)),Q,o,E;Q=!(o=yield C.next()).done;Q=!1){const c=o.value;var A=[];try{const h=s(this,et).range();if(h&&(h.startGroup>c.id||h.endGroup&&h.endGroup<c.id))break;const l=yield s(this,ms).openSendStream();const m=new cl(l);const f=Ct(A,new dl(m,c.consume(),s(this,et)),!0);yield f.run();a(this,mI,f.finalGroup())}catch(t){var e=t,g=!0}finally{var B=Qt(A,e,g);B&&(yield B)}}}catch(o){E=[o]}finally{try{Q&&(o=C.return)&&(yield o.call(C))}finally{if(E)throw E[0]}}})};class dl{constructor(A,t,e){n(this,Ei);n(this,ps);n(this,yI);n(this,Fs);n(this,fI);a(this,Ei,A),a(this,ps,t),a(this,yI,e),a(this,fI,kA.get().createContext(`GroupSubscriptionWriter:${e.subscribe.name}`))}finalGroup(){return s(this,Fs)}run(){return r(this,null,function*(){s(this,fI).debug("write group");try{for(var A=EA(s(this,ps)),t,e,g;t=!(e=yield A.next()).done;t=!1){const B=e.value;yield s(this,Ei).write({subscribeId:s(this,yI).subscribe.id,trackAlias:s(this,yI).subscribe.trackAlias,subGroupId:q(0),subscriberPriority:0,groupId:B.groupId,objectId:B.objectId,objectStatus:B.objectStatus,payload:B.payload}),a(this,Fs,{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,fI).debug("write group done")})}[pt()](){return s(this,Ei).close().catch(y)}[Symbol.asyncDispose](){return s(this,Ei).close().catch(y)}}Ei=new WeakMap,ps=new WeakMap,yI=new WeakMap,Fs=new WeakMap,fI=new WeakMap;class ll{constructor(A,t,e){n(this,De);I(this,"state");n(this,Gs);n(this,ri);this.state=A,a(this,Gs,t),a(this,ri,e)}ok(A){return r(this,null,function*(){var o,E,c;const t=(o=this.state.range())==null?void 0:o.startGroup,e=A.latest(),g=e==null?void 0:e.id,B=(c=(E=e==null?void 0:e.latest())==null?void 0:E.objectId)!=null?c:q(0),C=A.consume(t!=null?t:g),Q={type:J.SubscribeOk,id:this.state.subscribe.id,expires:q(0),groupOrder:"ascending",params:new Map,largestInfo:g?{group:g,object:B}:void 0};return yield s(this,ri).push(Q),new hl(this.state,C,s(this,Gs),s(this,ri))})}invalidRange(){return d(this,De,rg).call(this,q(1),"Invalid range")}retryTrackAlias(){return d(this,De,rg).call(this,q(2),"Retry track alias")}trackDoesNotExist(){return d(this,De,rg).call(this,q(3),"Track does not exist")}unauthorized(){return d(this,De,rg).call(this,q(4),"Unauthorized")}timeout(){return d(this,De,rg).call(this,q(5),"Timeout")}[pt()](){return this.trackDoesNotExist()}[Symbol.asyncDispose](){return this.trackDoesNotExist()}}Gs=new WeakMap,ri=new WeakMap,De=new WeakSet,rg=function(A,t){const e={type:J.SubscribeError,id:this.state.subscribe.id,errorCode:A,reason:t,trackAlias:this.state.subscribe.trackAlias};return s(this,ri).push(e)},mE=[xA({context:"Session",enter:"info",error:"error"})];class XQ{constructor(A,t,e){qi(Oo,5,this);n(this,pI);n(this,ks);n(this,FI);n(this,ci,kA.get().createContext("Publisher"));n(this,Se,new HA(new Map));n(this,me,new HA(new Map));n(this,ye,new z(10));a(this,pI,A),a(this,ks,t),a(this,FI,e)}announce(A){return r(this,null,function*(){if(s(this,Se).current().has(A.join("/")))throw new Error("Duplicate announcement");const t=new Map,e=s(this,pI).authToken();e&&t.set(AC,{type:AC,payload:new TextEncoder().encode(e)});const g={type:J.Announce,namespace:A,params:t},B=El(g);if(s(this,Se).update(Q=>Q.set(g.namespace.join("/"),B)),yield s(this,FI).push(g),!(yield Promise.race([B.state.ok(),s(this,pI).closed()])))throw new Error("Session closed")})}close(){s(this,me).current().forEach(A=>A.close()),s(this,me).close(),s(this,Se).close(),s(this,ye).close()}incomingSubscriptions(){return s(this,ye)}onMessage(A){return r(this,null,function*(){switch(A.type){case J.Subscribe:{const t=new iC(A);if(s(this,me).update(e=>(e.set(A.id,t),e)),s(this,ye).isFull()){const e=yield s(this,ye).pop();yield e==null?void 0:e.timeout()}yield s(this,ye).push(new ll(t,s(this,ks),s(this,FI)))}break;case J.SubscribeUpdate:{const t=s(this,me).current().get(A.id);t||s(this,ci).debug("No subscription found",A),t==null||t.onUpdate(A)}break;case J.Unsubscribe:{const t=s(this,me).current().get(A.id);t||s(this,ci).debug("No subscription found",A),t==null||t.onUnsubscribe(A)}break;case J.AnnounceOk:{const t=s(this,Se).current().get(A.namespace.join("/"));t||s(this,ci).debug("No announcement found",A),t==null||t.state.onOk(A)}break;case J.AnnounceError:{const t=s(this,Se).current().get(A.namespace.join("/"));t||s(this,ci).debug("No announcement found",A),t==null||t.state.onError(A)}break}})}}Oo=Hi(null),pI=new WeakMap,ks=new WeakMap,FI=new WeakMap,ci=new WeakMap,Se=new WeakMap,me=new WeakMap,ye=new WeakMap,PA(Oo,1,"announce",mE,XQ),He(Oo,XQ);function ul(i,A){const t=new iC(A),[e,g]=Z(100),B=new wl(t,e),C=new qa(i,t,g);return[B,C]}class wl{constructor(A,t){I(this,"state");n(this,hi);this.state=A,a(this,hi,t)}onDone(A){this.state.onDone(A)}onData(A){return s(this,hi).push(A)}onError(A){const t=this.state.onError(A);s(this,hi).abort(t)}close(){this.state.close(),s(this,hi).close()}}hi=new WeakMap;class qa{constructor(A,t,e){qi(Vo,5,this);n(this,UI);n(this,GI);n(this,GA);n(this,kI);n(this,RI,new G);a(this,GI,A),a(this,GA,t),a(this,kI,e)}get id(){return s(this,GA).subscribe.id}get trackAlias(){return s(this,GA).subscribe.trackAlias}get name(){return s(this,GA).subscribe.name}range(){return s(this,GA).range()}expiryNotification(){return s(this,GA).expiryNotification()}update(A,t){return r(this,null,function*(){const e={type:J.SubscribeUpdate,id:s(this,GA).subscribe.id,start:{group:A,object:q(0)},end:{group:t+q(1),object:q(0)},params:new Map,subscriberPriority:0};s(this,GA).onUpdate(e),yield s(this,GI).push(e)})}unsubscribe(){return r(this,null,function*(){const A={type:J.Unsubscribe,id:s(this,GA).subscribe.id};s(this,GA).onUnsubscribe(A),yield s(this,GI).push(A)})}close(){var A,t;return s(this,RI).resolve(),(t=(A=s(this,kI)).return)==null?void 0:t.call(A)}closed(){return s(this,RI).promise}done(){return s(this,GA).done()}expiryState(){return s(this,GA).expiryState()}unsubscribed(){return s(this,GA).isUnsubscribed()}return(){return r(this,null,function*(){return s(this,RI).resolve(),yield this.unsubscribe(),{done:!0,value:void 0}})}groups(){return Qe(this,null,function*(){var A,t;try{for(var m=EA(s(this,kI)),f,U,b;f=!(U=yield new aA(m.next())).done;f=!1){var Q=U.value;var o=[];try{const Y=Ct(o,Q,!0);try{for(var e=EA(Y.groups()),g,B,C;g=!(B=yield new aA(e.next())).done;g=!1){const N=B.value;const v=(A=s(this,GA).range())==null?void 0:A.startGroup,T=(t=s(this,GA).range())==null?void 0:t.endGroup;if(v&&N.groupId()<v)return{done:!0,value:void 0};if(T&&N.groupId()>T)return{done:!0,value:void 0};yield N}}catch(B){C=[B]}finally{try{g&&(B=e.return)&&(yield new aA(B.call(e)))}finally{if(C)throw C[0]}}}catch(E){var c=E,h=!0}finally{var l=Qt(o,c,h);l&&(yield new aA(l))}}}catch(U){b=[U]}finally{try{f&&(U=m.return)&&(yield new aA(U.call(m)))}finally{if(b)throw b[0]}}})}[Symbol.asyncIterator](){return this.groups()}objects(){return Qe(this,null,function*(){try{for(var B=EA(this.groups()),C,Q,o;C=!(Q=yield new aA(B.next())).done;C=!1){const E=Q.value;try{for(var A=EA(E),t,e,g;t=!(e=yield new aA(A.next())).done;t=!1){const c=e.value;yield c}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield new aA(e.call(A)))}finally{if(g)throw g[0]}}}}catch(Q){o=[Q]}finally{try{C&&(Q=B.return)&&(yield new aA(Q.call(B)))}finally{if(o)throw o[0]}}})}[(yE=[xA({context:"SubscriptionConsumer",enter:"info"})],pt())](){return d(this,UI,wB).call(this)}[Symbol.asyncDispose](){return d(this,UI,wB).call(this)}}Vo=Hi(null),GI=new WeakMap,GA=new WeakMap,kI=new WeakMap,RI=new WeakMap,UI=new WeakSet,wB=function(){return r(this,null,function*(){return yield this.close(),this.unsubscribe()})},wB=PA(Vo,17,"#dispose",yE,UI,wB),He(Vo,qa);const Dl=2e3;GE=[xA({context:"Session",return:"debug"})],FE=[xA({context:"Session",enter:"info",error:"error"})],pE=[xA({context:"Session",enter:"debug"})],fE=[xA({context:"Session",enter:"debug"})];class IC{constructor(A,t){qi(NI,5,this);n(this,Lt);n(this,zt);I(this,"nextSubscribeId",q(0));n(this,XA,new HA(new Map));n(this,di);n(this,li,kA.get().createContext("Subscriber"));a(this,zt,A),a(this,di,t),d(this,Lt,dQ).call(this).catch(y)}subscribe(g,B){return r(this,arguments,function*(A,t,e=new Map){const C=this.nextSubscribeId++,Q=s(this,zt).authToken();Q&&e.set(AC,{type:AC,payload:new TextEncoder().encode(Q)});const o={type:J.Subscribe,namespace:A,name:t.name,id:C,trackAlias:C,groupOrder:t.groupOrder,subscriberPriority:t.priority,filterType:t.filterType,params:e},[E,c]=ul(s(this,di),o);if(s(this,XA).update(l=>l.set(C,E)),yield s(this,di).push(o),!(yield Promise.race([E.state.ok(),s(this,zt).closed()])))throw new Error("Session closed");return c.closed().then(()=>Promise.race([Ye(Dl),this.closed()])).then(()=>d(this,Lt,cg).call(this,c.id)).catch(()=>d(this,Lt,cg).call(this,c.id)),c})}closed(){return s(this,zt).closed()}transportType(){return s(this,zt).transportType()}url(){return s(this,zt).url()}onMessage(A){return r(this,null,function*(){switch(A.type){case J.Announce:yield s(this,di).push({type:J.AnnounceOk,namespace:A.namespace});break;case J.SubscribeOk:{const t=s(this,XA).current().get(A.id);t&&t.state.onOk(A)}break;case J.SubscribeError:{const t=s(this,XA).current().get(A.id);t||s(this,li).debug("No subscription found",A),t==null||t.onError(A),d(this,Lt,cg).call(this,A.id)}break;case J.SubscribeDone:{const t=s(this,XA).current().get(A.id);t||s(this,li).debug("No subscription found",A),t==null||t.onDone(A)}break}})}onObjectReader(A){return r(this,null,function*(){const t=s(this,XA).current().get(A.subscribeId());if(!t){s(this,li).warn("No subscription found",A.subscribeId());return}yield t.onData(A)})}close(){s(this,XA).current().forEach(A=>A.close()),s(this,XA).close()}}NI=Hi(null),zt=new WeakMap,XA=new WeakMap,di=new WeakMap,li=new WeakMap,Lt=new WeakSet,dQ=function(){return r(this,null,function*(){try{for(var A=EA(s(this,XA)),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,li).debug("current subscriptions",C)}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}})},cg=function(A){s(this,XA).isClosed()||s(this,XA).update(t=>(t.delete(A),t))},dQ=PA(NI,17,"#observeChanges",GE,Lt,dQ),PA(NI,1,"subscribe",FE,IC),PA(NI,1,"close",pE,IC),cg=PA(NI,17,"#deleteSubscription",fE,Lt,cg),He(NI,IC);class jQ{constructor(A,t){qi(JI,5,this);n(this,mA);n(this,lt);n(this,Rs);n(this,ui);n(this,bI,kA.get().createContext("Session"));I(this,"subscriber");I(this,"publisher");n(this,LI);const[e,g]=Z(100);a(this,lt,A),a(this,ui,g),this.subscriber=new IC(this,e),this.publisher=new XQ(this,A,e),a(this,Rs,d(this,mA,ar).call(this)),a(this,LI,new HA(t)),this.closed().then(()=>this.close()).catch(y)}updateAuthToken(A){s(this,LI).update(A)}authToken(){return s(this,LI).current()}transportType(){return s(this,lt).transportType()}url(){return s(this,lt).url()}closed(){return s(this,Rs)}close(){try{this.subscriber.close(),this.publisher.close(),s(this,ui).cancel("closing"),s(this,lt).close()}catch(A){s(this,bI).warn("Error closing session",A)}}[(NE=[xA({context:"Session",return:"info",error:"error"})],UE=[xA({context:"Session",return:"info",error:"error"})],RE=[xA({context:"Session",return:"info",error:"error"})],kE=[xA({context:"Session",enter:"debug"})],Dn())](){d(this,mA,DB).call(this)}[Symbol.dispose](){d(this,mA,DB).call(this)}}JI=Hi(null),lt=new WeakMap,Rs=new WeakMap,ui=new WeakMap,bI=new WeakMap,LI=new WeakMap,mA=new WeakSet,nr=function(A){return r(this,null,function*(){var t,e;switch(s(this,bI).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 J.Goaway:break}})},ar=function(){return r(this,null,function*(){return(yield Promise.all([d(this,mA,uQ).call(this),d(this,mA,wQ).call(this),d(this,mA,lQ).call(this)])).find(t=>t instanceof Error)})},lQ=function(){return r(this,null,function*(){try{try{for(var A=EA(s(this,ui)),t,e,g;t=!(e=yield A.next()).done;t=!1){const B=e.value;s(this,bI).debug("sending message",B),yield s(this,lt).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}})},uQ=function(){return r(this,null,function*(){try{for(yield s(this,lt).afterHandshake();;){const A=yield s(this,lt).readMessage().catch(()=>{});if(!A)break;yield d(this,mA,nr).call(this,A)}}catch(A){return A}finally{s(this,ui).cancel("closing")}})},wQ=function(){return r(this,null,function*(){var A;try{for(;;){const t=yield s(this,lt).objectStream();if(!t)break;yield(A=this.subscriber)==null?void 0:A.onObjectReader(t)}}catch(t){return t}})},DB=function(){this.close()},lQ=PA(JI,17,"#runOutgoingMessages",NE,mA,lQ),uQ=PA(JI,17,"#runControl",UE,mA,uQ),wQ=PA(JI,17,"#runObjects",RE,mA,wQ),DB=PA(JI,17,"#dispose",kE,mA,DB),He(JI,jQ);const Sl=128;class ml{constructor(A,t,e){n(this,JA);n(this,it);n(this,Us);n(this,wi,!0);n(this,MI,!1);n(this,Ns);a(this,it,A),a(this,Us,t),a(this,Ns,e)}writeUnsigned8(A){return r(this,null,function*(){return d(this,JA,Ki).call(this),yield d(this,JA,Yi).call(this),s(this,it).writeUnsigned8(A)})}writeVarInt(A){return r(this,null,function*(){return d(this,JA,Ki).call(this),yield d(this,JA,Yi).call(this),s(this,it).writeVarInt(A)})}writeBigVarInt(A){return r(this,null,function*(){return d(this,JA,Ki).call(this),yield d(this,JA,Yi).call(this),s(this,it).writeBigVarInt(A)})}write(A){return r(this,null,function*(){return d(this,JA,Ki).call(this),yield d(this,JA,Yi).call(this),s(this,it).write(A)})}writeString(A){return r(this,null,function*(){return d(this,JA,Ki).call(this),yield d(this,JA,Yi).call(this),s(this,it).writeString(A)})}flush(){return r(this,null,function*(){d(this,JA,Ki).call(this),a(this,wi,!0),yield s(this,it).flush()})}close(){return r(this,null,function*(){s(this,MI)||(a(this,wi,!0),yield d(this,JA,Yi).call(this,!1),yield s(this,it).flush(),a(this,MI,!0),s(this,Ns).call(this))})}}it=new WeakMap,Us=new WeakMap,wi=new WeakMap,MI=new WeakMap,Ns=new WeakMap,JA=new WeakSet,Ki=function(){if(s(this,MI))throw new Error("Stream is closed")},Yi=function(A=!0){if(s(this,wi))return a(this,wi,!1),s(this,it).writeUnsigned8(s(this,Us)|(A?Sl:0))};class yl{constructor(A,t){n(this,NC);n(this,fe);n(this,_t);n(this,HI);n(this,Di);n(this,$t,new Map);n(this,qI,kA.get().createContext("WebSocketConnection"));n(this,vI,new Set(new Array(128).fill(0).map((A,t)=>t+1)));a(this,fe,A),a(this,_t,t),a(this,HI,new ReadableStream(new Md(A))),s(this,fe).addEventListener("close",()=>{s(this,_t).markPostHandshake(),s(this,$t).forEach(e=>e.close())})}openSendStream(){const A=s(this,vI).values().next().value;if(!A)throw new Error("No stream IDs available");return s(this,vI).delete(A),Promise.resolve(new ml(new mg(s(this,fe)),A,()=>d(this,NC,Er).call(this,A)))}transportType(){return"websocket"}url(){return s(this,fe).url}afterHandshake(){return s(this,_t).postHandshake()}objectStream(){return r(this,null,function*(){var A;for(;;){a(this,Di,s(this,HI).getReader());try{const{value:t,done:e}=yield s(this,Di).read();if(e)return;const[g,B,C]=t;if(s(this,$t).has(q(B))){const Q=s(this,$t).get(q(B));if(!Q)throw new Error("Stream not found");C.length>0&&(yield Q.push(C)),g||(s(this,qI).debug("Closing stream",{streamId:B}),Q.close(),s(this,$t).delete(q(B)))}else{let c;s(this,qI).debug("Creating new stream",{streamId:B});const[Q,o]=Z(1e3),E=new ReadableStream({pull(h){return r(this,null,function*(){const l=yield o.pop();l?h.enqueue(l):h.close()})}});if(s(this,$t).set(q(B),Q),g||(s(this,qI).debug("Closing new stream",{streamId:B}),yield E.cancel(),s(this,$t).delete(q(B))),C.length>0)return yield ua(new zB(C,E),B)}}finally{(A=s(this,Di))==null||A.releaseLock()}}})}close(){var A;return s(this,_t).cancel().catch(y),s(this,HI).cancel("closing").catch(y),(A=s(this,Di))==null||A.cancel("closing").catch(y),s(this,fe).close()}closed(){return Promise.resolve()}writeMessage(A){return r(this,null,function*(){yield s(this,_t).write(A)})}readMessage(){return r(this,null,function*(){return s(this,_t).read()})}}fe=new WeakMap,_t=new WeakMap,HI=new WeakMap,Di=new WeakMap,$t=new WeakMap,qI=new WeakMap,vI=new WeakMap,NC=new WeakSet,Er=function(A){s(this,vI).add(A)};class fl{constructor(A,t,e){n(this,LC);n(this,Ae);n(this,te);n(this,pe,new z(100));n(this,bs);n(this,Ls,0);n(this,bC,kA.get().createContext("WebTransportConnection"));a(this,bs,e),a(this,Ae,A),a(this,te,t),d(this,LC,rr).call(this).catch(g=>{s(this,bC).debug("Incoming streams handling ended with error",g),s(this,te).markPostHandshake(),s(this,pe).close()}),s(this,Ae).closed.then(()=>{s(this,te).markPostHandshake(),s(this,pe).close()})}openSendStream(){return r(this,null,function*(){const A=yield s(this,Ae).createUnidirectionalStream();return new wa(A)})}transportType(){return"webtransport"}url(){return s(this,bs)}afterHandshake(){return s(this,te).postHandshake()}closed(){return r(this,null,function*(){yield s(this,Ae).closed})}close(){s(this,Ae).close()}writeMessage(A){return r(this,null,function*(){yield s(this,te).write(A)})}readMessage(){return r(this,null,function*(){return s(this,te).read()})}objectStream(){return r(this,null,function*(){return s(this,pe).pop()})}}Ae=new WeakMap,te=new WeakMap,pe=new WeakMap,bs=new WeakMap,Ls=new WeakMap,bC=new WeakMap,LC=new WeakSet,rr=function(){return r(this,null,function*(){const A=s(this,Ae).incomingUnidirectionalStreams.getReader();for(;;){const{value:t,done:e}=yield A.read();if(e){s(this,pe).close();return}const g=new zB(new Uint8Array,t);yield s(this,pe).push(ua(g,s(this,Ls))),ft(this,Ls)._++}})};function zQ(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=eC.wrapWebsocket(A);Ha(t,i.role).catch(()=>{A.close()});const e=new yl(A,t);return new jQ(e,i.authToken)})}function pl(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=eC.wrapWebTransport(g);Ha(B,i.role).catch(()=>{e.close()});const C=new fl(e,B,i.url.toString());return new jQ(C,i.authToken)})}function Fl(i){return r(this,null,function*(){if(self.WebTransport&&(i==null?void 0:i.preferredTransport)!=="websocket"&&i.url.protocol.startsWith("https")){const A=pl(i).catch(()=>zQ(i)),t=yield Promise.race([A,Ye(i.websocketFallbackTimeoutMs)]);return t||zQ(i)}return zQ(i)})}class xt{constructor(){n(this,ee,{name:"",priority:0,groupOrder:"ascending",filterType:{type:"latest-group"}})}name(A){return s(this,ee).name=A,this}priority(A){return s(this,ee).priority=A,this}groupOrder(A){return s(this,ee).groupOrder=A,this}startGroup(A){return s(this,ee).filterType={type:"absolute-start",start:{group:A,object:q(0)}},this}range(A,t){return s(this,ee).filterType={type:"absolute-range",start:{group:A,object:q(0)},end:{group:t,object:q(0)}},this}build(){return s(this,ee)}}ee=new WeakMap;class va{constructor(A,t){n(this,KI);n(this,Js);a(this,KI,A),a(this,Js,t)}subscribe(A,t=new Map){return s(this,KI).subscribe(this.namespace(),A,t)}closed(){return s(this,KI).closed()}namespace(){return s(this,Js).namespace}}KI=new WeakMap,Js=new WeakMap;function Gl(i,A){return["com.vindral.moq",i]}function Oe(i){const A=i[1];if(!A)throw new Error("namespace must contain a channel ID");return A}function kl(i){return"tracks"in i}function Rl(i){const A=new TextDecoder().decode(i);return JSON.parse(A)}const Zo=class Zo{constructor(A,t){n(this,Hs);n(this,jA);n(this,Jt);n(this,Si,new L(100));n(this,It);n(this,Ms);n(this,JC,A=>r(this,null,function*(){if(!A)return s(this,jA).close();if(s(this,It))return;const t=s(this,Si).items().reduce((e,g)=>e<g?e:g,A);a(this,It,d(this,Hs,En).call(this,t,A)),s(this,It).size===0&&(yield s(this,jA).close())}));a(this,jA,A),a(this,Jt,t),A.done().then(e=>r(this,null,function*(){var g;return s(this,JC).call(this,(g=e.finalInfo)==null?void 0:g.group)})).catch(y),a(this,Ms,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,jA).id}name(){return s(this,jA).name}largestGroupId(){return s(this,Jt)}needsRenewal(){return s(this,jA).expiryState()==="active"&&s(this,It)===void 0}endOfTrack(A){const t=s(this,Si).items().reduce((e,g)=>e<g?e:g,A);return this.update(t,A)}update(A,t){return r(this,null,function*(){return a(this,It,d(this,Hs,En).call(this,A,t)),s(this,It).size===0&&(yield s(this,jA).close()),s(this,jA).update(A,t)})}unsubscribe(){return s(this,jA).unsubscribe()}next(){return r(this,null,function*(){var e;if(s(this,It)&&s(this,It).size===0)return{done:!0,value:void 0};const A=yield s(this,Ms).next();if(A.done)return A;const t=A.value.groupId();return(e=s(this,It))==null||e.delete(t),s(this,Si).push(t),s(this,Jt)||a(this,Jt,t),a(this,Jt,s(this,Jt)<t?t:s(this,Jt)),A})}return(){return s(this,jA).return()}[Symbol.asyncIterator](){return this}};jA=new WeakMap,Jt=new WeakMap,Si=new WeakMap,It=new WeakMap,Ms=new WeakMap,JC=new WeakMap,Hs=new WeakSet,En=function(A,t){const e=new Set;for(let g=A;g<=t;g++)e==null||e.add(g);return s(this,Si).items().forEach(g=>{e==null||e.delete(g)}),e};let gC=Zo;const Xo=class Xo{constructor(A){n(this,qs);n(this,ut);n(this,mi);n(this,ie,new z(10));n(this,Mt);n(this,vs,(A,t)=>r(this,null,function*(){var h=[];try{const e=Ct(h,yield s(this,ut).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 xt().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+q(1));break}const o=Q.build();g.newTrack=o;const[E]=yield Promise.all([A.subscribe(o),C?e.value.update(B,B):e.value.unsubscribe()]);E.done().then(()=>d(this,qs,rn).call(this,E)).catch(y);E.expiryNotification().then(()=>s(this,vs).call(this,A,o)).catch(y);const c=new gC(E,B);e.value=c;yield s(this,ie).push(c);s(this,Mt).info("Subscription renewed",g)}catch(l){var m=l,f=!0}finally{Qt(h,m,f)}}));a(this,ut,new Or(A)),a(this,mi,A),a(this,Mt,kA.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 gC(C,B));return C.done().then(()=>{var o;return d(o=Q,qs,rn).call(o,C)}).catch(y),C.expiryNotification().then(()=>{var o;return s(o=Q,vs).call(o,A,t)}).catch(y),Q})}largestGroupId(){return s(this,ut).unsafeValue().largestGroupId()}update(A,t){return r(this,null,function*(){var g=[];try{const e=Ct(g,yield s(this,ut).lock());s(this,ie).close();return e.value.update(A,t)}catch(B){var C=B,Q=!0}finally{Qt(g,C,Q)}})}endOfTrack(A){return r(this,null,function*(){var e=[];try{const t=Ct(e,yield s(this,ut).lock());s(this,ie).close();return t.value.endOfTrack(A)}catch(g){var B=g,C=!0}finally{Qt(e,B,C)}})}unsubscribe(){return r(this,null,function*(){var t=[];try{const A=Ct(t,yield s(this,ut).lock());s(this,ie).close();return A.value.unsubscribe()}catch(e){var g=e,B=!0}finally{Qt(t,g,B)}})}return(){return r(this,null,function*(){var t=[];try{const A=Ct(t,yield s(this,ut).lock());s(this,ie).close();return A.value.return()}catch(e){var g=e,B=!0}finally{Qt(t,g,B)}})}next(){return r(this,null,function*(){var t,e;const A=yield s(this,mi).next();if(A.done){yield(e=(t=s(this,mi)).return)==null?void 0:e.call(t);const g=yield s(this,ie).pop();if(g)return a(this,mi,g),this.next()}return A})}[Symbol.asyncIterator](){return this}objects(){return Qe(this,null,function*(){try{for(var Q=EA(this),o,E,c;o=!(E=yield new aA(Q.next())).done;o=!1){var A=E.value;var t=[];try{const h=Ct(t,A,!0);yield*Cn(h)}catch(e){var g=e,B=!0}finally{var C=Qt(t,g,B);C&&(yield new aA(C))}}}catch(E){c=[E]}finally{try{o&&(E=Q.return)&&(yield new aA(E.call(Q)))}finally{if(c)throw c[0]}}})}};ut=new WeakMap,mi=new WeakMap,ie=new WeakMap,Mt=new WeakMap,qs=new WeakSet,rn=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,ut).unsafeValue().subscribeId()!==A.id){s(this,Mt).info("subscribeId mismatch - the subscription already has been renewed");return}return this.return()})},vs=new WeakMap;let ae=Xo;const Ul="catalog";function Ka(i){const A=Rl(i.payload);if(!kl(A))throw new Error("unexpected catalog type");return A}const HC=class HC{constructor(A,t,e){n(this,MC);n(this,Fe);n(this,Ks);n(this,Ys);n(this,Ts);a(this,Ks,A),a(this,Fe,t),a(this,Ys,e),a(this,Ts,d(this,MC,cr).call(this)),this.closed().finally(()=>s(this,Fe).close()).catch(y)}catalog(){return s(this,Fe)}closed(){return s(this,Ts)}close(){return r(this,null,function*(){return s(this,Fe).close(),(yield s(this,Ks).promise).unsubscribe()})}static start(A,t){return r(this,null,function*(){const e=G.fromPromise(ae.subscribe(A,new xt().name(t.catalogName||Ul).groupOrder("ascending").build())),g=G.fromPromise(e.promise.then(o=>o.objects()));if(t.catalog)return new HC(e,new HA(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 HC(e,new HA(Q),g)})}};Fe=new WeakMap,Ks=new WeakMap,Ys=new WeakMap,Ts=new WeakMap,MC=new WeakSet,cr=function(){return r(this,null,function*(){const A=yield s(this,Ys).promise;try{for(var t=EA(A),e,g,B;e=!(g=yield t.next()).done;e=!1){const C=g.value;if(C.objectStatus!==qA.Normal)continue;const Q=Ka(C);s(this,Fe).update(Q)}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield g.call(t))}finally{if(B)throw B[0]}}})};let _Q=HC;class Nl{constructor(A,t,e,g){n(this,Ws);n(this,Ps);n(this,YI);n(this,xs);I(this,"track");n(this,TI,kA.get().createContext("CmafGroup"));this.track=g,a(this,Ps,e),a(this,YI,A),a(this,xs,t)}[Symbol.asyncIterator](){return Qe(this,null,function*(){const A={name:this.track.trackObject.name,namespace:this.track.namespace};s(this,TI).debug("start",S({},A));try{for(var t=EA(s(this,YI)),e,g,B;e=!(g=yield new aA(t.next())).done;e=!1){const C=g.value;if(C.objectStatus===qA.EndOfTrackAndGroup&&(yield new aA(this.track.endOfTrack(C.groupId))),C.objectStatus!==qA.Normal)continue;const Q=s(this,xs).createFragment(C.payload),o=Q.timescale(),E=Q.baseMediaDecodeTime()/o*1e3,c=Q.duration()/o*1e3,h=E+c,l=s(this,Ps)/1e3*o;Q.updateBaseMediaDecodeTime(Q.baseMediaDecodeTime()-l);const m=this.track.timestampRange();if(m&&E>=m[1])break;s(this,TI).debug("fragment",V(S({},A),{startTime:E,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 aA(g.call(t)))}finally{if(B)throw B[0]}}s(this,TI).debug("end",S({},A))})}[pt()](){return d(this,Ws,cn).call(this)}[Symbol.asyncDispose](){return d(this,Ws,cn).call(this)}}Ps=new WeakMap,YI=new WeakMap,xs=new WeakMap,TI=new WeakMap,Ws=new WeakSet,cn=function(){return r(this,null,function*(){var A,t;return yield(t=(A=s(this,YI)).return)==null?void 0:t.call(A),Promise.resolve()})};const PI=class PI{constructor(A,t,e,g,B){n(this,Os);n(this,Ht);n(this,Vs);n(this,Zs);I(this,"trackObject");I(this,"namespace");this.trackObject=A,this.namespace=t,a(this,Ht,e),a(this,Os,g),a(this,Vs,B)}static subscribe(C,Q,o){return r(this,arguments,function*(A,t,{timestampOffsetMs:e,startGroup:g,params:B}){var f;if(t.format!=="cmaf")throw new Error("format must be cmaf");const E=new xt().name(t.name);g&&E.startGroup(g);const c=E.build();if(t.initTrack){const U=new xt().name(t.initTrack).build(),[b,Y]=yield Promise.all([d(f=PI,qC,hr).call(f,A,U),ae.subscribe(A,c,{params:B,largestGroupId:g?g-q(1):void 0})]),N=new Ba(b);return new PI(t,A.namespace(),Y,N,e)}k(t.initData,"no init data found on track");const h=QA(t.initData),l=new Ba(new Uint8Array(h)),m=yield ae.subscribe(A,c,{params:B,largestGroupId:g?g-q(1):void 0});return new PI(t,A.namespace(),m,l,e)})}largestGroupId(){return s(this,Ht).largestGroupId()}stopAfterTimestampReached(A){a(this,Zs,[0,A])}timestampRange(){return s(this,Zs)}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 Nl(A.value,s(this,Os),s(this,Vs),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()})}};Os=new WeakMap,Ht=new WeakMap,Vs=new WeakMap,Zs=new WeakMap,qC=new WeakSet,hr=function(A,t){return r(this,null,function*(){var B=[];try{const e=Ct(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 E=Qt(B,Q,o);E&&(yield E)}})},n(PI,qC);let $Q=PI;const Ya=1e4,bl=3e4,jo=class jo{constructor(A,t,e){n(this,fi);n(this,vC,kA.get().createContext("Timeline"));n(this,Ge,new HA([]));n(this,yi);n(this,Xs);n(this,js);n(this,zs);a(this,Xs,A),a(this,js,e),a(this,yi,t),a(this,zs,d(this,fi,hn).call(this,s(this,yi))),this.closed().finally(()=>s(this,Ge).close()).catch(y)}closed(){return s(this,zs)}close(){return r(this,null,function*(){return(yield s(this,yi).promise).unsubscribe()})}timeline(){const[A,t]=s(this,Ge).value();return A}timestampWallclockOffset(){return Wi(this.timeline().map(A=>A.mediaPts-A.wallclock))}static start(A,t){const e=G.fromPromise(ae.subscribe(A,new xt().name(t).groupOrder("ascending").build()));return new jo(A,e,t)}waitForWallclockTime(A){return r(this,null,function*(){return yield s(this,Ge).waitFor(t=>!!t.find(e=>e.wallclock>=A)),this.timeline()})}waitForTimelineToHaveMinDuration(){return r(this,null,function*(){return yield s(this,Ge).waitFor(A=>{const t=A[0],e=A[A.length-1];return!t||!e?!1:e.wallclock-t.wallclock>Ya}),this.timeline()})}};vC=new WeakMap,Ge=new WeakMap,yi=new WeakMap,Xs=new WeakMap,js=new WeakMap,zs=new WeakMap,fi=new WeakSet,hn=function(A){return r(this,null,function*(){const t=yield A.promise;try{for(var m=EA(t),f,U,b;f=!(U=yield m.next()).done;f=!1){var Q=U.value;var o=[];try{const Y=Ct(o,Q,!0);try{for(var e=EA(Y),g,B,C;g=!(B=yield e.next()).done;g=!1){const N=B.value;if(N.objectStatus!==qA.Normal)continue;const v=Ll(N.payload);s(this,Ge).update(T=>{var P,X;for(T.push(...v),T.sort((yA,BA)=>yA.wallclock-BA.wallclock);T[0]&&((X=(P=T[T.length-1])==null?void 0:P.wallclock)!=null?X:0)-T[0].wallclock>bl;)T.shift();return T}),t===s(this,yi).resolved&&N.groupId>q(0)&&N.objectId==q(0)&&d(this,fi,dr).call(this,N.groupId).catch(T=>{s(this,vC).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(E){var c=E,h=!0}finally{var l=Qt(o,c,h);l&&(yield l)}}}catch(U){b=[U]}finally{try{f&&(U=m.return)&&(yield U.call(m))}finally{if(b)throw b[0]}}})},dr=function(A){return r(this,null,function*(){const t=A-q(1),e=this.timeline(),g=e[0],B=e[e.length-1];if(!g||!B||B.wallclock-g.wallclock>Ya)return;const C=G.fromPromise(ae.subscribe(s(this,Xs),new xt().name(s(this,js)).groupOrder("ascending").range(t,t).build()));return d(this,fi,hn).call(this,C)})};let Ao=jo;function Ll(i){var t;const A=new TextDecoder("utf-8").decode(i).split(`
1
+ (function(u,D){typeof exports=="object"&&typeof module!="undefined"?D(exports):typeof define=="function"&&define.amd?define(["exports"],D):(u=typeof globalThis!="undefined"?globalThis:u||self,D(u.Vindral={}))})(this,(function(u){"use strict";var Dw=Object.create;var gn=Object.defineProperty,Sw=Object.defineProperties,mw=Object.getOwnPropertyDescriptor,yw=Object.getOwnPropertyDescriptors;var EQ=Object.getOwnPropertySymbols;var vE=Object.prototype.hasOwnProperty,KE=Object.prototype.propertyIsEnumerable;var Tt=(u,D)=>(D=Symbol[u])?D:Symbol.for("Symbol."+u),Ce=u=>{throw TypeError(u)},sn=Math.pow,rQ=(u,D,p)=>D in u?gn(u,D,{enumerable:!0,configurable:!0,writable:!0,value:p}):u[D]=p,S=(u,D)=>{for(var p in D||(D={}))vE.call(D,p)&&rQ(u,p,D[p]);if(EQ)for(var p of EQ(D))KE.call(D,p)&&rQ(u,p,D[p]);return u},V=(u,D)=>Sw(u,yw(D)),qE=(u,D)=>gn(u,"name",{value:D,configurable:!0});var YE=(u,D)=>{var p={};for(var k in u)vE.call(u,k)&&D.indexOf(k)<0&&(p[k]=u[k]);if(u!=null&&EQ)for(var k of EQ(u))D.indexOf(k)<0&&KE.call(u,k)&&(p[k]=u[k]);return p};var Hi=u=>{var D;return[,,,Dw((D=u==null?void 0:u[Tt("metadata")])!=null?D:null)]},TE=["class","method","getter","setter","accessor","field","value","get","set"],dB=u=>u!==void 0&&typeof u!="function"?Ce("Function expected"):u,fw=(u,D,p,k,y)=>({kind:TE[u],name:D,metadata:k,addInitializer:G=>p._?Ce("Already initialized"):y.push(dB(G||null))}),He=(u,D)=>rQ(D,Tt("metadata"),u[3]),qi=(u,D,p,k)=>{for(var y=0,G=u[D>>1],L=G&&G.length;y<L;y++)D&1?G[y].call(p):k=G[y].call(p,k);return k},PA=(u,D,p,k,y,G)=>{var L,Z,z,QA,q,_=D&7,ot=!!(D&8),hA=!!(D&16),DA=_>3?u.length+1:_?ot?1:2:0,mB=TE[_+5],yB=_>3&&(u[DA-1]=[]),mQ=u[DA]||(u[DA]=[]),VA=_&&(!hA&&!ot&&(y=y.prototype),_<5&&(_>3||!hA)&&mw(_<4?y:{get[p](){return s(this,G)},set[p](pA){return a(this,G,pA)}},p));_?hA&&_<4&&qE(G,(_>2?"set ":_>1?"get ":"")+p):qE(y,p);for(var Ti=k.length-1;Ti>=0;Ti--)QA=fw(_,p,z={},u[3],mQ),_&&(QA.static=ot,QA.private=hA,q=QA.access={has:hA?pA=>pw(y,pA):pA=>p in pA},_^3&&(q.get=hA?pA=>(_^1?s:d)(pA,y,_^4?G:VA.get):pA=>pA[p]),_>2&&(q.set=hA?(pA,dg)=>a(pA,y,dg,_^4?G:VA.set):(pA,dg)=>pA[p]=dg)),Z=(0,k[Ti])(_?_<4?hA?G:VA[mB]:_>4?void 0:{get:VA.get,set:VA.set}:y,QA),z._=1,_^4||Z===void 0?dB(Z)&&(_>4?yB.unshift(Z):_?hA?G=Z:VA[mB]=Z:y=Z):typeof Z!="object"||Z===null?Ce("Object expected"):(dB(L=Z.get)&&(VA.get=L),dB(L=Z.set)&&(VA.set=L),dB(L=Z.init)&&yB.unshift(L));return _||He(u,y),VA&&gn(y,p,VA),hA?_^4?G:VA:y},I=(u,D,p)=>rQ(u,typeof D!="symbol"?D+"":D,p),Bn=(u,D,p)=>D.has(u)||Ce("Cannot "+p),pw=(u,D)=>Object(D)!==D?Ce('Cannot use the "in" operator on this value'):u.has(D),s=(u,D,p)=>(Bn(u,D,"read from private field"),p?p.call(u):D.get(u)),n=(u,D,p)=>D.has(u)?Ce("Cannot add the same private member more than once"):D instanceof WeakSet?D.add(u):D.set(u,p),a=(u,D,p,k)=>(Bn(u,D,"write to private field"),k?k.call(u,p):D.set(u,p),p),d=(u,D,p)=>(Bn(u,D,"access private method"),p);var ft=(u,D,p,k)=>({set _(y){a(u,D,y,p)},get _(){return s(u,D,k)}});var r=(u,D,p)=>new Promise((k,y)=>{var G=z=>{try{Z(p.next(z))}catch(QA){y(QA)}},L=z=>{try{Z(p.throw(z))}catch(QA){y(QA)}},Z=z=>z.done?k(z.value):Promise.resolve(z.value).then(G,L);Z((p=p.apply(u,D)).next())}),aA=function(u,D){this[0]=u,this[1]=D},Qe=(u,D,p)=>{var k=(L,Z,z,QA)=>{try{var q=p[L](Z),_=(Z=q.value)instanceof aA,ot=q.done;Promise.resolve(_?Z[0]:Z).then(hA=>_?k(L==="return"?L:"next",Z[1]?{done:hA.done,value:hA.value}:hA,z,QA):z({value:hA,done:ot})).catch(hA=>k("throw",hA,z,QA))}catch(hA){QA(hA)}},y=L=>G[L]=Z=>new Promise((z,QA)=>k(L,Z,z,QA)),G={};return p=p.apply(u,D),G[Tt("asyncIterator")]=()=>G,y("next"),y("throw"),y("return"),G},Cn=u=>{var D=u[Tt("asyncIterator")],p=!1,k,y={};return D==null?(D=u[Tt("iterator")](),k=G=>y[G]=L=>D[G](L)):(D=D.call(u),k=G=>y[G]=L=>{if(p){if(p=!1,G==="throw")throw L;return L}return p=!0,{done:!1,value:new aA(new Promise(Z=>{var z=D[G](L);z instanceof Object||Ce("Object expected"),Z(z)}),1)}}),y[Tt("iterator")]=()=>y,k("next"),"throw"in D?k("throw"):y.throw=G=>{throw G},"return"in D&&k("return"),y},EA=(u,D,p)=>(D=u[Tt("asyncIterator")])?D.call(u):(u=u[Tt("iterator")](),D={},p=(k,y)=>(y=u[k])&&(D[k]=G=>new Promise((L,Z,z)=>(G=y.call(u,G),z=G.done,Promise.resolve(G.value).then(QA=>L({value:QA,done:z}),Z)))),p("next"),p("return"),D);var Ct=(u,D,p)=>{if(D!=null){typeof D!="object"&&typeof D!="function"&&Ce("Object expected");var k,y;p&&(k=D[Tt("asyncDispose")]),k===void 0&&(k=D[Tt("dispose")],p&&(y=k)),typeof k!="function"&&Ce("Object not disposable"),y&&(k=function(){try{y.call(this)}catch(G){return Promise.reject(G)}}),u.push([p,k,D])}else p&&u.push([p]);return D},Qt=(u,D,p)=>{var k=typeof SuppressedError=="function"?SuppressedError:function(L,Z,z,QA){return QA=Error(z),QA.name="SuppressedError",QA.error=L,QA.suppressed=Z,QA},y=L=>D=p?new k(L,D,"An error was suppressed during disposal"):(p=!0,L),G=L=>{for(;L=u.pop();)try{var Z=L[1]&&L[1].call(L[2]);if(L[0])return Promise.resolve(Z).then(G,z=>(y(z),G()))}catch(z){y(z)}if(p)throw D};return G()};var Wt,zi,at,kg,Rg,Ft,Et,lA,Ot,Ee,je,Ug,ze,_i,$i,Ng,Qn,_e,$e,tt,rt,Ai,ti,bg,tA,ei,Vt,ct,Gt,FA,ce,he,uC,AI,Lg,Jg,uA,PE,xE,WE,OE,wC,DC,VE,lB,SC,ZE,XE,As,ts,es,is,vA,WA,gA,II,de,Zt,ii,jE,on,kt,gI,sI,Is,gs,BI,ss,Bs,Rt,CI,Cs,Qs,QI,Ii,zE,nn,ht,oI,os,nI,ns,as,Es,aI,yC,gi,_E,an,ue,rs,Ut,si,Bi,Ci,Nt,cs,Qi,bt,fC,IA,uB,cQ,vi,hQ,qe,EI,rI,Xt,pC,OA,ZA,oi,FC,jt,cI,cA,$E,Ar,tr,er,ir,Ir,gr,sr,Br,Cr,hI,ds,ls,SA,us,dI,lI,ws,GC,Qr,kC,wI,DI,we,ni,RC,ai,dt,LA,Ds,Ss,et,ms,ys,mI,fs,UC,or,Ei,ps,yI,Fs,fI,Gs,ri,De,rg,mE,pI,ks,FI,ci,Se,me,ye,Oo,hi,yE,GI,GA,kI,RI,Vo,UI,wB,fE,pE,FE,GE,zt,XA,di,li,NI,Lt,dQ,cg,kE,RE,UE,NE,lt,Rs,ui,bI,LI,mA,nr,ar,JI,lQ,uQ,wQ,DB,it,Us,wi,MI,Ns,JA,Ki,Yi,fe,_t,HI,Di,$t,qI,vI,NC,Er,Ae,te,pe,bs,Ls,bC,LC,rr,ee,KI,Js,jA,Jt,Si,It,Ms,JC,Hs,En,ut,mi,ie,Mt,qs,rn,vs,Fe,Ks,Ys,Ts,MC,cr,Ps,YI,xs,TI,Ws,cn,Os,Ht,Vs,Zs,qC,hr,vC,Ge,yi,Xs,js,zs,fi,hn,dr,KC,_s,ke,xI,bE,pi,Fi,Gi,Re,_o,WI,DQ,ki,$s,YC,lr,AB,TC,ur,PC,VI,ZI,tB,eB,LE,JE,ME,XI,jI,Ri,UA,wt,Dt,Ue,zI,iB,IB,Ie,KA,SQ,SB,wr,dn,NA,YA,St,Ui,nA,Ne,gB,sB,xC,_I,TA,Dr,$I,BB,Ag,Sr,mr,yr,fr,ln,ge,Ni,WC,pr,tg,be,eg,vt,ig,se,Ig,gg,sg,OC,VC,ZC,Fr,Je,CB,Kt,bA,bi,gt,Gr,hg,kr,_C,$,QB,oB,nB,Me,Qg,Rr,Ur,$C,Li,zA,Ji,og,Nr,br;const D=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")}};class p{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}}function k(i,A){if(!i)throw new Error(A)}const y=()=>{};class G{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(y)}static resolved(A){const t=new G;return t.resolve(A),t}static fromPromise(A){const t=new G;return t.promise=A,A.then(e=>{t.pending=!1,t.resolved=e},e=>{t.pending=!1,t.reject(e)}),t}}class L{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 Z(i){const A=new z(i);return[A,A]}class z{constructor(A){n(this,Wt);n(this,zi,new G);n(this,at);n(this,kg,!1);a(this,Wt,new L(A))}isFull(){return s(this,Wt).isFull()}close(){var A;(A=s(this,at))==null||A.resolve(),a(this,kg,!0)}abort(A){var t,e;(t=s(this,at))==null||t.promise.catch(y),(e=s(this,at))==null||e.reject(A)}push(A){return r(this,null,function*(){var t;s(this,Wt).isFull()&&(yield s(this,zi).promise),s(this,Wt).push(A),(t=s(this,at))==null||t.resolve(),a(this,at,new G)})}pop(){return r(this,null,function*(){var A;for(;!(s(this,kg)&&s(this,Wt).isEmpty());){const t=s(this,Wt).pop();if(t)return s(this,zi).resolve(),a(this,zi,new G),t;s(this,at)||a(this,at,new G),yield(A=s(this,at))==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}}Wt=new WeakMap,zi=new WeakMap,at=new WeakMap,kg=new WeakMap;function QA(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 q(i){return typeof BigInt=="function"?BigInt(i):i}class _{constructor(A,t=0){n(this,Rg);n(this,Ft);n(this,Et);I(this,"position",()=>s(this,Et));I(this,"peekBit",()=>this.getBit(s(this,Ft),s(this,Et)));I(this,"readBit",()=>{const A=this.peekBit();return ft(this,Et)._++,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,Et)._++)?1:0);return t});I(this,"remainingBits",()=>s(this,Ft).byteLength*8-s(this,Et));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,Et)._++)===0;)A++;let t=1<<A;for(let e=A-1;e>=0;e--)t|=this.getBit(s(this,Ft),ft(this,Et)._++)<<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});a(this,Rg,A),a(this,Ft,new Uint8Array(s(this,Rg))),a(this,Et,t)}bytes(){return s(this,Ft)}}Rg=new WeakMap,Ft=new WeakMap,Et=new WeakMap;function ot(){const i=self.MediaSource,A=self.ManagedMediaSource;return i!=null?i:A}const hA=new RegExp("(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"),DA=navigator.userAgent.toLowerCase(),mB=hA.test(DA),yB=()=>{const i=document.createElement("video");return i.canPlayType("application/vnd.apple.mpegURL")!==""||i.canPlayType("audio/mpegurl")!==""},mQ=()=>{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},VA=()=>DA.indexOf("CrKey")!==-1,Ti=()=>navigator.platform==="MacIntel"&&navigator.maxTouchPoints===0,pA=()=>navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,dg=()=>DA.indexOf("iphone")>=0&&DA.indexOf("like iphone")<0||DA.indexOf("ipad")>=0&&DA.indexOf("like ipad")<0||DA.indexOf("ipod")>=0&&DA.indexOf("like ipod")<0||pA(),Lr=()=>{var i,A;return pA()?!1:(A=(i=ot())==null?void 0:i.isTypeSupported('audio/mp4; codecs="opus"'))!=null?A:!1},Jr=()=>/^(?!.*chrome).*safari/i.test(DA);function Mr(){var i,A;if(/(iPhone|iPod|iPad)/i.test(DA))return(A=(i=DA==null?void 0:DA.match(/OS [\d_]+/i))==null?void 0:i[0])==null?void 0:A.substring(3).split("_").map(t=>parseInt(t))[0]}function Hr(){var i,A;if(/^((?!chrome|android).)*safari/i.test(DA))return(A=(i=DA.match(/version\/([\d.]+)/))==null?void 0:i[1])==null?void 0:A.split(".").map(t=>parseInt(t))[0]}const yQ=()=>{var t,e;const i=!!ot();let A=!1;return i&&(A=Lr()),{isMobile:mB,supportsMp4Opus:A,supportsMediaSource:i,supportsHls:yB(),supportsWebAssembly:mQ(),platform:{iosVersion:(t=Mr())!=null?t:Number.MAX_SAFE_INTEGER,safariVersion:(e=Hr())!=null?e:Number.MAX_SAFE_INTEGER,isIpadOS:pA(),isMacOS:Ti(),isIOS:dg()}}},fQ=(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 Pi{constructor(A){n(this,lA);n(this,Ot);n(this,Ee);a(this,Ot,A),a(this,Ee,new DataView(A.buffer,A.byteOffset,A.byteLength)),a(this,lA,0)}position(){return s(this,lA)}byteOffset(){return s(this,Ot).byteOffset+s(this,lA)}buffer(){return s(this,Ot)}remaining(){return s(this,Ot).length-s(this,lA)}readUint8(){const A=s(this,Ee).getUint8(s(this,lA));return a(this,lA,s(this,lA)+1),A}readUint24(){const A=s(this,Ee).getUint32(s(this,lA))>>8&16777215;return a(this,lA,s(this,lA)+3),A}readUint16(){const A=s(this,Ee).getUint16(s(this,lA));return a(this,lA,s(this,lA)+2),A}readUint32(){const A=s(this,Ee).getUint32(s(this,lA));return a(this,lA,s(this,lA)+4),A}readUint64(){const A=fQ(s(this,Ot),s(this,lA),s(this,lA)+7);return a(this,lA,s(this,lA)+8),A}readBytes(A){const t=s(this,Ot).subarray(s(this,lA),s(this,lA)+A);return a(this,lA,s(this,lA)+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))}}lA=new WeakMap,Ot=new WeakMap,Ee=new WeakMap;class qr{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}}}class xi{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 Wi=i=>i.reduce((A,t)=>A+t,0)/i.length,oe=i=>({last:i[i.length-1]||0,average:i.length===0?0:Wi(i),max:i.length===0?0:Math.max(...i),min:i.length===0?0:Math.min(...i)}),vr=i=>{let A=0,t=0,e=0,g=0,B=0;for(let E=0;E<i.length;E++){const{x:c,y:h}=i[E];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=Math.pow((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:E=>C*(i.length+E)+Q}};class Kr{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 L(A)}get total(){return this._total}get average(){return this.rates.isEmpty()?0:Wi(this.rates.items())}get minMaxAverage(){return oe(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 $A{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,un=FQ*1e3,GQ=(i,A,t)=>i%A===0?i/A:(i/A).toFixed(t),Yr=(i,A=1)=>i>=un?`${GQ(i,un,A)} Gbit/s`:i>=FQ?`${GQ(i,FQ,A)} Mbit/s`:i>=pQ?`${GQ(i,pQ,A)} Kbit/s`:`${i} bit/s`,Tr=({width:i,height:A})=>`${i}x${A}`,Pr=i=>i%1e3===0?`${i/1e3} kHz`:i>1e3?`${(i/1e3).toFixed(1)} kHz`:`${i} Hz`,wn=["off","error","warn","info","debug","trace"],xr={OFF:"off"},re=class re{constructor({context:A,logLevel:t,debug:e}){n(this,je,new Map);n(this,Ug,"");n(this,ze,!1);n(this,_i,"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)=>{});a(this,Ug,A),a(this,_i,t),a(this,ze,e||!1),this.setLevel(t),this.setDebug(s(this,ze))}setDebug(A){a(this,ze,A);for(const[t,e]of s(this,je))e.setDebug(A);A?(this.table=console.table.bind(console),this.count=console.count.bind(console)):(this.table=()=>{},this.count=()=>{})}setLevel(A){a(this,_i,A);for(const[e,g]of s(this,je))g.setLevel(A);const t=wn.indexOf(A);for(const[e,g]of wn.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,Ug)):this[g]=()=>{})}createContext(A){const t=s(this,je).get(A);if(!t){const e=new re({context:`${A}`,logLevel:s(this,_i),debug:s(this,ze)});return s(this,je).set(A,e),e}return t}static get(){return s(re,$i)||a(re,$i,new re({context:"Vindral",logLevel:"off"})),s(re,$i)}};je=new WeakMap,Ug=new WeakMap,ze=new WeakMap,_i=new WeakMap,$i=new WeakMap,n(re,$i);let kA=re;function xA(i){const A=kA.get().createContext(i.context);return function(e,g){const B=String(g.name);function C(...Q){i.enter&&A[i.enter](`Enter '${B}'`,S({},Q));try{const o=e.call(this,...Q);return o instanceof Promise?o.then(E=>{i.return&&A[i.return](`Return '${B}'`,E)}).catch(E=>{i.error&&A[i.error](`Error '${B}'`,E)}):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 Dn(){return typeof Symbol.dispose!="symbol"&&Object.defineProperty(Symbol,"dispose",{value:Symbol.for("dispose")}),Symbol.dispose}class Wr{constructor(A,t){n(this,Ng);I(this,"value");I(this,"unlocker");this.value=A,this.unlocker=t}unlocked(){var A;return(A=this.unlocker)==null?void 0:A.promise}[Dn()](){d(this,Ng,Qn).call(this)}[Symbol.dispose](){d(this,Ng,Qn).call(this)}}Ng=new WeakSet,Qn=function(){this.unlocker.resolve(this.value)};class Or{constructor(A){n(this,_e);n(this,$e,new G);a(this,_e,A),s(this,$e).resolve(A)}unsafeValue(){return s(this,_e)}isLocked(){return s(this,$e).pending}lock(){return r(this,null,function*(){const A=new G;A.promise.then(e=>{a(this,_e,e)}).catch(y);const t=s(this,$e).promise.then(()=>A);return a(this,$e,A),yield t,new Wr(s(this,_e),A)})}}_e=new WeakMap,$e=new WeakMap;class HA{constructor(A){n(this,tt);n(this,rt);a(this,tt,A),a(this,rt,new G)}isClosed(){var A;return!((A=s(this,rt))!=null&&A.pending)}current(){return s(this,tt)}value(){var A;return[s(this,tt),(A=s(this,rt))==null?void 0:A.promise]}update(A){var t;if(!((t=s(this,rt))!=null&&t.pending))throw new Error("ObservableValue is closed");a(this,tt,A instanceof Function?A(s(this,tt)):A),s(this,rt).resolve(s(this,tt)),a(this,rt,new G)}close(){var A;(A=s(this,rt))==null||A.resolve(s(this,tt)),a(this,rt,void 0)}waitFor(A){return r(this,null,function*(){if(A(s(this,tt)))return s(this,tt);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 Qe(this,null,function*(){for(;;){const[A,t]=this.value();if(yield A,!t)return;yield new aA(t)}})}}tt=new WeakMap,rt=new WeakMap;const Sn=(i,A)=>{const t=S({},i);return typeof t!="object"||A.forEach(e=>{delete t[e]}),t},Ke=(i,A=Date.now())=>{const t=i.length;if(t>0){const e=t-1,g=i[e];g.end||(g.end=A)}},Oi=(i,A=Date.now())=>{Ke(i),i.push({start:A})},Vi=i=>i.reduce((A,t)=>{var e;return A+(((e=t.end)!=null?e:Date.now())-t.start)},0),mn=(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),lC=class lC{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(lC,"create",()=>new lC);let RA=lC;function yn(i){try{return i()}catch(A){return A}}const fn=i=>{try{return JSON.parse(i)}catch(A){return}},pn=()=>{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("")},Ye=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))}),Vr=(i,A)=>r(null,null,function*(){throw yield i,new Error(A)});function Fn(i){return!(typeof i.edges[0]=="string"||i.channels[0]&&!("catalog"in i.channels[0]))}function Gn(i){return i.tracks.filter(A=>!!A.codec).filter(A=>RQ(A.codec||"")).map((A,t)=>{const e=A.codec,g=A.bitrate;k(e,"codec is required"),k(g!=null,"bitrate is required");const B=RQ(e);if(k(B,"codec is required"),D(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 D(B)==="text"?{track:A,id:t,bitRate:0,codec:B,kind:"subtitles",codecString:e,label:A.label,language:A.language}:(k(A.width,"width is required"),k(A.height,"width is required"),k(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)}function RQ(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"}const Te=i=>"width"in i&&typeof i.width=="number",Pe=i=>"sampleRate"in i&&typeof i.sampleRate=="number",xe=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"}},ne=()=>Number.MAX_SAFE_INTEGER,fB=()=>({width:Number.MAX_SAFE_INTEGER,height:Number.MAX_SAFE_INTEGER}),kn=i=>!(typeof i!="object"||i===null||!("type"in i)),Zr=i=>i?{Authorization:`Bearer ${i}`}:void 0,Xr=(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){}},jr=i=>typeof i=="object"&&i!==null&&"message"in i;class zr extends Error{constructor({status:t,url:e,body:g}){const B=fn(g),C=jr(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 _r=i=>typeof i.status=="number",$r=()=>{if(!(typeof window=="undefined"||typeof document=="undefined"))return Xr(window.location,document)},Ac=i=>{const A=$r();if(!A||i.searchParams.has("parentOrigin"))return i;const t=new URL(i.toString());return t.searchParams.append("parentOrigin",A),t},Rn=(i,A)=>r(null,null,function*(){const t=Ac(i),e=yield fetch(t.toString(),S({mode:"cors"},A));if(!e.ok)throw new zr({status:e.status,url:t,body:yield e.text()});return e}),UQ=(i,A)=>r(null,null,function*(){return yield(yield Rn(i,S({},A))).json()}),Un=(i,A)=>r(null,null,function*(){return Rn(i,S({method:"POST"},A))});function tc(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 Nn={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 bn{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(Nn.lbConnect(A),this.baseUrl),C=this.getAuthToken(g),Q=yield UQ(B,{headers:this.getHeaders(C)});if(tc(Q)){const o=Q.channels.map(E=>{const c=this.toChannel(E,g),h=Gn(E.catalog);return V(S(S({},E),c),{renditions:h})});return V(S({},Q),{channels:o})}else{const o=Q.channels.map(E=>{const c=this.toChannel(E,g);return S(S({},E),c)});return V(S({},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 UQ(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 UQ(e,{headers:this.getHeaders(g)}),C=Array.isArray(B)?B:B.channels;return this.toChannels(C,t,g)})}getHeaders(A){var e;return(e=Zr(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(Nn.thumbnails(t,e),this.baseUrl),Q=B.map(o=>new URL(`?channelId=${A.channelId}&width=${o.width}&height=${o.height}${ec(t,e)}`,C).toString());return{channelId:A.channelId,name:A.name,isLive:A.isLive,thumbnailUrls:Q}}}const ec=(i,A)=>A?i.channelGroupId?`&channelGroupId=${i.channelGroupId}&auth.token=${A}&auth.type=jwt`:`&auth.token=${A}&auth.type=jwt`:"";class Ln extends $A{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 ic={sizeBasedResolutionCapEnabled:!0,pictureInPictureEnabled:!0,abrEnabled:!0,burstEnabled:!1,mseEnabled:!0,mseOpusEnabled:!1,muted:!1,minBufferTime:1500,maxBufferTime:1500,logLevel:xr.OFF,maxSize:fB(),maxVideoBitRate:ne(),maxAudioBitRate:ne(),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},Jn="connection_failed",Mn="connection_failed_will_not_attempt_again",Hn="authentication_error",qn="authentication_expired",vn="channel_not_found",Kn="no_incoming_data_error",Yn="connection_inactivity",Ic="missing_init_segment",gc="no_track_context",sc="invalid_track_context_state",Tn="disconnected_by_edge",Bc="decoder_error",Cc="audio_player_error",Qc="media_source_error",oc="webgl_context_lost_error",nc="access_forbidden",ac="channel_switch_failed",Ec="drm_error";class W 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(S({},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 rc=(i,A)=>new W("MediaElement Error",{isFatal:i,code:"media_element_error",source:A},{mediaErrorCode:A.code}),Pn=(i,A)=>new W("Decoder Error",{isFatal:i,code:Bc,source:A,type:"internal"}),xn=(i,A)=>new W("Audio Player Error",{isFatal:i,code:Cc,source:A,type:"internal"}),cc=(i,A)=>new W(`No init segment for rendition id ${i} for channel ${A}`,{isFatal:!1,code:Ic,type:"internal"}),Wn=(i,A,t,e)=>new W("MediaSource Error",{isFatal:i,code:Qc,source:A,type:"internal"},{type:e,consecutiveErrorsCount:t}),pB=(i,A)=>new W(`No track context for ${i}${A?`, rendition id ${A}`:""}`,{isFatal:!1,code:gc,type:"internal"}),hc=(i,A)=>new W(`Track context is in an invalid state for ${i}${A?`, rendition id ${A}`:""}`,{isFatal:!1,code:sc,type:"internal"}),dc=()=>new W("Web Audio Context resume timeout",{isFatal:!1,code:"web_audio_context_resume_timeout"}),lg=i=>new W("Disconnected From Edge Server",{type:"external",source:i,isFatal:!1,code:Tn}),FB=i=>new W("Authentication Failed",{isFatal:!0,code:Hn,source:i}),lc=i=>new W("Authentication Expired",{isFatal:!0,code:qn,source:i}),uc=(i,A)=>new W("Connection closed due to inactivity",{isFatal:!1,code:Yn,source:A,type:i}),On=(i,A)=>new W("Channel not found",{isFatal:!1,code:vn,source:A,type:i}),wc=i=>new W("No Incoming Data",{isFatal:!1,code:Kn,source:i}),Dc=i=>new W("Connection attempt failed",{isFatal:!1,code:Jn,source:i}),Vn=()=>new W("Connection failed - no more reconnect attempts",{isFatal:!0,code:Mn}),Sc=i=>new W("WebGL Context Lost",{isFatal:!1,code:oc,source:i,type:"internal"}),Zn=i=>new W(i,{isFatal:!0,code:nc}),Xn=i=>new W(`Channel switch to '${i}' failed`,{isFatal:!1,code:ac}),jn=(i,A=!1,t)=>new W(i,{isFatal:A,code:Ec,source:t}),zn=(i,A)=>i&&typeof i=="object"&&A in i,_n=i=>!(typeof i!="object"||!zn(i,"channelId")||typeof i.channelId!="string"||!zn(i,"url")||typeof i.url!="string"||i.channelId.length===0||i.url.length===0),mc=i=>{if(!_n(i))throw new W("Invalid options",{isFatal:!0,code:"invalid_options"});const A=S({},i);return Object.keys(A).forEach(t=>{const e=A;typeof e[t]=="undefined"&&delete e[t]}),A},$n={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"'}]},yc={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}},Aa=(i,A)=>r(null,null,function*(){return navigator.requestMediaKeySystemAccess(i,[A]).catch(()=>{})}),ta=(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(S({},c),{robustness:Q,contentType:B?`${g==="audioCapabilities"?"audio/mp4":"video/mp4"}; codecs="${B}"`:c.contentType}));if(!(yield Aa(i,{initDataTypes:A,[g]:o})))break;C=o}return C}),fc=(i,A,t,e)=>r(null,null,function*(){const{keySystem:g,supportedConfig:B}=yc[i],{initDataTypes:C,videoCapabilities:Q,audioCapabilities:o}=B,E=e==null?void 0:e[i],c=(E==null?void 0:E.videoRobustness)||$n[i],h=(E==null?void 0:E.audioRobustness)||$n[i],[l,m]=yield Promise.all([ta(g,C,Q,c,"videoCapabilities",A),ta(g,C,o,h,"audioCapabilities",t)]);return!l&&!m?void 0:yield Aa(g,{initDataTypes:C,videoCapabilities:l,audioCapabilities:m})}),pc=(i,A,t,e)=>r(null,null,function*(){let g;for(const B of i)if(g=yield fc(B,A,t,e),g)return{keySystem:B,mediaKeySystemAccess:g}});class GB{constructor(A,t,e,g){I(this,"keySystem");I(this,"licenseServerUrl");I(this,"certificate");I(this,"headers",{});I(this,"queryParams",{});n(this,Ai);n(this,ti);a(this,Ai,t),this.keySystem=A,this.licenseServerUrl=e,this.certificate=g}get statistics(){return{keySystem:s(this,Ai).keySystem,licenseServerUrl:this.licenseServerUrl,mediaKeySystemConfiguration:s(this,Ai).getConfiguration()}}getMediaKeys(){return r(this,null,function*(){return s(this,ti)?s(this,ti):(a(this,ti,yield s(this,Ai).createMediaKeys()),s(this,ti))})}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:S({"Content-Type":"application/octet-stream"},this.headers)});if(!e.ok)throw new Error(`Failed to fetch license: ${e.statusText}`);return yield e.arrayBuffer()})}}Ai=new WeakMap,ti=new WeakMap;function ea(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 Fc(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 Gc(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 kc extends GB{constructor(t,e){super("clearkey",t,"");n(this,bg);a(this,bg,e)}handleLicenseRequest(t){const e=new Uint8Array(t),g=String.fromCharCode(...e),B=JSON.parse(g),C=[];for(let E=0;E<B.kids.length;E++){const c=B.kids[E];if(c){const h=ea(c).toLowerCase(),l=s(this,bg)[h];l&&C.push({kty:"oct",alg:"A128KW",kid:c,k:Fc(l)})}}const Q=JSON.stringify({keys:C,type:B.type});return new TextEncoder().encode(Q)}}bg=new WeakMap;class Rc extends GB{constructor(A,t,e){super("fairplay",A,t,e)}}const Uc=i=>{var Q,o,E,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 f=(Q=h[m])==null?void 0:Q.childNodes[0],U=(o=l[m])==null?void 0:o.childNodes[0];f!=null&&f.nodeValue&&U&&U.nodeValue&&(g[f.nodeValue]=U.nodeValue)}}const B=t.getElementsByTagName("Challenge")[0];let C;return B&&((E=B.childNodes[0])!=null&&E.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 Nc extends GB{constructor(A,t){super("playready",A,t)}requestLicense(A){return r(this,null,function*(){k(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=Uc(A),g=yield fetch(t,{method:"POST",headers:S(S({},e.headers),this.headers),body:e.message});if(!g.ok)throw new Error(`Failed to fetch license: ${g.statusText}`);return yield g.arrayBuffer()})}}class bc extends GB{constructor(A,t){super("widevine",A,t)}}const Lc=5e3;class ia{constructor(A,t,e={}){n(this,uA);n(this,tA);n(this,ei);n(this,Vt);n(this,ct,new G);n(this,Gt);n(this,FA);n(this,ce,new Map);n(this,he);n(this,uC,yQ());n(this,AI);n(this,Lg,A=>{if(s(this,tA).info("Received DRM data",{drmData:A}),window.clearTimeout(s(this,AI)),s(this,FA)){const t=d(this,uA,XE).call(this,A)[s(this,FA).keySystem];t&&(s(this,FA).licenseServerUrl=t)}s(this,ct).resolve(A)});n(this,Jg,A=>{s(this,tA).info("Encrypted event received",{event:A}),d(this,uA,PE).call(this,A)});n(this,wC,A=>{var B,C;s(this,tA).debug("Session message received",{event:A});const t=A.target,e=A.message;if(!s(this,ce).get(t)){s(this,tA).error("No active session found for event",{event:A});return}s(this,tA).debug("Requesting license for session",{sessionId:t.sessionId,licenseServerUrl:(B=s(this,FA))==null?void 0:B.licenseServerUrl}),(C=s(this,FA))==null||C.requestLicense(e).then(Q=>{s(this,tA).debug("License received for session",{sessionId:t.sessionId}),t.update(Q).catch(o=>{d(this,uA,lB).call(this,{message:"Failed to update session with license",isFatal:!1,error:o})})}).catch(Q=>{d(this,uA,lB).call(this,{message:"Failed to request license",isFatal:!1,error:Q})})});n(this,DC,A=>{const t=A.target;s(this,tA).debug("Key status changed for session",{sessionId:t.sessionId}),t.keyStatuses.forEach((e,g)=>{const B=ea(window.btoa(String.fromCharCode(...new Uint8Array(g))));s(this,tA).debug("Key status",{base64kid:B,status:e})})});n(this,SC,A=>r(this,null,function*(){const t=d(this,uA,ZE).call(this,A);s(this,tA).debug("Prioritized key system list",{keySystemList:t});const e=yield pc(t,A.videoCodec,A.audioCodec,{widevine:s(this,Gt).widevine,playready:s(this,Gt).playready});if(!e)return s(this,tA).warn("No supported key system found"),null;s(this,tA).debug("Supported key system found",e.mediaKeySystemAccess.getConfiguration());const{keySystem:g,mediaKeySystemAccess:B}=e;let C=null;return g==="clearkey"?(k(A.clearkeys,"No clearkeys found"),C=new kc(B,A.clearkeys)):g==="playready"?(k(A.playreadyLicenseUrl,"No playreadyLicenseUrl found"),C=new Nc(B,A.playreadyLicenseUrl)):g==="widevine"?(k(A.widevineLicenseUrl,"No widevineLicenseUrl found"),C=new bc(B,A.widevineLicenseUrl)):g==="fairplay"&&(k(A.fairplayLicenseUrl,"No fairplayLicenseUrl found"),k(A.fairplayCertificate,"No fairplayCertificate found"),C=new Rc(B,A.fairplayLicenseUrl,A.fairplayCertificate)),C&&(C.headers=s(this,Gt).headers||{},C.queryParams=s(this,Gt).queryParams||{}),C}));a(this,ei,A),a(this,tA,t),a(this,Gt,e),s(this,ei).on("received drm data",s(this,Lg))}static isSupported(){return!!navigator.requestMediaKeySystemAccess}attach(A){a(this,Vt,A),s(this,tA).info("Media element attached"),s(this,Vt).addEventListener("encrypted",s(this,Jg))}getStatistics(){var A,t;return!s(this,ct).resolved&&!((A=s(this,FA))!=null&&A.statistics)?null:S(S({},s(this,ct).resolved),(t=s(this,FA))==null?void 0:t.statistics)}unload(){var A;s(this,tA).info("Unloading EncryptedMediaExtensions"),s(this,ei).off("received drm data",s(this,Lg)),(A=s(this,Vt))==null||A.removeEventListener("encrypted",s(this,Jg)),s(this,ce).forEach((t,e)=>{e.close()}),s(this,ce).clear(),a(this,he,void 0),a(this,FA,void 0)}set headers(A){s(this,Gt).headers=A,s(this,FA)&&(s(this,FA).headers=A)}set queryParams(A){s(this,Gt).queryParams=A,s(this,FA)&&(s(this,FA).queryParams=A)}onChannelSwitch(){if(!s(this,ct).resolved){s(this,tA).debug("DRM is not used, skipping channel switch handling");return}Jr()&&s(this,uC).platform.safariVersion<18&&d(this,uA,lB).call(this,{message:"DRM channel switch not supported on Safari < 18",isFatal:!0}),window.clearTimeout(s(this,AI));const A=s(this,ct).resolved;a(this,ct,new G),a(this,AI,window.setTimeout(()=>{s(this,ct).resolve(A)},Lc))}}tA=new WeakMap,ei=new WeakMap,Vt=new WeakMap,ct=new WeakMap,Gt=new WeakMap,FA=new WeakMap,ce=new WeakMap,he=new WeakMap,uC=new WeakMap,AI=new WeakMap,Lg=new WeakMap,Jg=new WeakMap,uA=new WeakSet,PE=function(A){return r(this,null,function*(){try{yield d(this,uA,xE).call(this),s(this,tA).debug("Media keys initialization completed"),yield d(this,uA,WE).call(this,A.initData,A.initDataType)}catch(t){d(this,uA,lB).call(this,{message:"Failed to handle encrypted event",isFatal:!0,error:t})}})},xE=function(){return r(this,null,function*(){var t;s(this,tA).debug("Initializing media keys");const A=yield s(this,ct).promise;if((t=s(this,Vt))!=null&&t.mediaKeys){s(this,tA).debug("Media keys already set on media element");return}if(s(this,he)){s(this,tA).debug("Media keys initialization already in progress, waiting for completion"),yield s(this,he);return}a(this,he,r(this,null,function*(){const e=yield s(this,SC).call(this,A);s(this,tA).debug("CDM obtained",{cdm:e}),k(s(this,Vt),"No media element found"),k(e,"No CDM found");const g=yield e.getMediaKeys();e.certificate&&(yield d(this,uA,VE).call(this,g,e.certificate)),s(this,tA).debug("Setting media keys on media element"),yield s(this,Vt).setMediaKeys(g),a(this,FA,e)})),yield s(this,he)})},WE=function(A,t){return r(this,null,function*(){k(s(this,FA),"No CDM manager found");const e=yield s(this,FA).getMediaKeys();if(!A||!d(this,uA,OE).call(this,A)){s(this,tA).debug("Duplicate initData, no need to create new session",{initData:A});return}const g=e.createSession();s(this,tA).debug("Creating new session",{session:g}),g.addEventListener("keystatuseschange",s(this,DC)),g.closed.then(B=>{s(this,tA).info("Session is closed",{reason:B})}),g.addEventListener("message",s(this,wC)),s(this,ce).set(g,A),s(this,tA).debug("Generating request for session",{session:g,initDataType:t,initData:A}),yield g.generateRequest(t,A)})},OE=function(A){for(const[t,e]of s(this,ce))if(Gc(A,e))return!1;return!0},wC=new WeakMap,DC=new WeakMap,VE=function(A,t){return r(this,null,function*(){try{s(this,tA).debug("Setting server certificate",{certificate:t}),(yield A.setServerCertificate(t))||s(this,tA).warn("Server certificates are not supported by the CDM.")}catch(e){s(this,tA).error("Failed to set server certificate",{error:e})}})},lB=function(A){const{message:t,isFatal:e,error:g}=A;s(this,tA).error(t,{error:g}),s(this,ei).emit("error",jn(t,e,g))},SC=new WeakMap,ZE=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},XE=function(A){return{fairplay:A.fairplayLicenseUrl,playready:A.playreadyLicenseUrl,widevine:A.widevineLicenseUrl,clearkey:void 0}};const Jc=7,Mc=8,Hc=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},qc=i=>Hc(new DataView(i,0))!==0,Ia=(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}}},vc=i=>i&31,Kc=(i,A)=>{const t=new DataView(i,0);let e=Ia(t);for(;e;){const{position:g,nalPrefixSize:B}=e,C=Ia(t,g+4),Q=C?C.position-g-B:void 0;if(!A(new DataView(i,g+B,Q),B))return;e=C}},ga=i=>{const A=[],t=[];if(!qc(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 Kc(i,e=>{const g=e.byteOffset+e.byteLength;switch(vc(e.getUint8(0))){case Mc:t.push(e.buffer.slice(e.byteOffset,g));break;case Jc:A.push(e.buffer.slice(e.byteOffset,g));break}return!0}),{sequenceParameterSets:A,pictureParameterSets:t}},Yc=i=>{var f;const A=new DataView(i),t=A.getUint8(1),e=A.getUint8(2),g=A.getUint8(3),B=new _(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 b=0;b<(C!=3?8:12);b++)if(B.readBit()){const N=b<6?16:64;let v=0,T=8,P=8;for(let X=0;X<N;X++)P!=0&&(v=B.readSignedExpGolomb(),P=(T+v+256)%256),T=P==0?T:P}}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(),E=B.readUnsignedExpGolomb(),c=B.readBit();c===0&&B.readBit(),B.readBit();let h=o+1,l=E+1;if(l*=2-c,l*=16,h*=16,B.readBit()){const U=C==1?1:0,Y=1<<(C==1||C==2?1:0),N=2-c<<U,v=B.readUnsignedExpGolomb()*Y,T=B.readUnsignedExpGolomb()*Y,P=B.readUnsignedExpGolomb()*N,X=B.readUnsignedExpGolomb()*N;h-=v+T,l-=P+X}let m={numerator:1,denumerator:1};return B.readBit()&&B.readBit()&&(m=(f=Tc[B.readBits(8)])!=null?f:{numerator:0,denumerator:0}),{width:h,height:l,pixelAspectRatio:m,profileIdc:t,constraintFlags:e,levelIdc:g}},Tc=[{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}],Pc=184549376;function xc(i){const A=new Pi(i),t=Wc(A);(t.flags&Pc)!==0&&Oc(A);const e=Vc(A);if(String.fromCharCode(...e.frameId)==="TXXX"){const B=new Pi(A.readBytes(e.size));return{header:t,txx:Zc(B)}}}function Wc(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 Oc(i){const A=i.readUint32();return i.readBytes(A-4),{}}function Vc(i){const A=i.readBytes(4),t=i.readUint32(),e=i.readUint16();return{frameId:A,size:t,flags:e}}function Zc(i){const A=i.readUint8(),t=i.readUtf8String(),e=i.readUtf8String();return{encoding:A,description:t,value:e}}function sa(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 Xc(i,A){const t=sa(A),e=new Pi(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 Pt(i){const A=i.readUint8(),t=i.readUint24();return{version:A,flags:t}}const tI=class tI{constructor({timescale:A,presentationTime:t,presentationTimeDelta:e,schemeIdUri:g,value:B,eventDuration:C,id:Q,data:o}){I(this,"type",tI.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}=Pt(A);switch(t){case 1:{const e=A.readUint32(),g=A.readUint64(),B=A.readUint32(),C=A.readUint32(),Q=A.readUtf8String(),o=A.readUtf8String(),E=A.remaining(),c=A.readBytes(E);return new tI({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(),E=A.remaining(),c=A.readBytes(E);return new tI({timescale:B,presentationTimeDelta:C,schemeIdUri:e,value:g,eventDuration:Q,id:o,data:c})}default:throw new Error(`unsupported version ${t}`)}}};I(tI,"type","emsg");let kB=tI;const Mg=class Mg{constructor(A){I(this,"type",Mg.type);I(this,"data");this.data=A}static decodeData(A){const t=A.readRemaining();return new Mg(t)}};I(Mg,"type","mdat");let RB=Mg;const Hg=class Hg{constructor(A,t,e){I(this,"type",Hg.type);I(this,"extra");I(this,"byteOffset");I(this,"baseMediaDecodeTime");this.extra=A,this.byteOffset=t,this.baseMediaDecodeTime=e}static decodeData(A){const t=Pt(A),e=A.byteOffset();let g=0;return t.version===1?g=A.readUint64():g=A.readUint32(),new Hg(t,e,g)}};I(Hg,"type","tfdt");let UB=Hg;const rA=class rA{constructor(A,t,e){I(this,"type",rA.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=rA.FLAG_SAMPLE_FLAG_IS_NON_SYNC|rA.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}=Pt(A),e=A.readUint32();let g,B;t&rA.TRUN_DATA_OFFSET&&(g=A.readUint32()),t&rA.TRUN_FIRST_SAMPLE_FLAGS&&(B=A.readUint32());const C=new rA(e,g,B);for(let Q=0;Q<e;Q++)t&rA.SAMPLE_DURATION&&C.sampleDurations.push(A.readUint32()),t&rA.SAMPLE_SIZE&&C.sampleSizes.push(A.readUint32()),t&rA.SAMPLE_FLAGS&&C.sampleFlags.push(A.readUint32()),t&rA.SAMPLE_CTS&&C.sampleCts.push(A.readUint32());return C}};I(rA,"TRUN_DATA_OFFSET",1),I(rA,"TRUN_FIRST_SAMPLE_FLAGS",4),I(rA,"SAMPLE_DURATION",256),I(rA,"SAMPLE_SIZE",512),I(rA,"SAMPLE_FLAGS",1024),I(rA,"SAMPLE_CTS",2048),I(rA,"FLAG_SAMPLE_FLAG_IS_NON_SYNC",65536),I(rA,"FLAG_SAMPLE_DEPENDS_NO",33554432),I(rA,"FLAG_SAMPLE_DEPENDS_YES",16777216),I(rA,"type","trun");let ug=rA;const jc=1,zc=2,_c=8,$c=16,Ah=32,qg=class qg{constructor(A,t,e,g){I(this,"type",qg.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=Pt(A);let e,g,B;return A.readUint32(),(t.flags&jc)>0&&A.readUint64(),(t.flags&zc)>0&&A.readUint32(),(t.flags&_c)>0&&(e=A.readUint32()),(t.flags&$c)>0&&(g=A.readUint32()),(t.flags&Ah)>0&&(B=A.readUint32()),new qg(t,e,g,B)}};I(qg,"type","tfhd");let NB=qg;const vg=class vg{constructor(A,t,e){I(this,"type",vg.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=nt(A);B instanceof NB&&(t=B),B instanceof UB&&(e=B),B instanceof ug&&(g=B)}return new vg(t,e,g)}};I(vg,"type","traf");let bB=vg;const Kg=class Kg{constructor(A){I(this,"type",Kg.type);I(this,"traf");this.traf=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=nt(A);e instanceof bB&&(t=e)}if(!t)throw new Error("No traf found");return new Kg(t)}};I(Kg,"type","moof");let LB=Kg;const Yg=class Yg{constructor(){I(this,"type",Yg.type)}static decodeData(A){return new Yg}};I(Yg,"type","mvhd");let JB=Yg;const Tg=class Tg{constructor(A){I(this,"type",Tg.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){Pt(A),A.readUint32();const t=String.fromCharCode(...A.readBytes(4));return new Tg(t)}};I(Tg,"type","hdlr");let MB=Tg;const eI=class eI{constructor(A,t,e,g){I(this,"type",eI.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}=Pt(A);if(t===1){const Q=A.readUint64(),o=A.readUint64(),E=A.readUint32(),c=A.readUint64();return new eI(Q,o,E,c)}const e=A.readUint32(),g=A.readUint32(),B=A.readUint32(),C=A.readUint32();return new eI(e,g,B,C)}};I(eI,"type","mdhd");let HB=eI;const Pg=class Pg{constructor(A,t,e,g){I(this,"type",Pg.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){Pt(A);const t=A.readUint32();let e,g,B,C;for(let Q=0;Q<t;Q++)for(;A.remaining()>0;){const o=nt(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 Pg(g,C,B,e)}};I(Pg,"type","stsd");let qB=Pg;const xg=class xg{constructor(A){I(this,"type",xg.type);I(this,"stsd");this.stsd=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=nt(A);e instanceof qB&&(t=e)}if(!t)throw new Error("No stsd found");return new xg(t)}};I(xg,"type","stbl");let vB=xg;const Wg=class Wg{constructor(A){I(this,"type",Wg.type);I(this,"stbl");this.stbl=A}static decodeData(A){let t;for(;A.remaining()>0;){const e=nt(A);e instanceof vB&&(t=e)}if(!t)throw new Error("No stbl found");return new Wg(t)}};I(Wg,"type","minf");let KB=Wg;const Og=class Og{constructor(A,t,e){I(this,"type",Og.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=nt(A);B instanceof MB&&(t=B),B instanceof KB&&(e=B),B instanceof HB&&(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 Og(t,e,g)}};I(Og,"type","mdia");let YB=Og;const Vg=class Vg{constructor(A,t,e,g,B,C,Q,o){I(this,"type",Vg.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=Pt(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 E=A.readUint16();A.readUint16();const c=A.readUint16();return A.readUint16(),new Vg(e,g,B,C,Q,o,E,c)}};I(Vg,"type","tkhd");let TB=Vg;const Zg=class Zg{constructor(A,t){I(this,"type",Zg.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=nt(A);g instanceof TB&&(t=g),g instanceof YB&&(e=g)}if(!t)throw new Error("No tkhd found");if(!e)throw new Error("No mdia found");return new Zg(t,e)}};I(Zg,"type","trak");let PB=Zg;const Xg=class Xg{constructor(A,t){I(this,"type",Xg.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=nt(A);g instanceof PB&&e.push(g),g instanceof JB&&(t=g)}if(!t)throw new Error("No mvhd found");return new Xg(t,e)}};I(Xg,"type","moov");let xB=Xg;const jg=class jg{constructor(A,t,e,g,B,C,Q,o){I(this,"type",jg.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,E=[];for(let l=0;l<o;l++){const m=A.readBytes(A.readUint16());E.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 jg(e,g,B,C,Q,E,h,t)}};I(jg,"type","avcC");let bQ=jg;const zg=class zg{constructor(A,t,e,g,B){I(this,"type",zg.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=nt(A);switch(Q.type){case"avcC":C=Q;break}}if(!C)throw new Error("no avcC");return new zg(C,t,e,g,B)}};I(zg,"type","avc1");let LQ=zg;const _g=class _g{constructor(){I(this,"type",_g.type)}static decodeData(A){return new _g}};I(_g,"type","dOps");let JQ=_g;const $g=class $g{constructor(A,t,e){I(this,"type",$g.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=Xc(JQ,A);return new $g(B,e,g)}};I($g,"type","Opus");let MQ=$g;const iI=class iI{constructor(A,t){I(this,"type",iI.type);I(this,"ntpTimestamp");I(this,"mediaTime");this.ntpTimestamp=A,this.mediaTime=t}date(){const[A,t]=this.ntpTimestamp,e=A*1e3+t/sn(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}=Pt(A);A.readUint32();const e=A.readUint32(),g=A.readUint32();if(t===1){const C=A.readUint64();return new iI([e,g],C)}const B=A.readUint32();return new iI([e,g],B)}};I(iI,"type","prft");let WB=iI;class th{constructor(A,t){n(this,As);n(this,ts);a(this,As,A),a(this,ts,t.readBytes(A.size))}data(){return s(this,ts)}get type(){return s(this,As).type}}As=new WeakMap,ts=new WeakMap;const eh={moov:xB,trak:PB,tkhd:TB,mvhd:JB,moof:LB,traf:bB,tfhd:NB,tfdt:UB,trun:ug,mdat:RB,mdia:YB,hdlr:MB,minf:KB,stbl:vB,mdhd:HB,stsd:qB,prft:WB,avc1:LQ,avcC:bQ,Opus:MQ,emsg:kB};function nt(i){const A=sa(i),t=eh[A.type],e=new Pi(i.readBytes(A.size));if(!t){const B=new th(A,e);return e.readRemaining(),B}const g=t.decodeData(e);return e.readRemaining(),g}function ih(i){if(i.byteLength<8)throw new Error("Buffer too small");const A=new Pi(i),t=new Map;for(;A.remaining()>0;){const B=nt(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 xB))throw new Error("moov atom not found");return{ftyp:e,moov:g}}function Ih(i){if(i.byteLength<8)throw new Error("Buffer too small");const A=new Pi(i),t=new Map,e=[];for(;A.remaining()>0;){const Q=nt(A);Q instanceof kB&&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 LB))throw new Error("moof atom not found");if(!B||!(B instanceof RB))throw new Error("mdat atom not found");if(C&&!(C instanceof WB))throw new Error("invalid prft found");return{moof:g,mdat:B,prft:C,emsgs:e}}class gh{constructor(A){n(this,es);n(this,is);a(this,es,A),a(this,is,ih(A))}rawBytes(){return s(this,es)}init(){return s(this,is)}}es=new WeakMap,is=new WeakMap;const Wo=class Wo{constructor(A,t){n(this,vA);n(this,WA);n(this,gA);a(this,vA,t),a(this,WA,A),a(this,gA,Ih(t))}clone(){return new Wo(s(this,WA),new Uint8Array(s(this,vA).buffer.slice(s(this,vA).byteOffset,s(this,vA).byteOffset+s(this,vA).byteLength)))}updateBaseMediaDecodeTime(A){const t=new DataView(s(this,vA).buffer,s(this,vA).byteOffset,s(this,vA).byteLength);if(s(this,gA).moof.traf.tfdt)if(s(this,gA).moof.traf.tfdt.baseMediaDecodeTime=A,s(this,gA).moof.traf.tfdt.extra.version===1){const e=Math.floor(A/4294967296),g=(A&4294967295)>>>0;t.setUint32(s(this,gA).moof.traf.tfdt.byteOffset-s(this,vA).byteOffset,e),t.setUint32(s(this,gA).moof.traf.tfdt.byteOffset-s(this,vA).byteOffset+4,g)}else t.setUint32(s(this,gA).moof.traf.tfdt.byteOffset-s(this,vA).byteOffset,A)}producerReferenceTime(){if(s(this,gA).prft)return s(this,gA).prft.date()}duration(){const A=s(this,gA).moof.traf.trun,t=s(this,gA).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,gA).moof.traf.tfdt)==null?void 0:t.baseMediaDecodeTime;if(!A)throw new Error("no baseMediaDecodeTime");return A}startsWithKeyframe(){var e;const A=s(this,gA).moof.traf.trun,t=(A==null?void 0:A.firstSampleFlags)||(A==null?void 0:A.sampleFlags[0])||((e=s(this,gA).moof.traf.tfhd)==null?void 0:e.defaultSampleFlags);return t?(t&ug.FLAG_SAMPLE_DEPENDS_NO)!==0:!1}compositionTimeOffset(A){var t;return(t=s(this,gA).moof.traf.trun)==null?void 0:t.sampleCts[A]}timescale(){const A=s(this,WA).init().moov.traks[0];if(!A)throw new Error("no tracks");return A.mdia.mdhd.timescale}mediaType(){var t;const A=(t=s(this,WA).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,WA)}fragment(){return s(this,gA)}samplesCount(){var A;return((A=s(this,gA).moof.traf.trun)==null?void 0:A.samplesCount)||0}sample(A){var m,f,U,b,Y,N,v,T,P,X,yA,BA,fA,Bt,w;const t=(m=s(this,WA).init().moov.traks[0])==null?void 0:m.mdia.minf.stbl.stsd.codec,e=((f=s(this,gA).moof.traf.trun)==null?void 0:f.samplesCount)||0,g=(U=s(this,gA).moof.traf.tfdt)==null?void 0:U.baseMediaDecodeTime;if(A>=e||typeof g=="undefined"||!t)return;const B=((b=s(this,gA).moof.traf.trun)==null?void 0:b.sampleDurations[A])||0,C=((Y=s(this,gA).moof.traf.trun)==null?void 0:Y.sampleDurations.slice(0,A).reduce((R,x)=>R+x,0))||0,Q=g+C,o=((N=s(this,WA).init().moov.traks[0])==null?void 0:N.mdia.mdhd.timescale)||1e3,E=((v=s(this,gA).moof.traf.trun)==null?void 0:v.sampleSizes[A])||s(this,gA).mdat.data.byteLength,c=((T=s(this,gA).moof.traf.trun)==null?void 0:T.sampleSizes.slice(0,A).reduce((R,x)=>R+x,0))||0,h=s(this,gA).mdat.data.subarray(c,c+E),l=((P=s(this,gA).moof.traf.trun)==null?void 0:P.is_sync_sample(A))||!1;if(this.mediaType()==="video"){const R=((X=s(this,WA).init().moov.traks[0])==null?void 0:X.tkhd.width)||0,x=((yA=s(this,WA).init().moov.traks[0])==null?void 0:yA.tkhd.height)||0;return{type:"video",codec:t,width:R,height:x,duration:B,isSync:l,timescale:o,timestamp:Q,data:h}}return{type:"audio",codec:t,channels:((fA=(BA=s(this,WA).init().moov.traks[0])==null?void 0:BA.mdia.minf.stbl.stsd.opus)==null?void 0:fA.channelCount)||0,sampleRate:((w=(Bt=s(this,WA).init().moov.traks[0])==null?void 0:Bt.mdia.minf.stbl.stsd.opus)==null?void 0:w.sampleRate)||0,duration:B,isSync:l,timestamp:Q,data:h,timescale:o}}rawBytes(){return s(this,vA)}};vA=new WeakMap,WA=new WeakMap,gA=new WeakMap;let HQ=Wo;class Ba{constructor(A){n(this,II);a(this,II,new gh(A))}header(){return s(this,II)}createFragment(A){return new HQ(s(this,II),A)}}II=new WeakMap;function H(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 iA={ftyp:H("ftyp"),mvhd:H("mvhd"),moov:H("moov"),trak:H("trak"),tkhd:H("tkhd"),mdia:H("mdia"),mdhd:H("mdhd"),hdlr:H("hdlr"),minf:H("minf"),vmhd:H("vmhd"),smhd:H("smhd"),dinf:H("dinf"),dref:H("dref"),stbl:H("stbl"),stsd:H("stsd"),avc1:H("avc1"),av01:H("av01"),av1C:H("av1C"),avcC:H("avcC"),esds:H("esds"),colr:H("colr"),nclx:H("nclx"),mvex:H("mvex"),trex:H("trex"),udta:H("udta"),meta:H("meta"),ilst:H("ilst"),moof:H("moof"),mfhd:H("mfhd"),traf:H("traf"),tfhd:H("tfhd"),tfdt:H("tfdt"),trun:H("trun"),mdat:H("mdat"),mp4a:H("mp4a"),Opus:H("Opus"),prft:H("prft"),dOps:H("dOps"),emsg:H("emsg")},sh=1e3,wg=H("iso6"),Ca=new Uint8Array([0,0,2,0]),Bh=[wg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([97,118,99,49]),new Uint8Array([109,112,52,49])],Ch=[wg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([97,118,48,49]),new Uint8Array([109,112,52,49])],Qh=[wg,new Uint8Array([105,115,111,109]),new Uint8Array([105,115,111,50]),new Uint8Array([109,112,52,49])];class Qa{constructor(){I(this,"writer",new qr);I(this,"moofOffset",0)}}const dA=(i,A,t)=>{i.writer.writeUint32(t+8),i.writer.writeBytes(A)},wA=(i,A,t,e,g)=>{dA(i,A,t+4),i.writer.writeUint8(e),i.writer.writeUint24(g)},qQ=(i,A)=>{dA(i,iA.ftyp,wg.byteLength+Ca.byteLength+A.reduce((t,e)=>t+e.byteLength,0)),i.writer.writeBytes(wg),i.writer.writeBytes(Ca),A.forEach(t=>i.writer.writeBytes(t))},oh=Math.pow(2,32),nh=2208988800,ah=(i,A,t,e)=>{wA(i,iA.prft,20,1,0);const B=t/1e3,C=Math.floor(B),o=(B-C)*1e3*1e3*oh/1e6;i.writer.writeUint32(A),i.writer.writeUint32(C+nh),i.writer.writeUint32(o),i.writer.writeUint64(e)},Eh=(i,A,t)=>{wA(i,iA.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)},oa=i=>"sequenceParameterSets"in i,vQ=i=>"sequenceHeader"in i,We=i=>i.type=="video",Dg=i=>i.type=="audio",rh=(i,A,t)=>{const e=i.writer.position();wA(i,iA.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(Dg(A)?1:0),i.writer.writeUint16(Dg(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])),We(A)?(i.writer.writeUint32(A.width*65536),i.writer.writeUint32(A.height*65536)):Dg(A)&&(i.writer.writeUint32(0),i.writer.writeUint32(0)),i.writer.writeUint32At(e,i.writer.position()-e)},ch=(i,A)=>{wA(i,iA.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)},hh=(i,A)=>{const t=i.writer.position();wA(i,iA.hdlr,0,0,0),i.writer.writeUint32(0),i.writer.writeBytes(H(We(A)?"vide":"soun")),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeUint32(0),i.writer.writeBytes(H(We(A)?"VideoHandler\0":"SoundHandler\0")),i.writer.writeUint32At(t,i.writer.position()-t)},dh=i=>{const A=i.writer.position();dA(i,iA.dinf,0),wA(i,iA.dref,16,0,0),i.writer.writeUint32(1),wA(i,H("url "),0,0,1),i.writer.writeUint32At(A,i.writer.position()-A)},lh=(i,A)=>{const t=i.writer.position();dA(i,iA.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)},uh=(i,A)=>{var Q,o;const t=i.writer.position();dA(i,iA.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)},wh=(i,A)=>{const t=i.writer.position(),e=vQ(A)?iA.av01:iA.avc1;dA(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),oa(A)?lh(i,A):vQ(A)&&(uh(i,A),A.parsedSequenceHeader.colorConfig&&(dA(i,H("colr"),11),i.writer.writeBytes(iA.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&&(dA(i,H("pasp"),8),i.writer.writeUint32(A.pixelAspectRatio.numerator),i.writer.writeUint32(A.pixelAspectRatio.denumerator)),A.bitrate&&(dA(i,H("btrt"),12),i.writer.writeUint32(0),i.writer.writeUint32(A.bitrate),i.writer.writeUint32(A.bitrate)),i.writer.writeUint32At(t,i.writer.position()-t)},OB=(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();wA(i,iA.esds,0,0,0),OB(i,3,21+t+5+1),i.writer.writeUint16(A.trackId),i.writer.writeUint8(0),OB(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&&(OB(i,5,A.decoderConfig.byteLength),i.writer.writeBytes(A.decoderConfig)),OB(i,6,1),i.writer.writeUint8(2),i.writer.writeUint32At(e,i.writer.position()-e)},Sh=i=>{switch(i){case"aac":case"mp3":return"mp4a";case"opus":return"Opus"}},mh=(i,A)=>{const t=i.writer.position();dA(i,H("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)},yh=(i,A)=>{const t=i.writer.position();switch(dA(i,H(Sh(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":mh(i,A);break}A.bitrate&&(dA(i,H("btrt"),12),i.writer.writeUint32(0),i.writer.writeUint32(A.bitrate),i.writer.writeUint32(A.bitrate)),i.writer.writeUint32At(t,i.writer.position()-t)},fh=(i,A)=>{const t=i.writer.position();dA(i,iA.stbl,0);const e=i.writer.position();wA(i,iA.stsd,0,0,0),i.writer.writeUint32(1),We(A)?wh(i,A):Dg(A)&&yh(i,A),i.writer.writeUint32At(e,i.writer.position()-e),wA(i,H("stts"),4,0,0),i.writer.writeUint32(0),wA(i,H("stsc"),4,0,0),i.writer.writeUint32(0),wA(i,H("stsz"),8,0,0),i.writer.writeUint32(0),i.writer.writeUint32(0),wA(i,H("stco"),4,0,0),i.writer.writeUint32(0),i.writer.writeUint32At(t,i.writer.position()-t)},ph=(i,A)=>{const t=i.writer.position();dA(i,iA.minf,0),We(A)?(wA(i,iA.vmhd,8,0,1),i.writer.writeUint32(0),i.writer.writeUint32(0)):Dg(A)&&(wA(i,iA.smhd,4,0,0),i.writer.writeUint16(0),i.writer.writeUint16(0)),dh(i),fh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Fh=(i,A)=>{const t=i.writer.position();dA(i,iA.mdia,0),ch(i,A),hh(i,A),ph(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Gh=(i,A,t)=>{const e=i.writer.position();dA(i,iA.trak,0),rh(i,A,t),Fh(i,A),i.writer.writeUint32At(e,i.writer.position()-e)},kh=(i,A)=>{wA(i,iA.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)},Rh=(i,A)=>{const t=i.writer.position();dA(i,iA.mvex,0),A.forEach(e=>kh(i,e)),i.writer.writeUint32At(t,i.writer.position()-t)},Uh=(i,A,t,e)=>{const g=i.writer.position();dA(i,iA.moov,0),Eh(i,0,t),A.forEach(B=>Gh(i,B,t)),Rh(i,A),i.writer.writeUint32At(g,i.writer.position()-g)},Nh=(i,A)=>{const t=i.writer.position();wA(i,iA.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)},bh=(i,A)=>{const t=i.writer.position();wA(i,iA.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)},Lh=(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();wA(i,iA.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,Jh=(i,A)=>{const t=i.writer.position();dA(i,iA.traf,0),Nh(i,A),bh(i,A),Lh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},Mh=(i,A)=>{wA(i,iA.mfhd,4,0,0),i.writer.writeUint32(A)},Hh=(i,A)=>{const t=i.writer.position();dA(i,iA.moof,0),Mh(i,A.sequenceNumber),Jh(i,A),i.writer.writeUint32At(t,i.writer.position()-t)},qh=(i,A)=>{const t=A.samples.reduce((e,g)=>e+g.data.byteLength,0);dA(i,iA.mdat,t),A.samples.forEach(e=>i.writer.writeBytes(e.data))},VB=(i,A)=>{const t=new Qa,e=i.filter(B=>We(B)&&oa(B)).length>0;return i.filter(B=>We(B)&&vQ(B)).length>0?qQ(t,Ch):e?qQ(t,Bh):qQ(t,Qh),Uh(t,i,sh),t.writer.buffer()},ZB=i=>{var t;const A=new Qa;return((t=i.samples[0])==null?void 0:t.producerReferenceTime)!==void 0&&ah(A,i.trackId,i.samples[0].producerReferenceTime,i.timestamp),A.moofOffset=A.writer.position(),Hh(A,i),qh(A,i),A.writer.buffer()},vh=(i,A)=>{const t=i.map(C=>V(S({},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 ZB({trackId:1,timestamp:e,sequenceNumber:A,defaultSize:g.byteLength,defaultFlags:33554432,defaultDuration:B,samples:t})},Kh=(i,A,t,e)=>VB([{type:"audio",codec:"aac",decoderConfig:i,channelCount:A,sampleRate:t,timescale:e,duration:0,trackId:1}]),na=i=>{const{sequenceParameterSets:A,pictureParameterSets:t}=ga(i),e=A[0],g=t[0];if(!e||!g)throw new Error("No sps or pps provided");return Yc(e)},Yh=(i,A)=>{const t=i.map(Q=>V(S({},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 ZB({trackId:1,timestamp:g,sequenceNumber:A,defaultSize:B.byteLength,defaultFlags:e?33554432:16842752,defaultDuration:C,samples:t})},Th=(i,A)=>{const{sequenceParameterSets:t,pictureParameterSets:e}=ga(i),g=na(i);return VB([{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}])},Ph=(i,A,t)=>VB([{type:"audio",trackId:1,channelCount:A,timescale:t,codec:"opus",decoderConfig:i,duration:0,sampleRate:48e3}]),xh=(i,A)=>{const t=i.map(C=>V(S({},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 ZB({trackId:1,timestamp:e,sequenceNumber:A,defaultSize:g.byteLength,defaultFlags:33554432,defaultDuration:B,samples:t})},aa=i=>{const A=new _(i);return A.peekBit()===1&&A.readBits(32),Vh(A),td(A)},Wh=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]},Oh=i=>{let A=0;for(;A<100&&i.readBit()===0;)A++;return A>=32?0:i.readBits(A)+(1<<A)-1},Vh=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?Wh(i):[0,A];return{headerLength:1+B+Q,type:g,obuSize:o}},Zh=i=>{const A=i.readBits(32),t=i.readBits(32),e=i.readBit()!==0;let g=0;return e&&(g=Oh(i)+1),{timescale:t,equalPictureInterval:e,numUnitsInDisplayTick:A,numTicksPerPicture:g}},Ea=2,YQ=2,Xh=1,jh=2,zh=2,_h=13,$h=0,Ad=2,ra=0,td=i=>{const A=i.readBits(3),e=i.readBit()!==0,g=i.readBit()!==0;let B,C=!1,Q=!1,o=!1,E=0,c=0;const h=[];if(g)i.readBits(5);else{if(Q=i.readBit()!==0,Q&&(B=Zh(i),C=i.readBit()!==0,C))throw new Error("Not implemented");o=i.readBit()!==0;const MA=i.readBits(5)+1;for(let F=0;F<MA;F++){const K=i.readBits(12),AA=i.readBits(5);let CA=0;if(AA>7&&(CA=i.readBit()),C)throw new Error("decoderModelInfoPresentFlag==1");o&&i.readBit()!==0&&i.readBits(4),h.push({tier:CA,operatingPointIdc:K,seqLevelIdx:AA})}}const l=i.readBits(4)+1,m=i.readBits(4)+1,f=i.readBits(l)+1,U=i.readBits(m)+1;let b=!1;g?b=!1:b=i.readBit()!==0,b&&(E=i.readBits(4)+2,c=i.readBits(3)+1);const Y=i.readBit()!==0,N=i.readBit()!==0,v=i.readBit()!==0;let T=!1,P=!1,X=!1,yA=!1,BA=!1,fA=!1,Bt=!1,w=Ea,R=YQ,x=0;g||(T=i.readBit()!==0,P=i.readBit()!==0,X=i.readBit()!==0,yA=i.readBit()!==0,BA=i.readBit()!==0,BA&&(fA=i.readBit()!==0,Bt=i.readBit()!==0),i.readBit()!==0?w=Ea:w=i.readBit(),w>0?i.readBit()>0?R=YQ:R=i.readBit():R=YQ,BA?x=i.readBits(3):x=0);const eA=i.readBit()!==0,O=i.readBit()!==0,j=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:f,maxFrameHeight:U,frameIdNumbersPresentFlag:b,deltaFrameIdLength:E,additionalFrameIdLength:c,use_128x128Superblock:Y,enableFilterIntra:N,enableIntraEdgeFilter:v,enableInterintraCompound:T,enableMaskedCompound:P,enableWarpedMotion:X,enableDualFilter:yA,enableOrderHint:BA,enableJntComp:fA,enableRefFrameMvs:Bt,seqForceScreenContentTools:w,seqForceIntegerMv:R,orderHintBits:x,enableSuperres:eA,enableCdef:O,enableRestoration:j,colorConfig:ed(i,A),filmGrainParamsPresent:i.readBit()!==0}},ed=(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=jh,o=zh,E=Ad,c=!1,h=0,l=0,m=ra,f=!1;return C&&(Q=i.readBits(8),o=i.readBits(8),E=i.readBits(8)),g?(c=i.readBit()!==0,h=1,l=1,m=ra,f=!1,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:E,numPlanes:B,separateUvDeltaQ:f,subsamplingX:h,subsamplingY:l,transferCharacteristics:o}):Q===Xh&&o==_h&&E==$h?(c=!0,h=0,l=0,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:E,numPlanes:B,separateUvDeltaQ:f,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)),f=i.readBit()!==0,{highBitDepth:t,bitDepth:e,monoChrome:g,chromaSamplePosition:m,colorPrimaries:Q,colorRange:c,matrixCoefficients:E,numPlanes:B,separateUvDeltaQ:f,subsamplingX:h,subsamplingY:l,transferCharacteristics:o})},id=i=>{const A=aa(i);if(A)return{width:A.maxFrameWidth,height:A.maxFrameHeight}},Id=(i,A)=>{const t=i.map(Q=>V(S({},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 ZB({trackId:1,timestamp:g,sequenceNumber:A,defaultSize:B.byteLength,defaultFlags:e?33554432:16842752,defaultDuration:C,samples:t})},gd=(i,A)=>{const t=aa(i);if(!t)throw new Error("Failed to parse sequence header");return VB([{type:"video",parsedSequenceHeader:t,sequenceHeader:new Uint8Array(i),width:t.maxFrameWidth,height:t.maxFrameHeight,timescale:A,duration:0,trackId:1}])},sd=i=>{const{codec:A,initData:t,timescale:e}=i;switch(A){case"h264":return Cd(t,e);case"av1":return Qd(t,e);case"opus":return od(t,e,i.channelCount||2);case"aac":return nd(t,e,i.channelCount||2);default:throw new Error(`Failed to initialize ${A} segment`)}},Bd=(i,A)=>{switch(i){case"h264":return na(A);case"av1":return id(A)}},Cd=(i,A)=>Th(i,A),Qd=(i,A)=>gd(i,A),od=(i,A,t)=>Ph(new Uint8Array(i),t,A),nd=(i,A,t)=>Kh(new Uint8Array(i),t,A,A),ad=(i,A)=>{if(!i[0])throw new Error("At least one sample must be provided");switch(i[0].codec){case"h264":return Yh(i,A);case"opus":return xh(i,A);case"aac":return vh(i,A);case"av1":return Id(i,A);default:throw new Error(`Unsupported codec ${i[0].codec}`)}},Sg=i=>!!(i&1),Ed=i=>!!(i&2),rd=i=>!!(i&4),cd=i=>!!(i&8),hd=i=>!!(i&16),dd=i=>{const A=new DataView(i,0),t=A.getUint8(0),e=A.getUint16(1),g=A.getUint8(3),B=A.getUint8(4),C=fQ(new Uint8Array(i),5,12),Q=A.getUint32(13),o=hd(g)?A.getInt16(17):void 0,E=i.slice(e);return{version:t,renditionId:B,flags:g,timestamp:C,timescale:Q,payload:E,compositionTimeOffset:o}},ld="data:video/mp4;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAGF21kYXTeBAAAbGliZmFhYyAxLjI4AABCAJMgBDIARwAAArEGBf//rdxF6b3m2Ui3lizYINkj7u94MjY0IC0gY29yZSAxNDIgcjIgOTU2YzhkOCAtIEguMjY0L01QRUctNCBBVkMgY29kZWMgLSBDb3B5bGVmdCAyMDAzLTIwMTQgLSBodHRwOi8vd3d3LnZpZGVvbGFuLm9yZy94MjY0Lmh0bWwgLSBvcHRpb25zOiBjYWJhYz0wIHJlZj0zIGRlYmxvY2s9MTowOjAgYW5hbHlzZT0weDE6MHgxMTEgbWU9aGV4IHN1Ym1lPTcgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0xNiBjaHJvbWFfbWU9MSB0cmVsbGlzPTEgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz02IGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTI1MCBrZXlpbnRfbWluPTI1IHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NDAgcmM9Y3JmIG1idHJlZT0xIGNyZj0yMy4wIHFjb21wPTAuNjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCB2YnZfbWF4cmF0ZT03NjggdmJ2X2J1ZnNpemU9MzAwMCBjcmZfbWF4PTAuMCBuYWxfaHJkPW5vbmUgZmlsbGVyPTAgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAAAFZliIQL8mKAAKvMnJycnJycnJycnXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXiEASZACGQAjgCEASZACGQAjgAAAAAdBmjgX4GSAIQBJkAIZACOAAAAAB0GaVAX4GSAhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGagC/AySEASZACGQAjgAAAAAZBmqAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZrAL8DJIQBJkAIZACOAAAAABkGa4C/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmwAvwMkhAEmQAhkAI4AAAAAGQZsgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGbQC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm2AvwMkhAEmQAhkAI4AAAAAGQZuAL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGboC/AySEASZACGQAjgAAAAAZBm8AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZvgL8DJIQBJkAIZACOAAAAABkGaAC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmiAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpAL8DJIQBJkAIZACOAAAAABkGaYC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmoAvwMkhAEmQAhkAI4AAAAAGQZqgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGawC/AySEASZACGQAjgAAAAAZBmuAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZsAL8DJIQBJkAIZACOAAAAABkGbIC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm0AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZtgL8DJIQBJkAIZACOAAAAABkGbgCvAySEASZACGQAjgCEASZACGQAjgAAAAAZBm6AnwMkhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AAAAhubW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAABDcAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAzB0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAA+kAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAALAAAACQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAPpAAAAAAABAAAAAAKobWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAB1MAAAdU5VxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACU21pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAhNzdGJsAAAAr3N0c2QAAAAAAAAAAQAAAJ9hdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAALAAkABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAALWF2Y0MBQsAN/+EAFWdCwA3ZAsTsBEAAAPpAADqYA8UKkgEABWjLg8sgAAAAHHV1aWRraEDyXyRPxbo5pRvPAyPzAAAAAAAAABhzdHRzAAAAAAAAAAEAAAAeAAAD6QAAABRzdHNzAAAAAAAAAAEAAAABAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAAIxzdHN6AAAAAAAAAAAAAAAeAAADDwAAAAsAAAALAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAAiHN0Y28AAAAAAAAAHgAAAEYAAANnAAADewAAA5gAAAO0AAADxwAAA+MAAAP2AAAEEgAABCUAAARBAAAEXQAABHAAAASMAAAEnwAABLsAAATOAAAE6gAABQYAAAUZAAAFNQAABUgAAAVkAAAFdwAABZMAAAWmAAAFwgAABd4AAAXxAAAGDQAABGh0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAACAAAAAAAABDcAAAAAAAAAAAAAAAEBAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAQkAAADcAABAAAAAAPgbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAC7gAAAykBVxAAAAAAALWhkbHIAAAAAAAAAAHNvdW4AAAAAAAAAAAAAAABTb3VuZEhhbmRsZXIAAAADi21pbmYAAAAQc21oZAAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAADT3N0YmwAAABnc3RzZAAAAAAAAAABAAAAV21wNGEAAAAAAAAAAQAAAAAAAAAAAAIAEAAAAAC7gAAAAAAAM2VzZHMAAAAAA4CAgCIAAgAEgICAFEAVBbjYAAu4AAAADcoFgICAAhGQBoCAgAECAAAAIHN0dHMAAAAAAAAAAgAAADIAAAQAAAAAAQAAAkAAAAFUc3RzYwAAAAAAAAAbAAAAAQAAAAEAAAABAAAAAgAAAAIAAAABAAAAAwAAAAEAAAABAAAABAAAAAIAAAABAAAABgAAAAEAAAABAAAABwAAAAIAAAABAAAACAAAAAEAAAABAAAACQAAAAIAAAABAAAACgAAAAEAAAABAAAACwAAAAIAAAABAAAADQAAAAEAAAABAAAADgAAAAIAAAABAAAADwAAAAEAAAABAAAAEAAAAAIAAAABAAAAEQAAAAEAAAABAAAAEgAAAAIAAAABAAAAFAAAAAEAAAABAAAAFQAAAAIAAAABAAAAFgAAAAEAAAABAAAAFwAAAAIAAAABAAAAGAAAAAEAAAABAAAAGQAAAAIAAAABAAAAGgAAAAEAAAABAAAAGwAAAAIAAAABAAAAHQAAAAEAAAABAAAAHgAAAAIAAAABAAAAHwAAAAQAAAABAAAA4HN0c3oAAAAAAAAAAAAAADMAAAAaAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAACMc3RjbwAAAAAAAAAfAAAALAAAA1UAAANyAAADhgAAA6IAAAO+AAAD0QAAA+0AAAQAAAAEHAAABC8AAARLAAAEZwAABHoAAASWAAAEqQAABMUAAATYAAAE9AAABRAAAAUjAAAFPwAABVIAAAVuAAAFgQAABZ0AAAWwAAAFzAAABegAAAX7AAAGFwAAAGJ1ZHRhAAAAWm1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALWlsc3QAAAAlqXRvbwAAAB1kYXRhAAAAAQAAAABMYXZmNTUuMzMuMTAw",XB=()=>"wakeLock"in navigator&&window.navigator.userAgent.indexOf("Samsung")===-1;class ud{constructor(){I(this,"enabled",!1);I(this,"wakeLockVideo");I(this,"_wakeLock",null);I(this,"handleVisibilityChange",()=>{this._wakeLock!==null&&document.visibilityState==="visible"&&this.enable()});XB()&&(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(!XB()){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",ld),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 XB()?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;XB()?(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 wd=/\r\n|\r|\n/;class ca{constructor(A){n(this,de);n(this,Zt);a(this,de,A),a(this,Zt,0)}skipEmptyLines(){let A=0;for(;s(this,de)[s(this,Zt)]==="";)ft(this,Zt)._++,A++;return A}readLine(){return s(this,de)[ft(this,Zt)._++]}takeUntilEmptyLine(){const A=[];for(;s(this,de)[s(this,Zt)]!=="";){const t=this.readLine();if(t===void 0)break;A.push(t)}return A}linesLeft(){return s(this,de).length-s(this,Zt)}}de=new WeakMap,Zt=new WeakMap;class ha{constructor(){n(this,ii)}parse(A){const t=[],e=A.split(wd),g=new ca(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,ii,jE).call(this,g);t.push(C),g.skipEmptyLines()}return t}}ii=new WeakSet,jE=function(A){A.skipEmptyLines();const t=A.takeUntilEmptyLine(),e=new ca(t);let g=e.readLine(),B;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,E]=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,ii,on).call(this,C),l=d(this,ii,on).call(this,o);return{id:B,startTime:h,endTime:l,text:c}},on=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};class TQ extends $A{constructor({type:t,autoplay:e,muted:g,logger:B,poster:C}){super();I(this,"element");I(this,"logger");I(this,"seekTimes",new L(10));I(this,"seekStartTime");I(this,"_userProvidedMuted");I(this,"timers",new RA);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(y)});I(this,"play",()=>{this.element.muted=this._userProvidedMuted,this._play().catch(t=>{if(t instanceof Error){const e=new W("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:Wi(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 Dd=["minBufferTime","maxBufferTime","burstEnabled","sizeBasedResolutionCapEnabled","separateVideoSocketEnabled","videoCodecs"];function Sd(i){return Dd.includes(i)}class md{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&&Sd(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 yd=i=>{const A=window;A.vindralInstances=A.vindralInstances||{},A.vindralInstances[i.getStatistics().clientId.substring(0,8)]=i},fd=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 Pe(i)?A={type:"media-source",audio:{contentType:xe(i),bitrate:i.bitRate,channels:i.channels.toString(),samplerate:i.sampleRate}}:A={type:"media-source",video:{contentType:xe(i),bitrate:i.bitRate,width:i.width,height:i.height,framerate:i.frameRate[0]/i.frameRate[1]}},navigator.mediaCapabilities.decodingInfo(A)},pd=.15,Fd=.2,da=.4,Gd=.5,kd=.6,PQ=15,Rd={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,mC=class mC{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),E=this.qualityOfServiceSource.timeActive()-this.qualityOfServiceSource.timeSpentBuffering(),c=o*E/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,{slope:C}=g,Q=g.predict(PQ),o=C<0,E=g.predict(PQ)<da&&g.slope<0,c=g.predict(PQ)>kd,h=this.qualityOfServiceSource.timeSpentBufferingLast(30*1e3),l=this.qualityOfServiceSource.timeSpentActiveLast(30*1e3),m=h/l;if(t<.15&&m>.8){this.adaptLevel("reconnect");return}if(e.decodeRate<=1){this.adaptLevel("downgrade");return}E||t<pd?o&&t<da&&Q<Fd&&this.adaptLevel(A.playbackState==="buffering"?"double downgrade":"downgrade"):t>Gd&&c&&!this.tooMuchTimeBuffering(B)&&!this.tooManyBufferingEvents(B)&&this.adaptLevel("upgrade")});I(this,"onAdaptedLevel",()=>{this.reset()});I(this,"adaptLevel",A=>this.emitter.emit("adapt level",A));this.qualityOfServiceSource=e,this.config=S(S({},Rd),g),this.emitter=A,this.logger=t}tooMuchTimeBuffering(A){return this.qualityOfServiceSource.timeSpentBufferingLast(A)/this.qualityOfServiceSource.timeSpentActiveLast(A)>this.config.maxBufferingRatio.last10Seconds}tooManyBufferingEvents(A){return this.qualityOfServiceSource.timeSpentBufferingLast(A)>this.config.maxBufferingEvents.last10Seconds}};I(mC,"create",(A,t,e,g={})=>new mC(A,t,e,g));let WQ=mC;const Ud={minBufferTime:1500,maxBufferTime:1500,cooldownTime:3e4,maxBufferingEvents:{last30Seconds:3},maxBufferingRatio:{last30Seconds:.15}},le=class le{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,E=Math.ceil(Math.max((e-t)/(le.BUFFER_TIME_MAX_STEPS-1),le.BUFFER_TIME_STEP_SIZE));(o>this.config.maxBufferingRatio.last30Seconds||C>this.config.maxBufferingEvents.last30Seconds)&&(this.targetBufferTimeTarget.targetBufferTime=Math.min(e,this.targetBufferTimeTarget.targetBufferTime+E),this.bufferTimeAdjustmentCount++,this.reset())});this.qualityOfServiceSource=e,this.targetBufferTimeTarget=g,this.config=S(S({},Ud),B),this.emitter=A,this.logger=t}updateConfig(A){this.config=S(S({},this.config),A)}};I(le,"BUFFER_TIME_STEP_SIZE",500),I(le,"BUFFER_TIME_MAX_STEPS",3),I(le,"create",(A,t,e,g,B={})=>new le(A,t,e,g,B));let OQ=le;var jB=(i=>(i[i.StreamHeaderGroup=4]="StreamHeaderGroup",i[i.FetchHeader=5]="FetchHeader",i[i.StreamHeaderTrack=60]="StreamHeaderTrack",i))(jB||{});const qA={Normal:0,ObjectDoesNotExist:1,GroupDoesNotExist:2,EndOfGroup:3,EndOfTrackAndGroup:4};function la(i){switch(i){case qA.Normal:case qA.ObjectDoesNotExist:case qA.GroupDoesNotExist:case qA.EndOfGroup:case qA.EndOfTrackAndGroup:return}throw new Error("Unknown object status "+i)}class Nd{constructor(A,t,e,g,B,C){n(this,kt);n(this,gI);n(this,sI);n(this,Is);n(this,gs);n(this,BI,new G);n(this,ss,0);n(this,Bs);a(this,kt,A),a(this,gI,t),a(this,sI,e),a(this,Is,g),a(this,gs,B),a(this,Bs,C)}endStatus(){return s(this,BI).promise}groupId(){return s(this,gI)}subscribeId(){return s(this,sI)}next(){return r(this,null,function*(){if(!s(this,BI).pending)return{done:!0,value:void 0};if(yield s(this,kt).isDone())return{done:!0,value:void 0};const A=s(this,ss)===0?s(this,gI):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===qA.EndOfTrackAndGroup||g===qA.EndOfGroup)&&s(this,BI).resolve(g),ft(this,ss)._++,{done:!1,value:{subscribeId:s(this,sI),trackAlias:s(this,Is),groupId:A,subGroupId:q(0),objectId:t,subscriberPriority:s(this,gs),streamId:s(this,Bs),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,gI=new WeakMap,sI=new WeakMap,Is=new WeakMap,gs=new WeakMap,BI=new WeakMap,ss=new WeakMap,Bs=new WeakMap;class bd{constructor(A,t,e,g,B){n(this,Ii);n(this,Rt);n(this,CI);n(this,Cs);n(this,Qs);n(this,QI);a(this,Rt,A),a(this,CI,t),a(this,Cs,e),a(this,Qs,g),a(this,QI,B)}streamId(){return s(this,QI)}groups(){return d(this,Ii,zE).call(this)}subscribeId(){return s(this,CI)}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,Ii,nn).call(this)}[Symbol.asyncDispose](){return d(this,Ii,nn).call(this)}}Rt=new WeakMap,CI=new WeakMap,Cs=new WeakMap,Qs=new WeakMap,QI=new WeakMap,Ii=new WeakSet,zE=function(){return Qe(this,null,function*(){for(;!(yield new aA(s(this,Rt).isDone()));){const A=yield new aA(s(this,Rt).readBigVarInt()),t=new Nd(s(this,Rt),A,s(this,CI),s(this,Cs),s(this,Qs),s(this,QI));if(yield t,(yield new aA(Promise.race([t.endStatus(),s(this,Rt).closed()])))===qA.EndOfTrackAndGroup)return}})},nn=function(){return s(this,Rt).close().catch(()=>{})};class Ld{constructor(A,t,e,g,B,C,Q){n(this,gi);n(this,ht);n(this,oI);n(this,os);n(this,nI);n(this,ns);n(this,as);n(this,Es,!1);n(this,aI);n(this,yC,kA.get().createContext("GroupReader"));a(this,ht,A),a(this,oI,t),a(this,os,e),a(this,nI,g),a(this,ns,B),a(this,as,C),a(this,aI,Q)}streamId(){return s(this,aI)}groupId(){return s(this,nI)}subscribeId(){return s(this,oI)}next(){return r(this,null,function*(){try{if((yield s(this,ht).isDone())||s(this,Es))return{done:!0,value:void 0};const A=yield s(this,ht).readBigVarInt(),t=yield s(this,ht).readVarInt();let e=0,g=new Uint8Array;return t>0?g=yield s(this,ht).read(t):e=yield s(this,ht).readVarInt(),la(e),e===qA.EndOfGroup&&a(this,Es,!0),{done:!1,value:{subscribeId:s(this,oI),trackAlias:s(this,os),groupId:s(this,nI),subGroupId:s(this,ns),subscriberPriority:s(this,as),streamId:s(this,aI),objectId:A,objectStatus:e,payload:g}}}catch(A){return s(this,yC).info("Error reading object",{error:A}),{done:!0,value:void 0}}})}return(){return r(this,null,function*(){return yield s(this,ht).close().catch(()=>{}),{done:!0,value:void 0}})}groups(){return d(this,gi,_E).call(this)}[Symbol.asyncIterator](){return this}[pt()](){return d(this,gi,an).call(this)}[Symbol.asyncDispose](){return d(this,gi,an).call(this)}}ht=new WeakMap,oI=new WeakMap,os=new WeakMap,nI=new WeakMap,ns=new WeakMap,as=new WeakMap,Es=new WeakMap,aI=new WeakMap,yC=new WeakMap,gi=new WeakSet,_E=function(){return Qe(this,null,function*(){yield this})},an=function(){return s(this,ht).close().catch(()=>{})};function ua(i,A){return r(this,null,function*(){const t=yield i.readVarInt();switch(t){case jB.StreamHeaderGroup:{const e=yield i.readBigVarInt(),g=yield i.readBigVarInt(),B=yield i.readBigVarInt(),C=yield i.readBigVarInt(),Q=yield i.readUnsigned8();return new Ld(i,e,g,B,C,Q,A)}case jB.StreamHeaderTrack:{const e=yield i.readBigVarInt(),g=yield i.readBigVarInt(),B=yield i.readUnsigned8();return new bd(i,e,g,B,A)}default:throw new Error("Unexpected message type "+t)}})}class Jd{constructor(A,t){n(this,ue);n(this,rs);a(this,ue,A),a(this,rs,t)}start(A){s(this,ue).addEventListener("message",t=>{if(typeof t.data=="object"&&t.data instanceof ArrayBuffer){const e=new Uint8Array(t.data);e[0]==s(this,rs)&&A.enqueue(e.subarray(1))}}),s(this,ue).addEventListener("error",()=>A.error(new Error("WebSocket error"))),s(this,ue).addEventListener("close",()=>yn(()=>A.close()))}cancel(A){s(this,ue).close(void 0,A)}}ue=new WeakMap,rs=new WeakMap;class Md{constructor(A){n(this,Ut);n(this,si,null);n(this,Bi,null);n(this,Ci,null);a(this,Ut,A)}start(A){a(this,si,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])}}}),a(this,Bi,()=>yn(()=>A.close())),a(this,Ci,()=>A.error(new Error("WebSocket error"))),s(this,Ut).addEventListener("message",s(this,si)),s(this,Ut).addEventListener("error",s(this,Ci)),s(this,Ut).addEventListener("close",s(this,Bi))}cancel(A){s(this,si)&&s(this,Ut).removeEventListener("message",s(this,si)),s(this,Ci)&&s(this,Ut).removeEventListener("error",s(this,Ci)),s(this,Bi)&&s(this,Ut).removeEventListener("close",s(this,Bi))}}Ut=new WeakMap,si=new WeakMap,Bi=new WeakMap,Ci=new WeakMap;class zB{constructor(A,t){n(this,IA);n(this,Nt);n(this,cs);n(this,Qi);n(this,bt,0);n(this,fC,new TextDecoder);a(this,Nt,A),a(this,cs,t),a(this,Qi,t.getReader())}readUnsigned8(){return r(this,null,function*(){return yield d(this,IA,vi).call(this,1),d(this,IA,qe).call(this,1)[0]})}readString(){return r(this,null,function*(){const A=yield this.readVarInt(),t=yield this.read(A);return s(this,fC).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,IA,vi).call(this,1);const A=(d(this,IA,hQ).call(this,1)[0]&192)>>6;switch(s(this,Nt)[s(this,bt)]=d(this,IA,hQ).call(this,1)[0]&63,A){case 0:return q(d(this,IA,qe).call(this,1)[0]);case 1:{yield d(this,IA,vi).call(this,2);const t=d(this,IA,qe).call(this,2),e=new DataView(t.buffer,t.byteOffset,t.byteLength);return q(e.getUint16(0))}case 2:{yield d(this,IA,vi).call(this,4);const t=d(this,IA,qe).call(this,4),e=new DataView(t.buffer,t.byteOffset,t.byteLength);return q(e.getUint32(0))}case 3:{yield d(this,IA,vi).call(this,8);const t=d(this,IA,qe).call(this,8),e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(typeof e.getBigUint64!="undefined")return q(e.getBigUint64(0));const g=fQ(t,0,7);return q(g)}default:throw new Error("Invalid VarInt size")}})}read(A){return r(this,null,function*(){return yield d(this,IA,vi).call(this,A),d(this,IA,qe).call(this,A)})}readAll(){return r(this,null,function*(){for(;yield d(this,IA,cQ).call(this););return d(this,IA,qe).call(this,d(this,IA,uB).call(this))})}isDone(){return r(this,null,function*(){return d(this,IA,uB).call(this)>0?!1:(yield d(this,IA,cQ).call(this))==0})}closed(){return r(this,null,function*(){return s(this,Qi).closed})}close(){return r(this,null,function*(){return s(this,Qi).releaseLock(),s(this,cs).cancel()})}}Nt=new WeakMap,cs=new WeakMap,Qi=new WeakMap,bt=new WeakMap,fC=new WeakMap,IA=new WeakSet,uB=function(){return s(this,Nt).length-s(this,bt)},cQ=function(){return r(this,null,function*(){const{value:A,done:t}=yield s(this,Qi).read();if(t)return Promise.resolve(0);if(d(this,IA,uB).call(this)===0)a(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),a(this,Nt,B)}return a(this,bt,0),Promise.resolve(A.length)})},vi=function(A){return r(this,null,function*(){for(;d(this,IA,uB).call(this)<A;)if((yield d(this,IA,cQ).call(this))===0)throw new Error("Read failed")})},hQ=function(A){return s(this,Nt).subarray(s(this,bt),s(this,bt)+A)},qe=function(A){const t=d(this,IA,hQ).call(this,A);return a(this,bt,s(this,bt)+t.length),t};class wa{constructor(A){n(this,EI,new Uint8Array(8));n(this,rI);n(this,Xt);n(this,pC,new TextEncoder);a(this,rI,A),a(this,Xt,s(this,rI).getWriter())}writeString(A){return r(this,null,function*(){const t=s(this,pC).encode(A);return yield this.writeVarInt(t.length),this.write(t)})}write(A){return s(this,Xt).write(A)}writeUnsigned8(A){return s(this,Xt).write(_B(A,s(this,EI)))}writeVarInt(A){return s(this,Xt).write(ka(A,s(this,EI)))}writeBigVarInt(A){return s(this,Xt).write(Ra(A,s(this,EI)))}flush(){return r(this,null,function*(){})}close(){return r(this,null,function*(){s(this,Xt).releaseLock(),yield s(this,rI).close()})}}EI=new WeakMap,rI=new WeakMap,Xt=new WeakMap,pC=new WeakMap;const Da={OPEN:1},hs=class hs{constructor(A){n(this,OA,0);n(this,ZA,new Uint8Array(hs.DEFAULT_BUFFER_SIZE));n(this,oi);n(this,FC,new TextEncoder);a(this,oi,A)}writeString(A){return r(this,null,function*(){const t=s(this,FC).encode(A);return yield this.writeVarInt(t.length),this.write(t)})}ensureBufferSpace(A){if(s(this,ZA).length-s(this,OA)>=A)return;const t=new Uint8Array(s(this,ZA).length+A);t.set(s(this,ZA)),a(this,ZA,t)}write(A){return this.ensureBufferSpace(A.length),s(this,ZA).set(A,s(this,OA)),a(this,OA,s(this,OA)+A.byteLength),Promise.resolve()}writeUnsigned8(A){return this.ensureBufferSpace(1),_B(A,s(this,ZA).subarray(s(this,OA))),a(this,OA,s(this,OA)+1),Promise.resolve()}writeVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return this.ensureBufferSpace(8),a(this,OA,s(this,OA)+ka(A,s(this,ZA).subarray(s(this,OA))).byteLength),Promise.resolve()}writeBigVarInt(A){if(A<0)throw new Error(`VarInt can not be negative: ${A}`);return this.ensureBufferSpace(8),a(this,OA,s(this,OA)+Ra(A,s(this,ZA).subarray(s(this,OA))).byteLength),Promise.resolve()}flush(){if(s(this,oi).readyState!==Da.OPEN)throw new Error("Writer is not open");return s(this,oi).send(s(this,ZA).subarray(0,s(this,OA))),a(this,OA,0),a(this,ZA,new Uint8Array(hs.DEFAULT_BUFFER_SIZE)),Promise.resolve()}close(){return s(this,oi).close(),Promise.resolve()}};OA=new WeakMap,ZA=new WeakMap,oi=new WeakMap,FC=new WeakMap,I(hs,"DEFAULT_BUFFER_SIZE",1024);let mg=hs;const Sa=Math.pow(2,6)-1,ma=Math.pow(2,14)-1,ya=Math.pow(2,30)-1,Hd=Number.MAX_SAFE_INTEGER,qd=typeof BigInt=="function"?sn(q(2),q(62))-q(1):q(Number.MAX_SAFE_INTEGER);function _B(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<=Sa)return _B(i,A);if(i<=ma)return fa(i|16384,A);if(i<=ya)return pa(i|2147483648,A);if(i<=Hd)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<Sa)return _B(Number(i),A);if(i<ma)return fa(Number(i)|16384,A);if(i<=ya)return pa(Number(i)|2147483648,A);if(i<=qd)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 J=(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))(J||{});function $B(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 VQ(i,A){return r(this,null,function*(){yield i.writeVarInt(A.length);for(const t of A)yield i.writeString(t)})}const AC=q(2);function Zi(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 Xi(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 vd(i){return r(this,null,function*(){return{type:J.Announce,namespace:yield $B(i),params:yield Zi(i)}})}function Kd(i,A){return r(this,null,function*(){yield VQ(i,A.namespace),yield Xi(i,A.params)})}function Yd(i){return r(this,null,function*(){return{type:J.AnnounceOk,namespace:yield $B(i)}})}function Td(i,A){return r(this,null,function*(){yield VQ(i,A.namespace)})}const Pd={Subscriber:2},tC={Role:q(0)},Ua={Draft07:4278190087};function Na(i){return r(this,null,function*(){const A=yield i.readVarInt();switch(A){case Ua.Draft07:return{type:"known",value:A};default:return{type:"unknown",value:A}}})}function xd(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 Xi(i,A.parameters)})}function Wd(i){return r(this,null,function*(){const A=[],t=yield i.readVarInt();for(let g=0;g<t;g++)A.push(yield Na(i));const e=yield Zi(i);if(!e.has(tC.Role))throw new Error("Role parameter is required");return{type:J.ClientSetup,supportedVersions:A,parameters:e}})}function Od(i,A){return r(this,null,function*(){yield i.writeVarInt(A.selectedVersion.value),yield Xi(i,A.parameters)})}function Vd(i){return r(this,null,function*(){const A=yield Na(i);if(A.type!=="known")throw new Error("Expected known version");const t=yield Zi(i);if(!t.has(tC.Role))throw new Error("Role parameter is required");return{type:J.ServerSetup,selectedVersion:A,parameters:t}})}const Zd={"latest-group":1,"latest-object":2,"absolute-start":3,"absolute-range":4};function Xd(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 jd(i,A){return r(this,null,function*(){const t=Zd[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 ba(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 La(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 $B(i),g=yield i.readString(),B=yield i.readUnsigned8(),C=yield ba(i),Q=yield Xd(i),o=yield Zi(i);if(Q.type==="absolute-range"){const E=Q.start.group>Q.end.group,c=Q.start.group===Q.end.group&&Q.start.object>Q.end.object;if(E||c)throw new Error("Invalid filter range")}return{type:J.Subscribe,id:A,trackAlias:t,namespace:e,name:g,subscriberPriority:B,groupOrder:C,filterType:Q,params:o}})}function _d(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.trackAlias),yield VQ(i,A.namespace),yield i.writeString(A.name),yield i.writeUnsigned8(A.subscriberPriority),yield La(i,A.groupOrder),yield jd(i,A.filterType),yield Xi(i,A.params)})}const ZQ={TrackEnded:3,Expired:6};function $d(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:J.SubscribeDone,id:A,errorCode:t,reason:e,finalInfo:B}})}function Al(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 tl(i){return r(this,null,function*(){return{type:J.SubscribeError,id:yield i.readBigVarInt(),errorCode:yield i.readBigVarInt(),reason:yield i.readString(),trackAlias:yield i.readBigVarInt()}})}function el(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 il(i){return r(this,null,function*(){const A=yield i.readBigVarInt(),t=yield i.readBigVarInt(),e=yield ba(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 Zi(i);return{type:J.SubscribeOk,id:A,groupOrder:e,expires:t,largestInfo:B,params:C}})}function Il(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id),yield i.writeBigVarInt(A.expires),yield La(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 Xi(i,A.params)})}function gl(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 Zi(i),o=t>g,E=t===g&&e>B;if(o||E)throw new Error("Invalid filter range");return{type:J.SubscribeUpdate,id:A,start:{group:t,object:e},end:{group:g,object:B},subscriberPriority:C,params:Q}})}function sl(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 Xi(i,A.params)})}function Bl(i){return r(this,null,function*(){return{type:J.Unsubscribe,id:yield i.readBigVarInt()}})}function Cl(i,A){return r(this,null,function*(){yield i.writeBigVarInt(A.id)})}class Ja{constructor(A){n(this,cA);n(this,jt);n(this,cI,new Uint8Array);a(this,jt,A)}write(A){return r(this,null,function*(){yield s(this,jt).writeVarInt(A.type);const t=new mg({close:()=>{},readyState:Da.OPEN,send:e=>{a(this,cI,new Uint8Array(e))}});switch(A.type){case J.Subscribe:yield d(this,cA,tr).call(this,t,A);break;case J.Announce:yield d(this,cA,Br).call(this,t,A);break;case J.SubscribeOk:yield d(this,cA,er).call(this,t,A);break;case J.SubscribeUpdate:yield d(this,cA,Ir).call(this,t,A);break;case J.SubscribeError:yield d(this,cA,ir).call(this,t,A);break;case J.SubscribeDone:yield d(this,cA,gr).call(this,t,A);break;case J.Unsubscribe:yield d(this,cA,sr).call(this,t,A);break;case J.ClientSetup:yield d(this,cA,$E).call(this,t,A);break;case J.ServerSetup:yield d(this,cA,Ar).call(this,t,A);break;case J.AnnounceOk:yield d(this,cA,Cr).call(this,t,A);break;default:throw new Error(`Unknown message type: ${A.type}`)}yield t.flush(),yield s(this,jt).writeVarInt(s(this,cI).byteLength),yield s(this,jt).write(s(this,cI)),yield s(this,jt).flush()})}close(){return r(this,null,function*(){return s(this,jt).close()})}}jt=new WeakMap,cI=new WeakMap,cA=new WeakSet,$E=function(A,t){return r(this,null,function*(){yield xd(A,t)})},Ar=function(A,t){return r(this,null,function*(){yield Od(A,t)})},tr=function(A,t){return r(this,null,function*(){yield _d(A,t)})},er=function(A,t){return r(this,null,function*(){yield Il(A,t)})},ir=function(A,t){return r(this,null,function*(){yield el(A,t)})},Ir=function(A,t){return r(this,null,function*(){yield sl(A,t)})},gr=function(A,t){return r(this,null,function*(){yield Al(A,t)})},sr=function(A,t){return r(this,null,function*(){yield Cl(A,t)})},Br=function(A,t){return r(this,null,function*(){yield Kd(A,t)})},Cr=function(A,t){return r(this,null,function*(){yield Td(A,t)})};class Ql{constructor(A,t){n(this,hI);n(this,ds);n(this,ls);a(this,hI,A),a(this,ds,new Ja(A)),a(this,ls,t)}write(A){return r(this,null,function*(){yield s(this,hI).write(s(this,ls)),yield s(this,ds).write(A)})}close(){return s(this,hI).close()}}hI=new WeakMap,ds=new WeakMap,ls=new WeakMap;function ol(i){return r(this,null,function*(){return{type:J.AnnounceError,namespace:yield $B(i),errorCode:yield i.readBigVarInt(),reason:yield i.readString()}})}function nl(i,A,t){return r(this,null,function*(){return{type:J.Unknown,messageType:A,payload:yield i.read(t)}})}class Ma{constructor(A){n(this,SA);a(this,SA,A)}cancel(){return s(this,SA).close()}read(){return r(this,null,function*(){const A=yield s(this,SA).readVarInt(),t=yield s(this,SA).readVarInt();switch(A){case J.ServerSetup:return Vd(s(this,SA));case J.ClientSetup:return Wd(s(this,SA));case J.Subscribe:return zd(s(this,SA));case J.SubscribeOk:return il(s(this,SA));case J.SubscribeDone:return $d(s(this,SA));case J.SubscribeError:return tl(s(this,SA));case J.SubscribeUpdate:return gl(s(this,SA));case J.Unsubscribe:return Bl(s(this,SA));case J.Announce:return vd(s(this,SA));case J.AnnounceOk:return Yd(s(this,SA));case J.AnnounceError:return ol(s(this,SA))}return nl(s(this,SA),q(A),t)})}}SA=new WeakMap;const uI=class uI{constructor(A,t){n(this,GC);n(this,us);n(this,dI);n(this,lI,new G);n(this,ws,new G);a(this,us,A),a(this,dI,t),s(this,lI).resolve()}write(A){return r(this,null,function*(){const t=yield d(this,GC,Qr).call(this);try{yield s(this,us).write(A)}finally{t.resolve()}})}markPostHandshake(){s(this,ws).resolve()}postHandshake(){return s(this,ws).promise}read(){return r(this,null,function*(){return s(this,dI).read()})}cancel(){return s(this,dI).cancel()}static wrapWebsocket(A){const t=new ReadableStream(new Jd(A,s(uI,kC))),e=new Ma(new zB(new Uint8Array([]),t)),g=new Ql(new mg(A),new Uint8Array([0]));return new uI(g,e)}static wrapWebTransport(A){const t=A.writable,e=A.readable;return new uI(new Ja(new wa(t)),new Ma(new zB(new Uint8Array,e)))}};us=new WeakMap,dI=new WeakMap,lI=new WeakMap,ws=new WeakMap,GC=new WeakSet,Qr=function(){const A=new G,t=s(this,lI).promise.then(()=>A);return a(this,lI,A),t},kC=new WeakMap,n(uI,kC,0);let eC=uI;function Ha(i,A){return r(this,null,function*(){yield i.write({type:J.ClientSetup,supportedVersions:[{type:"known",value:Ua.Draft07}],parameters:new Map([[tC.Role,{type:tC.Role,payload:new Uint8Array([A])}]])});const t=yield i.read();if(i.markPostHandshake(),t.type!==J.ServerSetup)throw new Error("Expected server setup message");if(t.selectedVersion.type!=="known")throw new Error("Expected known version")})}class al{constructor(A){I(this,"announce");n(this,wI,new G);this.announce=A}onOk(A){s(this,wI).resolve(A)}onError(A){const t=new Error(A.reason);return s(this,wI).reject(t),t}ok(){return s(this,wI).promise}}wI=new WeakMap;function El(i){const A=new al(i);return new rl(A)}class rl{constructor(A){I(this,"state");this.state=A}}const SI=class SI{constructor(A){I(this,"subscribe");n(this,DI,new G);n(this,we,new G);n(this,ni,new G);n(this,RC,Date.now());n(this,ai,new G);n(this,dt);switch(this.subscribe=A,A.filterType.type){case"absolute-start":a(this,dt,{startGroup:A.filterType.start.group});break;case"absolute-range":a(this,dt,{startGroup:A.filterType.start.group,endGroup:A.filterType.end.group});break}}onUpdate(A){a(this,dt,{startGroup:A.start.group}),A.end.group>q(0)&&(s(this,dt).endGroup=A.end.group-q(1))}onError(A){const t=new Error(A.reason);return s(this,DI).reject(t),s(this,we).reject(t),t}onDone(A){A.finalInfo&&(s(this,dt)||a(this,dt,{startGroup:q(0)}),s(this,dt).endGroup=A.finalInfo.group),s(this,we).resolve(A)}onUnsubscribe(A){s(this,ni).resolve(A)}onOk(A){const t=Math.max(0,Date.now()-s(this,RC)),e=Number(A.expires);if(e>0){const g=Math.max(SI.minGraceTime,Math.min(e/10,SI.maxGraceTime));Promise.race([Ye(e-g-t),this.done().catch(y)]).then(()=>s(this,ai).resolve(this.expiryState())).catch(y)}s(this,DI).resolve(A)}done(){return s(this,we).promise}ok(){return s(this,DI).promise}range(){return s(this,dt)}close(){s(this,ai).promise.catch(y),s(this,ai).reject(new Error("Subscription closed"))}expiryState(){return s(this,we).resolved&&s(this,we).resolved.errorCode!==ZQ.Expired?"done":s(this,ni).pending?"active":"unsubscribed"}unsubscribed(){return s(this,ni).promise}isUnsubscribed(){return s(this,ni).resolved}expiryNotification(){return s(this,ai).promise}};DI=new WeakMap,we=new WeakMap,ni=new WeakMap,RC=new WeakMap,ai=new WeakMap,dt=new WeakMap,I(SI,"maxGraceTime",15e3),I(SI,"minGraceTime",3e3);let iC=SI;class cl{constructor(A){n(this,LA);n(this,Ds,!1);a(this,LA,A)}write(A){return r(this,null,function*(){s(this,Ds)||(yield s(this,LA).writeVarInt(jB.StreamHeaderGroup),yield s(this,LA).writeBigVarInt(A.subscribeId),yield s(this,LA).writeBigVarInt(A.trackAlias),yield s(this,LA).writeBigVarInt(A.groupId),yield s(this,LA).writeBigVarInt(A.subGroupId),yield s(this,LA).writeUnsigned8(A.subscriberPriority),a(this,Ds,!0)),yield s(this,LA).writeBigVarInt(A.objectId),yield s(this,LA).writeVarInt(A.payload.length),A.payload.length>0?yield s(this,LA).write(A.payload):yield s(this,LA).writeVarInt(A.objectStatus),yield s(this,LA).flush()})}close(){return r(this,null,function*(){yield s(this,LA).close()})}}LA=new WeakMap,Ds=new WeakMap;class hl{constructor(A,t,e,g){n(this,UC);n(this,Ss);n(this,et);n(this,ms);n(this,ys);n(this,mI);n(this,fs);a(this,Ss,t),a(this,et,A),a(this,ms,e),a(this,ys,g),a(this,fs,kA.get().createContext(`SubscriptionWriter:${A.subscribe.name}`))}finalInfo(){return s(this,mI)}run(){return r(this,null,function*(){yield Promise.race([d(this,UC,or).call(this).catch(A=>s(this,fs).error("error writing subscription",A)),s(this,et).unsubscribed(),s(this,et).done(),s(this,et).expiryNotification().catch(y)])})}done(A,t){return r(this,null,function*(){if(s(this,et).isUnsubscribed())return;const e={type:J.SubscribeDone,id:s(this,et).subscribe.id,errorCode:A,reason:t,finalInfo:s(this,mI)};s(this,et).onDone(e),yield s(this,ys).push(e)})}[pt()](){return this.done(ZQ.TrackEnded,"Track ended")}[Symbol.asyncDispose](){return this.done(ZQ.TrackEnded,"Track ended")}}Ss=new WeakMap,et=new WeakMap,ms=new WeakMap,ys=new WeakMap,mI=new WeakMap,fs=new WeakMap,UC=new WeakSet,or=function(){return r(this,null,function*(){try{for(var C=EA(s(this,Ss)),Q,o,E;Q=!(o=yield C.next()).done;Q=!1){const c=o.value;var A=[];try{const h=s(this,et).range();if(h&&(h.startGroup>c.id||h.endGroup&&h.endGroup<c.id))break;const l=yield s(this,ms).openSendStream();const m=new cl(l);const f=Ct(A,new dl(m,c.consume(),s(this,et)),!0);yield f.run();a(this,mI,f.finalGroup())}catch(t){var e=t,g=!0}finally{var B=Qt(A,e,g);B&&(yield B)}}}catch(o){E=[o]}finally{try{Q&&(o=C.return)&&(yield o.call(C))}finally{if(E)throw E[0]}}})};class dl{constructor(A,t,e){n(this,Ei);n(this,ps);n(this,yI);n(this,Fs);n(this,fI);a(this,Ei,A),a(this,ps,t),a(this,yI,e),a(this,fI,kA.get().createContext(`GroupSubscriptionWriter:${e.subscribe.name}`))}finalGroup(){return s(this,Fs)}run(){return r(this,null,function*(){s(this,fI).debug("write group");try{for(var A=EA(s(this,ps)),t,e,g;t=!(e=yield A.next()).done;t=!1){const B=e.value;yield s(this,Ei).write({subscribeId:s(this,yI).subscribe.id,trackAlias:s(this,yI).subscribe.trackAlias,subGroupId:q(0),subscriberPriority:0,groupId:B.groupId,objectId:B.objectId,objectStatus:B.objectStatus,payload:B.payload}),a(this,Fs,{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,fI).debug("write group done")})}[pt()](){return s(this,Ei).close().catch(y)}[Symbol.asyncDispose](){return s(this,Ei).close().catch(y)}}Ei=new WeakMap,ps=new WeakMap,yI=new WeakMap,Fs=new WeakMap,fI=new WeakMap;class ll{constructor(A,t,e){n(this,De);I(this,"state");n(this,Gs);n(this,ri);this.state=A,a(this,Gs,t),a(this,ri,e)}ok(A){return r(this,null,function*(){var o,E,c;const t=(o=this.state.range())==null?void 0:o.startGroup,e=A.latest(),g=e==null?void 0:e.id,B=(c=(E=e==null?void 0:e.latest())==null?void 0:E.objectId)!=null?c:q(0),C=A.consume(t!=null?t:g),Q={type:J.SubscribeOk,id:this.state.subscribe.id,expires:q(0),groupOrder:"ascending",params:new Map,largestInfo:g?{group:g,object:B}:void 0};return yield s(this,ri).push(Q),new hl(this.state,C,s(this,Gs),s(this,ri))})}invalidRange(){return d(this,De,rg).call(this,q(1),"Invalid range")}retryTrackAlias(){return d(this,De,rg).call(this,q(2),"Retry track alias")}trackDoesNotExist(){return d(this,De,rg).call(this,q(3),"Track does not exist")}unauthorized(){return d(this,De,rg).call(this,q(4),"Unauthorized")}timeout(){return d(this,De,rg).call(this,q(5),"Timeout")}[pt()](){return this.trackDoesNotExist()}[Symbol.asyncDispose](){return this.trackDoesNotExist()}}Gs=new WeakMap,ri=new WeakMap,De=new WeakSet,rg=function(A,t){const e={type:J.SubscribeError,id:this.state.subscribe.id,errorCode:A,reason:t,trackAlias:this.state.subscribe.trackAlias};return s(this,ri).push(e)},mE=[xA({context:"Session",enter:"info",error:"error"})];class XQ{constructor(A,t,e){qi(Oo,5,this);n(this,pI);n(this,ks);n(this,FI);n(this,ci,kA.get().createContext("Publisher"));n(this,Se,new HA(new Map));n(this,me,new HA(new Map));n(this,ye,new z(10));a(this,pI,A),a(this,ks,t),a(this,FI,e)}announce(A){return r(this,null,function*(){if(s(this,Se).current().has(A.join("/")))throw new Error("Duplicate announcement");const t=new Map,e=s(this,pI).authToken();e&&t.set(AC,{type:AC,payload:new TextEncoder().encode(e)});const g={type:J.Announce,namespace:A,params:t},B=El(g);if(s(this,Se).update(Q=>Q.set(g.namespace.join("/"),B)),yield s(this,FI).push(g),!(yield Promise.race([B.state.ok(),s(this,pI).closed()])))throw new Error("Session closed")})}close(){s(this,me).current().forEach(A=>A.close()),s(this,me).close(),s(this,Se).close(),s(this,ye).close()}incomingSubscriptions(){return s(this,ye)}onMessage(A){return r(this,null,function*(){switch(A.type){case J.Subscribe:{const t=new iC(A);if(s(this,me).update(e=>(e.set(A.id,t),e)),s(this,ye).isFull()){const e=yield s(this,ye).pop();yield e==null?void 0:e.timeout()}yield s(this,ye).push(new ll(t,s(this,ks),s(this,FI)))}break;case J.SubscribeUpdate:{const t=s(this,me).current().get(A.id);t||s(this,ci).debug("No subscription found",A),t==null||t.onUpdate(A)}break;case J.Unsubscribe:{const t=s(this,me).current().get(A.id);t||s(this,ci).debug("No subscription found",A),t==null||t.onUnsubscribe(A)}break;case J.AnnounceOk:{const t=s(this,Se).current().get(A.namespace.join("/"));t||s(this,ci).debug("No announcement found",A),t==null||t.state.onOk(A)}break;case J.AnnounceError:{const t=s(this,Se).current().get(A.namespace.join("/"));t||s(this,ci).debug("No announcement found",A),t==null||t.state.onError(A)}break}})}}Oo=Hi(null),pI=new WeakMap,ks=new WeakMap,FI=new WeakMap,ci=new WeakMap,Se=new WeakMap,me=new WeakMap,ye=new WeakMap,PA(Oo,1,"announce",mE,XQ),He(Oo,XQ);function ul(i,A){const t=new iC(A),[e,g]=Z(100),B=new wl(t,e),C=new qa(i,t,g);return[B,C]}class wl{constructor(A,t){I(this,"state");n(this,hi);this.state=A,a(this,hi,t)}onDone(A){this.state.onDone(A)}onData(A){return s(this,hi).push(A)}onError(A){const t=this.state.onError(A);s(this,hi).abort(t)}close(){this.state.close(),s(this,hi).close()}}hi=new WeakMap;class qa{constructor(A,t,e){qi(Vo,5,this);n(this,UI);n(this,GI);n(this,GA);n(this,kI);n(this,RI,new G);a(this,GI,A),a(this,GA,t),a(this,kI,e)}get id(){return s(this,GA).subscribe.id}get trackAlias(){return s(this,GA).subscribe.trackAlias}get name(){return s(this,GA).subscribe.name}range(){return s(this,GA).range()}expiryNotification(){return s(this,GA).expiryNotification()}update(A,t){return r(this,null,function*(){const e={type:J.SubscribeUpdate,id:s(this,GA).subscribe.id,start:{group:A,object:q(0)},end:{group:t+q(1),object:q(0)},params:new Map,subscriberPriority:0};s(this,GA).onUpdate(e),yield s(this,GI).push(e)})}unsubscribe(){return r(this,null,function*(){const A={type:J.Unsubscribe,id:s(this,GA).subscribe.id};s(this,GA).onUnsubscribe(A),yield s(this,GI).push(A)})}close(){var A,t;return s(this,RI).resolve(),(t=(A=s(this,kI)).return)==null?void 0:t.call(A)}closed(){return s(this,RI).promise}done(){return s(this,GA).done()}expiryState(){return s(this,GA).expiryState()}unsubscribed(){return s(this,GA).isUnsubscribed()}return(){return r(this,null,function*(){return s(this,RI).resolve(),yield this.unsubscribe(),{done:!0,value:void 0}})}groups(){return Qe(this,null,function*(){var A,t;try{for(var m=EA(s(this,kI)),f,U,b;f=!(U=yield new aA(m.next())).done;f=!1){var Q=U.value;var o=[];try{const Y=Ct(o,Q,!0);try{for(var e=EA(Y.groups()),g,B,C;g=!(B=yield new aA(e.next())).done;g=!1){const N=B.value;const v=(A=s(this,GA).range())==null?void 0:A.startGroup,T=(t=s(this,GA).range())==null?void 0:t.endGroup;if(v&&N.groupId()<v)return{done:!0,value:void 0};if(T&&N.groupId()>T)return{done:!0,value:void 0};yield N}}catch(B){C=[B]}finally{try{g&&(B=e.return)&&(yield new aA(B.call(e)))}finally{if(C)throw C[0]}}}catch(E){var c=E,h=!0}finally{var l=Qt(o,c,h);l&&(yield new aA(l))}}}catch(U){b=[U]}finally{try{f&&(U=m.return)&&(yield new aA(U.call(m)))}finally{if(b)throw b[0]}}})}[Symbol.asyncIterator](){return this.groups()}objects(){return Qe(this,null,function*(){try{for(var B=EA(this.groups()),C,Q,o;C=!(Q=yield new aA(B.next())).done;C=!1){const E=Q.value;try{for(var A=EA(E),t,e,g;t=!(e=yield new aA(A.next())).done;t=!1){const c=e.value;yield c}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield new aA(e.call(A)))}finally{if(g)throw g[0]}}}}catch(Q){o=[Q]}finally{try{C&&(Q=B.return)&&(yield new aA(Q.call(B)))}finally{if(o)throw o[0]}}})}[(yE=[xA({context:"SubscriptionConsumer",enter:"info"})],pt())](){return d(this,UI,wB).call(this)}[Symbol.asyncDispose](){return d(this,UI,wB).call(this)}}Vo=Hi(null),GI=new WeakMap,GA=new WeakMap,kI=new WeakMap,RI=new WeakMap,UI=new WeakSet,wB=function(){return r(this,null,function*(){return yield this.close(),this.unsubscribe()})},wB=PA(Vo,17,"#dispose",yE,UI,wB),He(Vo,qa);const Dl=2e3;GE=[xA({context:"Session",return:"debug"})],FE=[xA({context:"Session",enter:"info",error:"error"})],pE=[xA({context:"Session",enter:"debug"})],fE=[xA({context:"Session",enter:"debug"})];class IC{constructor(A,t){qi(NI,5,this);n(this,Lt);n(this,zt);I(this,"nextSubscribeId",q(0));n(this,XA,new HA(new Map));n(this,di);n(this,li,kA.get().createContext("Subscriber"));a(this,zt,A),a(this,di,t),d(this,Lt,dQ).call(this).catch(y)}subscribe(g,B){return r(this,arguments,function*(A,t,e=new Map){const C=this.nextSubscribeId++,Q=s(this,zt).authToken();Q&&e.set(AC,{type:AC,payload:new TextEncoder().encode(Q)});const o={type:J.Subscribe,namespace:A,name:t.name,id:C,trackAlias:C,groupOrder:t.groupOrder,subscriberPriority:t.priority,filterType:t.filterType,params:e},[E,c]=ul(s(this,di),o);if(s(this,XA).update(l=>l.set(C,E)),yield s(this,di).push(o),!(yield Promise.race([E.state.ok(),s(this,zt).closed()])))throw new Error("Session closed");return c.closed().then(()=>Promise.race([Ye(Dl),this.closed()])).then(()=>d(this,Lt,cg).call(this,c.id)).catch(()=>d(this,Lt,cg).call(this,c.id)),c})}closed(){return s(this,zt).closed()}transportType(){return s(this,zt).transportType()}url(){return s(this,zt).url()}onMessage(A){return r(this,null,function*(){switch(A.type){case J.Announce:yield s(this,di).push({type:J.AnnounceOk,namespace:A.namespace});break;case J.SubscribeOk:{const t=s(this,XA).current().get(A.id);t&&t.state.onOk(A)}break;case J.SubscribeError:{const t=s(this,XA).current().get(A.id);t||s(this,li).debug("No subscription found",A),t==null||t.onError(A),d(this,Lt,cg).call(this,A.id)}break;case J.SubscribeDone:{const t=s(this,XA).current().get(A.id);t||s(this,li).debug("No subscription found",A),t==null||t.onDone(A)}break}})}onObjectReader(A){return r(this,null,function*(){const t=s(this,XA).current().get(A.subscribeId());if(!t){s(this,li).warn("No subscription found",A.subscribeId());return}yield t.onData(A)})}close(){s(this,XA).current().forEach(A=>A.close()),s(this,XA).close()}}NI=Hi(null),zt=new WeakMap,XA=new WeakMap,di=new WeakMap,li=new WeakMap,Lt=new WeakSet,dQ=function(){return r(this,null,function*(){try{for(var A=EA(s(this,XA)),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,li).debug("current subscriptions",C)}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}})},cg=function(A){s(this,XA).isClosed()||s(this,XA).update(t=>(t.delete(A),t))},dQ=PA(NI,17,"#observeChanges",GE,Lt,dQ),PA(NI,1,"subscribe",FE,IC),PA(NI,1,"close",pE,IC),cg=PA(NI,17,"#deleteSubscription",fE,Lt,cg),He(NI,IC);class jQ{constructor(A,t){qi(JI,5,this);n(this,mA);n(this,lt);n(this,Rs);n(this,ui);n(this,bI,kA.get().createContext("Session"));I(this,"subscriber");I(this,"publisher");n(this,LI);const[e,g]=Z(100);a(this,lt,A),a(this,ui,g),this.subscriber=new IC(this,e),this.publisher=new XQ(this,A,e),a(this,Rs,d(this,mA,ar).call(this)),a(this,LI,new HA(t)),this.closed().then(()=>this.close()).catch(y)}updateAuthToken(A){s(this,LI).update(A)}authToken(){return s(this,LI).current()}transportType(){return s(this,lt).transportType()}url(){return s(this,lt).url()}closed(){return s(this,Rs)}close(){try{this.subscriber.close(),this.publisher.close(),s(this,ui).cancel("closing"),s(this,lt).close()}catch(A){s(this,bI).warn("Error closing session",A)}}[(NE=[xA({context:"Session",return:"info",error:"error"})],UE=[xA({context:"Session",return:"info",error:"error"})],RE=[xA({context:"Session",return:"info",error:"error"})],kE=[xA({context:"Session",enter:"debug"})],Dn())](){d(this,mA,DB).call(this)}[Symbol.dispose](){d(this,mA,DB).call(this)}}JI=Hi(null),lt=new WeakMap,Rs=new WeakMap,ui=new WeakMap,bI=new WeakMap,LI=new WeakMap,mA=new WeakSet,nr=function(A){return r(this,null,function*(){var t,e;switch(s(this,bI).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 J.Goaway:break}})},ar=function(){return r(this,null,function*(){return(yield Promise.all([d(this,mA,uQ).call(this),d(this,mA,wQ).call(this),d(this,mA,lQ).call(this)])).find(t=>t instanceof Error)})},lQ=function(){return r(this,null,function*(){try{try{for(var A=EA(s(this,ui)),t,e,g;t=!(e=yield A.next()).done;t=!1){const B=e.value;s(this,bI).debug("sending message",B),yield s(this,lt).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}})},uQ=function(){return r(this,null,function*(){try{for(yield s(this,lt).afterHandshake();;){const A=yield s(this,lt).readMessage().catch(()=>{});if(!A)break;yield d(this,mA,nr).call(this,A)}}catch(A){return A}finally{s(this,ui).cancel("closing")}})},wQ=function(){return r(this,null,function*(){var A;try{for(;;){const t=yield s(this,lt).objectStream();if(!t)break;yield(A=this.subscriber)==null?void 0:A.onObjectReader(t)}}catch(t){return t}})},DB=function(){this.close()},lQ=PA(JI,17,"#runOutgoingMessages",NE,mA,lQ),uQ=PA(JI,17,"#runControl",UE,mA,uQ),wQ=PA(JI,17,"#runObjects",RE,mA,wQ),DB=PA(JI,17,"#dispose",kE,mA,DB),He(JI,jQ);const Sl=128;class ml{constructor(A,t,e){n(this,JA);n(this,it);n(this,Us);n(this,wi,!0);n(this,MI,!1);n(this,Ns);a(this,it,A),a(this,Us,t),a(this,Ns,e)}writeUnsigned8(A){return r(this,null,function*(){return d(this,JA,Ki).call(this),yield d(this,JA,Yi).call(this),s(this,it).writeUnsigned8(A)})}writeVarInt(A){return r(this,null,function*(){return d(this,JA,Ki).call(this),yield d(this,JA,Yi).call(this),s(this,it).writeVarInt(A)})}writeBigVarInt(A){return r(this,null,function*(){return d(this,JA,Ki).call(this),yield d(this,JA,Yi).call(this),s(this,it).writeBigVarInt(A)})}write(A){return r(this,null,function*(){return d(this,JA,Ki).call(this),yield d(this,JA,Yi).call(this),s(this,it).write(A)})}writeString(A){return r(this,null,function*(){return d(this,JA,Ki).call(this),yield d(this,JA,Yi).call(this),s(this,it).writeString(A)})}flush(){return r(this,null,function*(){d(this,JA,Ki).call(this),a(this,wi,!0),yield s(this,it).flush()})}close(){return r(this,null,function*(){s(this,MI)||(a(this,wi,!0),yield d(this,JA,Yi).call(this,!1),yield s(this,it).flush(),a(this,MI,!0),s(this,Ns).call(this))})}}it=new WeakMap,Us=new WeakMap,wi=new WeakMap,MI=new WeakMap,Ns=new WeakMap,JA=new WeakSet,Ki=function(){if(s(this,MI))throw new Error("Stream is closed")},Yi=function(A=!0){if(s(this,wi))return a(this,wi,!1),s(this,it).writeUnsigned8(s(this,Us)|(A?Sl:0))};class yl{constructor(A,t){n(this,NC);n(this,fe);n(this,_t);n(this,HI);n(this,Di);n(this,$t,new Map);n(this,qI,kA.get().createContext("WebSocketConnection"));n(this,vI,new Set(new Array(128).fill(0).map((A,t)=>t+1)));a(this,fe,A),a(this,_t,t),a(this,HI,new ReadableStream(new Md(A))),s(this,fe).addEventListener("close",()=>{s(this,_t).markPostHandshake(),s(this,$t).forEach(e=>e.close())})}openSendStream(){const A=s(this,vI).values().next().value;if(!A)throw new Error("No stream IDs available");return s(this,vI).delete(A),Promise.resolve(new ml(new mg(s(this,fe)),A,()=>d(this,NC,Er).call(this,A)))}transportType(){return"websocket"}url(){return s(this,fe).url}afterHandshake(){return s(this,_t).postHandshake()}objectStream(){return r(this,null,function*(){var A;for(;;){a(this,Di,s(this,HI).getReader());try{const{value:t,done:e}=yield s(this,Di).read();if(e)return;const[g,B,C]=t;if(s(this,$t).has(q(B))){const Q=s(this,$t).get(q(B));if(!Q)throw new Error("Stream not found");C.length>0&&(yield Q.push(C)),g||(s(this,qI).debug("Closing stream",{streamId:B}),Q.close(),s(this,$t).delete(q(B)))}else{let c;s(this,qI).debug("Creating new stream",{streamId:B});const[Q,o]=Z(1e3),E=new ReadableStream({pull(h){return r(this,null,function*(){const l=yield o.pop();l?h.enqueue(l):h.close()})}});if(s(this,$t).set(q(B),Q),g||(s(this,qI).debug("Closing new stream",{streamId:B}),yield E.cancel(),s(this,$t).delete(q(B))),C.length>0)return yield ua(new zB(C,E),B)}}finally{(A=s(this,Di))==null||A.releaseLock()}}})}close(){var A;return s(this,_t).cancel().catch(y),s(this,HI).cancel("closing").catch(y),(A=s(this,Di))==null||A.cancel("closing").catch(y),s(this,fe).close()}closed(){return Promise.resolve()}writeMessage(A){return r(this,null,function*(){yield s(this,_t).write(A)})}readMessage(){return r(this,null,function*(){return s(this,_t).read()})}}fe=new WeakMap,_t=new WeakMap,HI=new WeakMap,Di=new WeakMap,$t=new WeakMap,qI=new WeakMap,vI=new WeakMap,NC=new WeakSet,Er=function(A){s(this,vI).add(A)};class fl{constructor(A,t,e){n(this,LC);n(this,Ae);n(this,te);n(this,pe,new z(100));n(this,bs);n(this,Ls,0);n(this,bC,kA.get().createContext("WebTransportConnection"));a(this,bs,e),a(this,Ae,A),a(this,te,t),d(this,LC,rr).call(this).catch(g=>{s(this,bC).debug("Incoming streams handling ended with error",g),s(this,te).markPostHandshake(),s(this,pe).close()}),s(this,Ae).closed.then(()=>{s(this,te).markPostHandshake(),s(this,pe).close()})}openSendStream(){return r(this,null,function*(){const A=yield s(this,Ae).createUnidirectionalStream();return new wa(A)})}transportType(){return"webtransport"}url(){return s(this,bs)}afterHandshake(){return s(this,te).postHandshake()}closed(){return r(this,null,function*(){yield s(this,Ae).closed})}close(){s(this,Ae).close()}writeMessage(A){return r(this,null,function*(){yield s(this,te).write(A)})}readMessage(){return r(this,null,function*(){return s(this,te).read()})}objectStream(){return r(this,null,function*(){return s(this,pe).pop()})}}Ae=new WeakMap,te=new WeakMap,pe=new WeakMap,bs=new WeakMap,Ls=new WeakMap,bC=new WeakMap,LC=new WeakSet,rr=function(){return r(this,null,function*(){const A=s(this,Ae).incomingUnidirectionalStreams.getReader();for(;;){const{value:t,done:e}=yield A.read();if(e){s(this,pe).close();return}const g=new zB(new Uint8Array,t);yield s(this,pe).push(ua(g,s(this,Ls))),ft(this,Ls)._++}})};function zQ(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=eC.wrapWebsocket(A);Ha(t,i.role).catch(()=>{A.close()});const e=new yl(A,t);return new jQ(e,i.authToken)})}function pl(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=eC.wrapWebTransport(g);Ha(B,i.role).catch(()=>{e.close()});const C=new fl(e,B,i.url.toString());return new jQ(C,i.authToken)})}function Fl(i){return r(this,null,function*(){if(self.WebTransport&&(i==null?void 0:i.preferredTransport)!=="websocket"&&i.url.protocol.startsWith("https")){const A=pl(i).catch(()=>zQ(i)),t=yield Promise.race([A,Ye(i.websocketFallbackTimeoutMs)]);return t||zQ(i)}return zQ(i)})}class xt{constructor(){n(this,ee,{name:"",priority:0,groupOrder:"ascending",filterType:{type:"latest-group"}})}name(A){return s(this,ee).name=A,this}priority(A){return s(this,ee).priority=A,this}groupOrder(A){return s(this,ee).groupOrder=A,this}startGroup(A){return s(this,ee).filterType={type:"absolute-start",start:{group:A,object:q(0)}},this}range(A,t){return s(this,ee).filterType={type:"absolute-range",start:{group:A,object:q(0)},end:{group:t,object:q(0)}},this}build(){return s(this,ee)}}ee=new WeakMap;class va{constructor(A,t){n(this,KI);n(this,Js);a(this,KI,A),a(this,Js,t)}subscribe(A,t=new Map){return s(this,KI).subscribe(this.namespace(),A,t)}closed(){return s(this,KI).closed()}namespace(){return s(this,Js).namespace}}KI=new WeakMap,Js=new WeakMap;function Gl(i,A){return["com.vindral.moq",i]}function Oe(i){const A=i[1];if(!A)throw new Error("namespace must contain a channel ID");return A}function kl(i){return"tracks"in i}function Rl(i){const A=new TextDecoder().decode(i);return JSON.parse(A)}const Zo=class Zo{constructor(A,t){n(this,Hs);n(this,jA);n(this,Jt);n(this,Si,new L(100));n(this,It);n(this,Ms);n(this,JC,A=>r(this,null,function*(){if(!A)return s(this,jA).close();if(s(this,It))return;const t=s(this,Si).items().reduce((e,g)=>e<g?e:g,A);a(this,It,d(this,Hs,En).call(this,t,A)),s(this,It).size===0&&(yield s(this,jA).close())}));a(this,jA,A),a(this,Jt,t),A.done().then(e=>r(this,null,function*(){var g;return s(this,JC).call(this,(g=e.finalInfo)==null?void 0:g.group)})).catch(y),a(this,Ms,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,jA).id}name(){return s(this,jA).name}largestGroupId(){return s(this,Jt)}needsRenewal(){return s(this,jA).expiryState()==="active"&&s(this,It)===void 0}endOfTrack(A){const t=s(this,Si).items().reduce((e,g)=>e<g?e:g,A);return this.update(t,A)}update(A,t){return r(this,null,function*(){return a(this,It,d(this,Hs,En).call(this,A,t)),s(this,It).size===0&&(yield s(this,jA).close()),s(this,jA).update(A,t)})}unsubscribe(){return s(this,jA).unsubscribe()}next(){return r(this,null,function*(){var e;if(s(this,It)&&s(this,It).size===0)return{done:!0,value:void 0};const A=yield s(this,Ms).next();if(A.done)return A;const t=A.value.groupId();return(e=s(this,It))==null||e.delete(t),s(this,Si).push(t),s(this,Jt)||a(this,Jt,t),a(this,Jt,s(this,Jt)<t?t:s(this,Jt)),A})}return(){return s(this,jA).return()}[Symbol.asyncIterator](){return this}};jA=new WeakMap,Jt=new WeakMap,Si=new WeakMap,It=new WeakMap,Ms=new WeakMap,JC=new WeakMap,Hs=new WeakSet,En=function(A,t){const e=new Set;for(let g=A;g<=t;g++)e==null||e.add(g);return s(this,Si).items().forEach(g=>{e==null||e.delete(g)}),e};let gC=Zo;const Xo=class Xo{constructor(A){n(this,qs);n(this,ut);n(this,mi);n(this,ie,new z(10));n(this,Mt);n(this,vs,(A,t)=>r(this,null,function*(){var h=[];try{const e=Ct(h,yield s(this,ut).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 xt().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+q(1));break}const o=Q.build();g.newTrack=o;const[E]=yield Promise.all([A.subscribe(o),C?e.value.update(B,B):e.value.unsubscribe()]);E.done().then(()=>d(this,qs,rn).call(this,E)).catch(y);E.expiryNotification().then(()=>s(this,vs).call(this,A,o)).catch(y);const c=new gC(E,B);e.value=c;yield s(this,ie).push(c);s(this,Mt).info("Subscription renewed",g)}catch(l){var m=l,f=!0}finally{Qt(h,m,f)}}));a(this,ut,new Or(A)),a(this,mi,A),a(this,Mt,kA.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 gC(C,B));return C.done().then(()=>{var o;return d(o=Q,qs,rn).call(o,C)}).catch(y),C.expiryNotification().then(()=>{var o;return s(o=Q,vs).call(o,A,t)}).catch(y),Q})}largestGroupId(){return s(this,ut).unsafeValue().largestGroupId()}update(A,t){return r(this,null,function*(){var g=[];try{const e=Ct(g,yield s(this,ut).lock());s(this,ie).close();return e.value.update(A,t)}catch(B){var C=B,Q=!0}finally{Qt(g,C,Q)}})}endOfTrack(A){return r(this,null,function*(){var e=[];try{const t=Ct(e,yield s(this,ut).lock());s(this,ie).close();return t.value.endOfTrack(A)}catch(g){var B=g,C=!0}finally{Qt(e,B,C)}})}unsubscribe(){return r(this,null,function*(){var t=[];try{const A=Ct(t,yield s(this,ut).lock());s(this,ie).close();return A.value.unsubscribe()}catch(e){var g=e,B=!0}finally{Qt(t,g,B)}})}return(){return r(this,null,function*(){var t=[];try{const A=Ct(t,yield s(this,ut).lock());s(this,ie).close();return A.value.return()}catch(e){var g=e,B=!0}finally{Qt(t,g,B)}})}next(){return r(this,null,function*(){var t,e;const A=yield s(this,mi).next();if(A.done){yield(e=(t=s(this,mi)).return)==null?void 0:e.call(t);const g=yield s(this,ie).pop();if(g)return a(this,mi,g),this.next()}return A})}[Symbol.asyncIterator](){return this}objects(){return Qe(this,null,function*(){try{for(var Q=EA(this),o,E,c;o=!(E=yield new aA(Q.next())).done;o=!1){var A=E.value;var t=[];try{const h=Ct(t,A,!0);yield*Cn(h)}catch(e){var g=e,B=!0}finally{var C=Qt(t,g,B);C&&(yield new aA(C))}}}catch(E){c=[E]}finally{try{o&&(E=Q.return)&&(yield new aA(E.call(Q)))}finally{if(c)throw c[0]}}})}};ut=new WeakMap,mi=new WeakMap,ie=new WeakMap,Mt=new WeakMap,qs=new WeakSet,rn=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,ut).unsafeValue().subscribeId()!==A.id){s(this,Mt).info("subscribeId mismatch - the subscription already has been renewed");return}return this.return()})},vs=new WeakMap;let ae=Xo;const Ul="catalog";function Ka(i){const A=Rl(i.payload);if(!kl(A))throw new Error("unexpected catalog type");return A}const HC=class HC{constructor(A,t,e){n(this,MC);n(this,Fe);n(this,Ks);n(this,Ys);n(this,Ts);a(this,Ks,A),a(this,Fe,t),a(this,Ys,e),a(this,Ts,d(this,MC,cr).call(this)),this.closed().finally(()=>s(this,Fe).close()).catch(y)}catalog(){return s(this,Fe)}closed(){return s(this,Ts)}close(){return r(this,null,function*(){return s(this,Fe).close(),(yield s(this,Ks).promise).unsubscribe()})}static start(A,t){return r(this,null,function*(){const e=G.fromPromise(ae.subscribe(A,new xt().name(t.catalogName||Ul).groupOrder("ascending").build())),g=G.fromPromise(e.promise.then(o=>o.objects()));if(t.catalog)return new HC(e,new HA(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 HC(e,new HA(Q),g)})}};Fe=new WeakMap,Ks=new WeakMap,Ys=new WeakMap,Ts=new WeakMap,MC=new WeakSet,cr=function(){return r(this,null,function*(){const A=yield s(this,Ys).promise;try{for(var t=EA(A),e,g,B;e=!(g=yield t.next()).done;e=!1){const C=g.value;if(C.objectStatus!==qA.Normal)continue;const Q=Ka(C);s(this,Fe).update(Q)}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield g.call(t))}finally{if(B)throw B[0]}}})};let _Q=HC;class Nl{constructor(A,t,e,g){n(this,Ws);n(this,Ps);n(this,YI);n(this,xs);I(this,"track");n(this,TI,kA.get().createContext("CmafGroup"));this.track=g,a(this,Ps,e),a(this,YI,A),a(this,xs,t)}[Symbol.asyncIterator](){return Qe(this,null,function*(){const A={name:this.track.trackObject.name,namespace:this.track.namespace};s(this,TI).debug("start",S({},A));try{for(var t=EA(s(this,YI)),e,g,B;e=!(g=yield new aA(t.next())).done;e=!1){const C=g.value;if(C.objectStatus===qA.EndOfTrackAndGroup&&(yield new aA(this.track.endOfTrack(C.groupId))),C.objectStatus!==qA.Normal)continue;const Q=s(this,xs).createFragment(C.payload),o=Q.timescale(),E=Q.baseMediaDecodeTime()/o*1e3,c=Q.duration()/o*1e3,h=E+c,l=s(this,Ps)/1e3*o;Q.updateBaseMediaDecodeTime(Q.baseMediaDecodeTime()-l);const m=this.track.timestampRange();if(m&&E>=m[1])break;s(this,TI).debug("fragment",V(S({},A),{startTime:E,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 aA(g.call(t)))}finally{if(B)throw B[0]}}s(this,TI).debug("end",S({},A))})}[pt()](){return d(this,Ws,cn).call(this)}[Symbol.asyncDispose](){return d(this,Ws,cn).call(this)}}Ps=new WeakMap,YI=new WeakMap,xs=new WeakMap,TI=new WeakMap,Ws=new WeakSet,cn=function(){return r(this,null,function*(){var A,t;return yield(t=(A=s(this,YI)).return)==null?void 0:t.call(A),Promise.resolve()})};const PI=class PI{constructor(A,t,e,g,B){n(this,Os);n(this,Ht);n(this,Vs);n(this,Zs);I(this,"trackObject");I(this,"namespace");this.trackObject=A,this.namespace=t,a(this,Ht,e),a(this,Os,g),a(this,Vs,B)}static subscribe(C,Q,o){return r(this,arguments,function*(A,t,{timestampOffsetMs:e,startGroup:g,params:B}){var f;if(t.format!=="cmaf")throw new Error("format must be cmaf");const E=new xt().name(t.name);g&&E.startGroup(g);const c=E.build();if(t.initTrack){const U=new xt().name(t.initTrack).build(),[b,Y]=yield Promise.all([d(f=PI,qC,hr).call(f,A,U),ae.subscribe(A,c,{params:B,largestGroupId:g?g-q(1):void 0})]),N=new Ba(b);return new PI(t,A.namespace(),Y,N,e)}k(t.initData,"no init data found on track");const h=QA(t.initData),l=new Ba(new Uint8Array(h)),m=yield ae.subscribe(A,c,{params:B,largestGroupId:g?g-q(1):void 0});return new PI(t,A.namespace(),m,l,e)})}largestGroupId(){return s(this,Ht).largestGroupId()}stopAfterTimestampReached(A){a(this,Zs,[0,A])}timestampRange(){return s(this,Zs)}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 Nl(A.value,s(this,Os),s(this,Vs),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()})}};Os=new WeakMap,Ht=new WeakMap,Vs=new WeakMap,Zs=new WeakMap,qC=new WeakSet,hr=function(A,t){return r(this,null,function*(){var B=[];try{const e=Ct(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 E=Qt(B,Q,o);E&&(yield E)}})},n(PI,qC);let $Q=PI;const Ya=1e4,bl=3e4,jo=class jo{constructor(A,t,e){n(this,fi);n(this,vC,kA.get().createContext("Timeline"));n(this,Ge,new HA([]));n(this,yi);n(this,Xs);n(this,js);n(this,zs);a(this,Xs,A),a(this,js,e),a(this,yi,t),a(this,zs,d(this,fi,hn).call(this,s(this,yi))),this.closed().finally(()=>s(this,Ge).close()).catch(y)}closed(){return s(this,zs)}close(){return r(this,null,function*(){return(yield s(this,yi).promise).unsubscribe()})}timeline(){const[A,t]=s(this,Ge).value();return A}timestampWallclockOffset(){return Wi(this.timeline().map(A=>A.mediaPts-A.wallclock))}static start(A,t){const e=G.fromPromise(ae.subscribe(A,new xt().name(t).groupOrder("ascending").build()));return new jo(A,e,t)}waitForWallclockTime(A){return r(this,null,function*(){return yield s(this,Ge).waitFor(t=>!!t.find(e=>e.wallclock>=A)),this.timeline()})}waitForTimelineToHaveMinDuration(){return r(this,null,function*(){return yield s(this,Ge).waitFor(A=>{const t=A[0],e=A[A.length-1];return!t||!e?!1:e.wallclock-t.wallclock>Ya}),this.timeline()})}};vC=new WeakMap,Ge=new WeakMap,yi=new WeakMap,Xs=new WeakMap,js=new WeakMap,zs=new WeakMap,fi=new WeakSet,hn=function(A){return r(this,null,function*(){const t=yield A.promise;try{for(var m=EA(t),f,U,b;f=!(U=yield m.next()).done;f=!1){var Q=U.value;var o=[];try{const Y=Ct(o,Q,!0);try{for(var e=EA(Y),g,B,C;g=!(B=yield e.next()).done;g=!1){const N=B.value;if(N.objectStatus!==qA.Normal)continue;const v=Ll(N.payload);s(this,Ge).update(T=>{var P,X;for(T.push(...v),T.sort((yA,BA)=>yA.wallclock-BA.wallclock);T[0]&&((X=(P=T[T.length-1])==null?void 0:P.wallclock)!=null?X:0)-T[0].wallclock>bl;)T.shift();return T}),t===s(this,yi).resolved&&N.groupId>q(0)&&N.objectId==q(0)&&d(this,fi,dr).call(this,N.groupId).catch(T=>{s(this,vC).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(E){var c=E,h=!0}finally{var l=Qt(o,c,h);l&&(yield l)}}}catch(U){b=[U]}finally{try{f&&(U=m.return)&&(yield U.call(m))}finally{if(b)throw b[0]}}})},dr=function(A){return r(this,null,function*(){const t=A-q(1),e=this.timeline(),g=e[0],B=e[e.length-1];if(!g||!B||B.wallclock-g.wallclock>Ya)return;const C=G.fromPromise(ae.subscribe(s(this,Xs),new xt().name(s(this,js)).groupOrder("ascending").range(t,t).build()));return d(this,fi,hn).call(this,C)})};let Ao=jo;function Ll(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 Jl(i){return typeof i.language=="string"}const zo=class zo{constructor(A,t,e,g,B){n(this,KC,new ha);n(this,_s);n(this,ke);n(this,xI,0);I(this,"trackObject");I(this,"namespace");a(this,ke,A),a(this,_s,t),this.trackObject=e,this.namespace=g,a(this,xI,B)}static subscribe(A,t,e){return r(this,null,function*(){if(!Jl(t))throw new Error("track object language is required");const g=new xt().name(t.name).build(),B=yield ae.subscribe(A,g),C=B.objects();return new zo(B,C,t,A.namespace(),e)})}largestGroupId(){return s(this,ke).largestGroupId()}update(A,t){return s(this,ke).update(A,t)}unsubscribe(){return s(this,ke).unsubscribe()}next(){return r(this,null,function*(){for(;;){const A=yield s(this,_s).next();if(A.done)return A;if(A.value.objectStatus!==qA.Normal)continue;const t=new TextDecoder().decode(A.value.payload),e=s(this,KC).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,ke).return(),{done:!0,value:void 0}})}[Symbol.asyncIterator](){return this}[pt()](){return this.unsubscribe()}[Symbol.asyncDispose](){return this.unsubscribe()}};KC=new WeakMap,_s=new WeakMap,ke=new WeakMap,xI=new WeakMap;let to=zo;bE=[xA({context:"Channel",enter:"info"})];const OI=class OI{constructor(A,t,e,g,B){n(this,WI);I(this,"namespace");n(this,pi);n(this,Fi);n(this,Gi);n(this,Re);this.namespace=g,a(this,pi,A),a(this,Fi,t),a(this,Gi,e),a(this,Re,B)}static start(A,t){return r(this,null,function*(){const e=new va(A,{namespace:t.namespace}),[g,B]=yield Promise.all([Ao.start(e,"timeline"),_Q.start(e,{catalog:t.catalog,namespace:t.namespace})]);return new OI(e,g,B,t.namespace,0)})}closed(){return s(this,Gi).closed()}catalog(){return s(this,Gi).catalog()}timestampWallclockOffset(){return s(this,Fi).timestampWallclockOffset()}timestampOffsetMs(){return s(this,Re)}setTimestampOffsetMs(A){a(this,Re,A)}waitForWallclockTime(A){return s(this,Fi).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,WI,DQ).call(this,()=>$Q.subscribe(s(this,pi),C!=null?C:A,{timestampOffsetMs:s(this,Re),startGroup:e,params:g}))}subscribeWebVttTrack(A){return d(this,WI,DQ).call(this,()=>to.subscribe(s(this,pi),A,s(this,Re)))}subscribeTrack(A){return d(this,WI,DQ).call(this,()=>s(this,pi).subscribe(A))}close(){return Promise.all([s(this,Gi).close(),s(this,Fi).close()])}};_o=Hi(null),pi=new WeakMap,Fi=new WeakMap,Gi=new WeakMap,Re=new WeakMap,WI=new WeakSet,DQ=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,Ye(500)])),t!==this.catalog().current())return A();throw g}})},PA(_o,9,"start",bE,OI),He(_o,OI),qi(_o,3,OI);let sC=OI;const $o=class $o{constructor(A){n(this,YC);n(this,ki);n(this,$s);const[t,e]=A.value.value();a(this,ki,{createdAt:new Date,wallclock:new Date(t.ntpTimestamp),rtt:t.rtt}),a(this,$s,d(this,YC,lr).call(this,A))}wallclock(){const t=Date.now()-s(this,ki).createdAt.getTime();return s(this,ki).wallclock.getTime()+t}closed(){return s(this,$s)}static start(A){return new $o(A)}};ki=new WeakMap,$s=new WeakMap,YC=new WeakSet,lr=function(A){return r(this,null,function*(){try{for(var t=EA(A.value),e,g,B;e=!(g=yield t.next()).done;e=!1){const C=g.value;a(this,ki,{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 eo=$o;function BC(i){return typeof i=="string"||i===null||i===void 0}function Ml(i){return"provider"in i&&typeof i.provider=="string"&&(!("widevineLicenseUrl"in i)||BC(i.widevineLicenseUrl))&&(!("playreadyLicenseUrl"in i)||BC(i.playreadyLicenseUrl))&&(!("fairplayLicenseUrl"in i)||BC(i.fairplayLicenseUrl))&&(!("fairplayCertificate"in i)||BC(i.fairplayCertificate))}function Hl(i){try{return QA(i)}catch(A){throw new Error("Failed to convert fairplayCertificate")}}function ql(i){const A=new TextDecoder().decode(i),t=JSON.parse(A);if(!Ml(t))throw new Error("Invalid drm object");const B=t,{fairplayCertificate:e}=B,g=YE(B,["fairplayCertificate"]);return V(S({},g),{fairplayCertificate:e?Hl(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=Ct(o,yield A.subscribeTrack(new xt().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=ql(C.value.payload);return new io(V(S({},Q),{videoCodec:t,audioCodec:e}))}catch(E){var c=E,h=!0}finally{var l=Qt(o,c,h);l&&(yield l)}})}}function vl(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(!vl(t))throw new Error("Invalid stats object");return t}const Kl=1e4,An=class An{constructor(A,t,e){n(this,TC);I(this,"ip");I(this,"value");n(this,AB);this.ip=e,this.value=new HA(t),a(this,AB,d(this,TC,ur).call(this,A))}closed(){return s(this,AB)}idleTimeout(){return r(this,null,function*(){for(;;){const[A,t]=this.value.value();try{yield Promise.race([kQ(Kl,new Error("Idle timeout")),t])}catch(e){return e}}})}static start(A){return r(this,null,function*(){const e=(yield A.subscribe(new xt().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)})}};AB=new WeakMap,TC=new WeakSet,ur=function(A){return r(this,null,function*(){try{for(var t=EA(A),e,g,B;e=!(g=yield t.next()).done;e=!1){const C=g.value;if(C.objectStatus!==qA.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 Io=An;class Yl{constructor(A){n(this,PC,kA.get().createContext("UpstreamWatcher"));n(this,VI);a(this,VI,new HA(G.fromPromise(A.closed())))}update(A){s(this,VI).update(G.fromPromise(A.closed()))}closed(){return r(this,null,function*(){try{for(;;){const[A,t]=s(this,VI).value();let e=!1;yield Promise.race([t==null?void 0:t.then(()=>e=!0),A.promise.then(()=>{if(!e)throw s(this,PC).warn("Upstream closed"),new Error("Upstream closed")})])}}catch(A){return A}})}}PC=new WeakMap,VI=new WeakMap;const Tl=q(8);function Pl(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:Tl,payload:A}}class go{constructor(A,t){n(this,ZI,kA.get().createContext("TracksIterator"));n(this,tB);n(this,eB);a(this,tB,A),a(this,eB,t)}[Symbol.asyncIterator](){return Qe(this,null,function*(){const A=s(this,eB);try{for(var t=EA(s(this,tB)),e,g,B;e=!(g=yield new aA(t.next())).done;e=!1){const C=g.value;if(!C)continue;const Q={name:C.trackObject.name,namespace:C.namespace};s(this,ZI).debug("track start",S({mediaType:A},Q)),yield*Cn(C),s(this,ZI).debug("track end",S({mediaType:A},Q))}}catch(g){B=[g]}finally{try{e&&(g=t.return)&&(yield new aA(g.call(t)))}finally{if(B)throw B[0]}}s(this,ZI).debug("tracks ended",{mediaType:A})})}}ZI=new WeakMap,tB=new WeakMap,eB=new WeakMap;let xl=(ME=[xA({context:"Player",enter:"info"})],JE=[xA({context:"Player",enter:"info",return:"info"})],LE=[xA({context:"Player",enter:"info"})],Ie=class{constructor(A,t,e){qi(IB,5,this);n(this,KA);n(this,XI);n(this,jI);n(this,Ri);n(this,UA);n(this,wt,new HA(void 0));n(this,Dt,new HA(void 0));n(this,Ue,new HA(void 0));n(this,zI);n(this,iB);I(this,"subtitles",new go(s(this,Ue),"subtitles"));I(this,"video",new go(s(this,Dt),"video"));I(this,"audio",new go(s(this,wt),"audio"));a(this,XI,A),a(this,jI,eo.start(e)),a(this,Ri,e),a(this,UA,new HA(t)),a(this,zI,new Yl(t)),a(this,iB,Promise.race([e.idleTimeout(),d(this,KA,wr).call(this),s(this,zI).closed()])),s(this,XI).closed().then(()=>this.close()).catch(y)}closed(){return s(this,iB)}static start(A,t){return r(this,null,function*(){const e=new Map;if(t.burstMs!==void 0){const c=Pl(t.burstMs);e.set(c.type,c)}const g=new va(A,{namespace:Gl("auxiliary")}),[[B,C,Q],o]=yield Promise.all([sC.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])),Io.start(g)]),E=new Ie(A,B,o);return Q&&s(E,wt).update(Q),C&&s(E,Dt).update(C),E})}connectionInfo(){const A=s(this,Ri).value.current();return{ip:s(this,Ri).ip,rtt:A.rtt,estimatedBandwidth:A.estimatedBandwidth}}stats(){return s(this,Ri).value}catalog(){return s(this,UA).current().catalog()}namespace(){return s(this,UA).current().namespace}videoTrack(){var A;return(A=s(this,Dt).current())==null?void 0:A.trackObject}audioTrack(){var A;return(A=s(this,wt).current())==null?void 0:A.trackObject}referenceClock(){return s(this,jI)}drm(){return r(this,null,function*(){var t,e;if(this.catalog().current().tracks.find(({name:g})=>g==="drm"))return io.create(s(this,UA).current(),(t=this.videoTrack())==null?void 0:t.codec,(e=this.audioTrack())==null?void 0:e.codec)})}close(){return Promise.all([s(this,UA).current().close(),s(this,UA).close(),d(this,KA,SQ).call(this,s(this,wt)),d(this,KA,SQ).call(this,s(this,Dt)),d(this,KA,SQ).call(this,s(this,Ue))])}zap(A,t){return r(this,null,function*(){var f,U;const e=yield sC.start(s(this,XI),A),g=s(this,jI).wallclock()-t,B=s(this,UA).current(),C=B.timestampWallclockOffset(),Q=yield e.waitForWallclockTime(g);s(this,zI).update(e),yield s(this,UA).current().close();const o=Q.toReversed().find(b=>b.wallclock<=g),E=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?q(o.groupId):void 0;E&&((f=s(this,Dt).current())==null||f.stopAfterTimestampReached(E),(U=s(this,wt).current())==null||U.stopAfterTimestampReached(E)),s(this,UA).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,Ue).current())==null?void 0:e.unsubscribe();return}const[t]=yield Promise.all([s(this,UA).current().subscribeWebVttTrack(A),(g=s(this,Ue).current())==null?void 0:g.unsubscribe()]);s(this,Ue).update(t)})}setVideoTrack(A,t){return r(this,null,function*(){const e=yield d(this,KA,SB).call(this,s(this,UA).current(),A,s(this,Dt).current(),t);s(this,Dt).update(e)})}setAudioTrack(A,t){return r(this,null,function*(){const e=yield d(this,KA,SB).call(this,s(this,UA).current(),A,s(this,wt).current(),t);s(this,wt).update(e)})}},IB=Hi(null),XI=new WeakMap,jI=new WeakMap,Ri=new WeakMap,UA=new WeakMap,wt=new WeakMap,Dt=new WeakMap,Ue=new WeakMap,zI=new WeakMap,iB=new WeakMap,KA=new WeakSet,SQ=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()},SB=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+q(1):void 0)}),B?e==null?void 0:e.update(B,B):e==null?void 0:e.unsubscribe()]);return C})},wr=function(){return r(this,null,function*(){try{for(var B=EA(s(this,UA)),C,Q,o;C=!(Q=yield B.next()).done;C=!1){const E=Q.value;try{for(var A=EA(E.catalog()),t,e,g;t=!(e=yield A.next()).done;t=!1){const c=e.value;yield Promise.all([d(this,KA,dn).call(this,c,s(this,Dt)),d(this,KA,dn).call(this,c,s(this,wt))])}}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]}}})},dn=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,UA).current().subscribeCmafTrack(Q))}})},PA(IB,1,"close",ME,Ie),PA(IB,1,"zap",JE,Ie),SB=PA(IB,17,"#replaceTrack",LE,KA,SB),He(IB,Ie),Ie);function so(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 Wl=1e4,tn=class tn{constructor(A,t,e,g,B,C){n(this,TA);n(this,NA);n(this,YA);n(this,St);n(this,Ui,"disconnected");n(this,nA);n(this,Ne,new Map);n(this,gB);n(this,sB,new L(10));n(this,xC,Number.MAX_SAFE_INTEGER);n(this,_I,new Map);n(this,$I,A=>{if(!A){s(this,nA).setSubtitleTrack(void 0).catch(y);return}const t=s(this,Ne).get(Oe(s(this,nA).namespace())),e=t==null?void 0:t.getTextTrack(A);e&&s(this,nA).setSubtitleTrack(e).catch(y)});n(this,BB,A=>{switch(A.type){case"subscribe":{if(s(this,Ag)){s(this,YA).info("Ignoring - we are already switching");return}a(this,Ag,!0),d(this,TA,mr).call(this,A.subscription).catch(t=>{s(this,YA).error("error handling subscription",t),s(this,NA).emit("received signal",{type:"subscription changed",subscription:A.subscription,reset:!0})}).finally(()=>a(this,Ag,!1))}break;case"telemetry":Un(new URL("/api/telemetry",s(this,St).url().replace("wss://","https://")),{body:A.body,headers:{"Content-Type":"text/plain"}}).catch(y);break;case"refresh auth":s(this,St).updateAuthToken(A.token);break}});n(this,Ag,!1);I(this,"disconnect",(A="Disconnect Requested")=>{s(this,YA).info("Disconnecting",A),s(this,St).close(),s(this,nA).close().catch(y),a(this,_I,new Map),a(this,Ui,"disconnected")});a(this,NA,A),a(this,YA,t),a(this,St,e),a(this,nA,g),a(this,Ne,B),a(this,gB,C),s(this,NA).on("send signal",s(this,BB)),s(this,NA).on("disconnect",this.disconnect),s(this,NA).on("text track",s(this,$I)),d(this,TA,Dr).call(this).catch(y),d(this,TA,yr).call(this).catch(y)}get estimatedBandwidth(){return s(this,xC)}unload(){s(this,NA).off("send signal",s(this,BB)),s(this,NA).off("disconnect",this.disconnect),s(this,NA).off("text track",s(this,$I)),this.disconnect()}suspend(){}unsuspend(){}getStatistics(){const t=s(this,nA).connectionInfo().estimatedBandwidth;return{rtt:oe(s(this,sB).items()),estimatedBandwidth:t,connectCount:0,connectionAttemptCount:0,edgeUrl:s(this,St).url(),connectionProtocol:"moq"}}static start(A,t,e,g){return r(this,null,function*(){var Y,N,v,T;const B=new Map(g.connectInfo.channels.map(P=>[Oe(P.catalog.namespace),new Co(new HA(P.catalog))])),C=yield g.onConnectInfo(g.connectInfo),Q=g.options.get("authenticationToken");let o,E;switch(typeof g.edgeUrl){case"string":{o=so(g.edgeUrl,C,Q);break}default:o=so(g.edgeUrl.moqUrl||g.edgeUrl.moqWsUrl,C,Q),E=so(g.edgeUrl.moqWsUrl,C,Q);break}const c=(Y=g.connectInfo.channels.find(P=>P.channelId===C.channelId))==null?void 0:Y.catalog;t.debug("Resolved edge url",{edgeUrl:o,edgeWsUrl:E}),k(c,"no catalog found");const h=(N=B.get(Oe(c.namespace)))==null?void 0:N.getVideoTrack(C.video),l=(v=B.get(Oe(c.namespace)))==null?void 0:v.getAudioTrack(C.audio),m=yield Fl({url:o,wsUrl:E,authToken:g.options.get("authenticationToken"),preferredTransport:g.options.get("webtransportEnabled")?"webtransport":"websocket",role:Pd.Subscriber,websocketFallbackTimeoutMs:2e3}),f=yield Promise.race([xl.start(m.subscriber,{namespace:c.namespace,catalog:c,videoTrack:h==null?void 0:h.track,audioTrack:l==null?void 0:l.track,burstMs:C.burstMs||0}),kQ(Wl,new Error("Timeout waiting for player to start")),Vr(m.closed(),"Session closed before player started")]),U=new Co(f.catalog());B.set(Oe(c.namespace),U),A.emit("received signal",{type:"client ip",ip:f.connectionInfo().ip}),f.drm().then(P=>{P&&A.emit("received drm data",P.value)}).catch(P=>{t.error("Error getting DRM data",P)});const b=new tn(A,t,m,f,B,e);return C.textTrack&&s(T=b,$I).call(T,C.textTrack),b})}getState(){return s(this,Ui)}get rtt(){return s(this,nA).connectionInfo().rtt}close(){s(this,St).close()}closed(){return Promise.race([s(this,St).closed(),s(this,nA).closed()])}};NA=new WeakMap,YA=new WeakMap,St=new WeakMap,Ui=new WeakMap,nA=new WeakMap,Ne=new WeakMap,gB=new WeakMap,sB=new WeakMap,xC=new WeakMap,_I=new WeakMap,TA=new WeakSet,Dr=function(){return r(this,null,function*(){try{for(var A=EA(s(this,nA).stats()),t,e,g;t=!(e=yield A.next()).done;t=!1){const{rtt:B}=e.value;s(this,sB).push(B)}}catch(e){g=[e]}finally{try{t&&(e=A.return)&&(yield e.call(A))}finally{if(g)throw g[0]}}})},$I=new WeakMap,BB=new WeakMap,Ag=new WeakMap,Sr=function(A){return r(this,null,function*(){var g;const t=yield s(this,gB).connect({channelId:A});if(!Fn(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})},mr=function(A){return r(this,null,function*(){var C,Q,o;s(this,YA).info("handle subscription",A);const t=s(this,nA);let e=s(this,Ne).get(A.channelId);if(e||(e=new Co(new HA(yield d(this,TA,Sr).call(this,A.channelId))),s(this,Ne).set(A.channelId,e)),t.namespace().join("/")!==e.namespace().join("/")){s(this,YA).info("changing channel",A.channelId);const E=e.getVideoTrack(A.video),c=e.getAudioTrack(A.audio);yield t.zap({namespace:e.namespace(),catalog:e.catalog(),videoTrack:E==null?void 0:E.track,audioTrack:c==null?void 0:c.track},500),t.drm().then(h=>{h&&s(this,NA).emit("received drm data",h.value)}).catch(h=>{s(this,YA).error("Error getting DRM data",h)}),s(this,YA).info("switched channel",A.channelId),(C=s(this,Ne).get(Oe(t.namespace())))==null||C.updateCatalog(t.catalog()),s(this,NA).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,nA).videoTrack())==null?void 0:Q.name)?s(this,nA).setVideoTrack(g.track):void 0,B&&B.track.name!==((o=s(this,nA).audioTrack())==null?void 0:o.name)?s(this,nA).setAudioTrack(B.track):void 0]),s(this,NA).emit("received signal",{type:"subscription changed",subscription:A})})},yr=function(){return r(this,null,function*(){try{a(this,Ui,"connecting"),s(this,YA).info("Connecting..."),a(this,Ui,"connected"),yield Promise.all([d(this,TA,ln).call(this,s(this,nA).referenceClock(),s(this,nA).audio),d(this,TA,ln).call(this,s(this,nA).referenceClock(),s(this,nA).video),d(this,TA,fr).call(this,s(this,nA).subtitles)]),yield s(this,nA).closed(),s(this,St).close(),s(this,YA).info("Session closed")}catch(A){s(this,YA).warn("Session error",A)}})},fr=function(A){return r(this,null,function*(){try{for(var t=EA(A),e,g,B;e=!(g=yield t.next()).done;e=!1){const C=g.value;s(this,NA).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]}}})},ln=function(A,t){return r(this,null,function*(){var Q;let e="",g="",B;const C=s(this,nA).videoTrack()===void 0;try{for(var l=EA(t),m,f,U;m=!(f=yield l.next()).done;m=!1){const b=f.value;const Y=Oe(b.track.namespace),N=b.track.trackObject.language,v=RQ((Q=b.track.trackObject.codec)!=null?Q:""),T=b.track.trackObject.codec,P=v?xe({codec:v,codecString:T}):void 0,X=!!b.track.trackObject["com.vindral.drm"];try{for(var o=EA(b),E,c,h;E=!(c=yield o.next()).done;E=!1){const[yA,BA]=c.value;const Bt={channelId:e!==""&&(C||BA.mediaType()==="video")&&e!==Y?Y:void 0,language:BA.mediaType()==="audio"&&g!==N?N:void 0,drmTransition:B!==void 0&&B!==X};e=Y,g=N,B=X;const w=BA.producerReferenceTime(),R=s(this,_I).get(b.track.namespace)||0;if(w&&Date.now()-R>1e3){s(this,_I).set(b.track.namespace,Date.now());const x=A.wallclock()-w.getTime();s(this,YA).debug("timing-info",{mediaType:BA.mediaType(),referenceClock:A,delta:x,groupId:yA,timestamp:BA.baseMediaDecodeTime()/BA.timescale()*1e3+x,wallclockTime:w.getTime()}),s(this,NA).emit("received signal",{type:"timing info",timingInfo:{channelId:Y,timestamp:BA.baseMediaDecodeTime()/BA.timescale()*1e3+x,wallclockTime:w.getTime()}})}s(this,NA).emit("received moq data",{payload:BA,channelId:Y,groupId:yA,mimeType:P,codec:v,switchInfo:Bt,renditionId:Ol(b.track.trackObject.name)})}}catch(c){h=[c]}finally{try{E&&(c=o.return)&&(yield c.call(o))}finally{if(h)throw h[0]}}}}catch(f){U=[f]}finally{try{m&&(f=l.return)&&(yield f.call(l))}finally{if(U)throw U[0]}}})};let Bo=tn;function Ol(i){return i.split("").reduce((t,e)=>t=e.charCodeAt(0)+(t<<6)+(t<<16)-t,0)}class Co{constructor(A){n(this,WC);n(this,ge);n(this,Ni);a(this,ge,A),a(this,Ni,d(this,WC,pr).call(this))}catalog(){return s(this,ge).current()}namespace(){return s(this,ge).current().namespace}updateCatalog(A){a(this,ge,A)}getTextTrack(A){return s(this,ge).current().tracks.find(t=>t.label===A)}getAudioTrack(A){if(!A.codec)return;const t=s(this,Ni).filter(e=>!(!Pe(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,Ni).filter(e=>!(!Te(e)||e.bitRate>A.bitRate||A.codec&&e.codec!==A.codec));return t[t.length-1]}renditions(){return s(this,Ni)}}ge=new WeakMap,Ni=new WeakMap,WC=new WeakSet,pr=function(){const[A,t]=s(this,ge).value();return Gn(A)};const Vl=(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 Zl extends $A{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=y,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",S({},this.options)),this.close("one websocket had an error"),this.emit("error",new W("WebSocket error",{code:"websocket_error",isFatal:!1}))});I(this,"onClose",t=>{switch(this.logger.info("Closed",V(S({},this.options),{reason:t.reason,code:t.code,isSuspended:this.isSuspended})),this.close("one websocket was closed"),t.code){case 4e3:this.emit("error",FB(lg()));break;case 4001:this.emit("error",FB(lg()));break;case 4002:this.emit("error",lc(lg()));break;case 4003:this.emit("error",On("internal",lg()));break;case 4010:this.emit("error",uc("internal",lg()));break}this.emit("close",this)});I(this,"onOpen",()=>{this.logger.info("Opened",S({},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",S({},this.options)),yield Ye(this.options.reconnectDelay);const e=yield this.options.reconnectHandler(this.reconnectState);if(this.reconnectState.reconnectRetries++,!e)return this._isConnectInProgress=!1,this.emit("error",Vn()),!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(S({},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 W&&(this.logger.error("Failed to connect",e.toStringifiable()),e.isFatal())||this.shouldContinueConnecting&&(this.logger.info("Connection aborted",{error:e}),this.emit("error",new W("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 Xl=65536*8,jl=.9,Qo=i=>Xl*jl*1e3/i,qt=class qt{constructor(A,t,e){I(this,"emitter");I(this,"transport");I(this,"logger");I(this,"config");I(this,"rtts",new L(10));I(this,"lastPingSentTime",Date.now());I(this,"isPingInFlight",!1);I(this,"connectCount",0);I(this,"missedPings",0);I(this,"_estimatedPingBandwidth");I(this,"contextSwitchesInProgress",new Set);I(this,"contextSwitchesCompleted",new Set);I(this,"buffer",[]);I(this,"disconnected",new G);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 t;const A=oe(this.rtts.items());return{rtt:A,estimatedBandwidth:Qo(A.average),edgeUrl:(t=this.transport)==null?void 0:t.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(kn(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=Vl(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(!kn(e))return;switch(e.type){case"pong":this.lastPingSentTime&&(this.rtts.push(Date.now()-this.lastPingSentTime),this.isPingInFlight=!1,this.emitter.emit("rtt",this.rtt));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 Zl({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),this.emitter.emit("rtt",this.rtt)),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._estimatedPingBandwidth=Qo(e.estimatedRtt),this.logger=t,this.emitter=A,this.config=e,this.emitter.on("send signal",this.sendSignal),this.emitter.on("disconnect",this.close),this.emitter.on("reconnect",this.reconnect),this.disconnected.promise.catch(y),this.transport=this.connectWebSocketTransport()}get rtt(){return this.rtts.items().length>0?Wi(this.rtts.items()):0}get estimatedBandwidth(){return this.rtt>0?Qo(this.rtt):this._estimatedPingBandwidth}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)=>new Promise((g,B)=>{const C=new qt(A,t,e);C.transport.once("error",Q=>B(Q)),C.transport.once("open",()=>g(C))}));let oo=qt;class zl{constructor(A){n(this,tg);n(this,be,[]);n(this,eg);a(this,tg,A)}select(A){if(s(this,tg).edgeUrl)return s(this,tg).edgeUrl;s(this,be).length===0&&a(this,be,s(this,be).concat(A));const t=s(this,be).shift();if(a(this,eg,t),t)return t}shiftedEdge(){return s(this,eg)}reset(){a(this,eg,void 0),a(this,be,[])}}tg=new WeakMap,be=new WeakMap,eg=new WeakMap;const Bg=class Bg{constructor(A,t,e){n(this,ZC);I(this,"emitter");I(this,"logger");I(this,"config");I(this,"apiClient");I(this,"connectionImpl");n(this,vt,!0);n(this,ig);n(this,se,0);n(this,Ig,0);n(this,gg);n(this,sg);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;a(this,vt,!1),(A=this.connectionImpl)==null||A.suspend()});I(this,"unsuspend",()=>{var A;a(this,vt,!0),(A=this.connectionImpl)==null||A.unsuspend(),this.connect()});I(this,"getState",()=>this.connectionImpl?this.connectionImpl.getState():"disconnected");I(this,"getStatistics",()=>this.connectionImpl?V(S({},this.connectionImpl.getStatistics()),{connectCount:s(this,Ig),connectionAttemptCount:s(this,se)}):{rtt:{min:0,max:0,average:0,last:0},estimatedBandwidth:0,connectCount:s(this,Ig),connectionAttemptCount:s(this,se),connectionProtocol:void 0});I(this,"connect",()=>{a(this,vt,!0),!s(this,ig)&&a(this,ig,d(this,ZC,Fr).call(this))});I(this,"disconnect",(A="Disconnect Requested")=>{var t;a(this,vt,!1),(t=this.connectionImpl)==null||t.close(A)});I(this,"reconnect",A=>{this.disconnect(A),this.connect()});n(this,OC,()=>r(this,null,function*(){try{return yield this.apiClient.connect(this.config.options.getOptions())}catch(A){if(_r(A))switch(A.status){case 401:throw this.emitter.emit("error",FB(A)),FB(A);case 403:throw this.emitter.emit("error",Zn(A.message)),Zn(A.message)}throw this.emitter.emit("error",Dc(A instanceof Error?A:void 0)),A}}));n(this,VC,()=>r(this,null,function*(){const A=Date.now(),t=()=>Date.now()-A;return Promise.race([Ye(Bg.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 bn({publicEndpoint:this.config.options.get("url").toString(),tokenFactory:()=>this.config.options.get("authenticationToken")})}get rtt(){var A,t;return(t=(A=this.connectionImpl)==null?void 0:A.rtt)!=null?t:0}get estimatedBandwidth(){var A;return((A=this.connectionImpl)==null?void 0:A.estimatedBandwidth)||Number.MAX_SAFE_INTEGER}get firstConnectionTime(){return s(this,gg)}get lastConnectionTime(){return s(this,sg)}};vt=new WeakMap,ig=new WeakMap,se=new WeakMap,Ig=new WeakMap,gg=new WeakMap,sg=new WeakMap,OC=new WeakMap,VC=new WeakMap,ZC=new WeakSet,Fr=function(){return r(this,null,function*(){var t;const A=new zl({edgeUrl:this.config.options.get("edgeUrl")});for(a(this,se,0);;){ft(this,se)._++;try{const[g,B]=yield Promise.all([s(this,OC).call(this),s(this,VC).call(this)]),C=B/2;if(!s(this,vt))break;const Q=A.select(g.edges);if(!Q)throw new W("Failed to resolve edge url",{isFatal:!0,code:"failed_to_resolve_edge_url"});Fn(g)?this.connectionImpl=yield Bo.start(this.emitter,this.logger,this.apiClient,V(S({},this.config),{connectInfo:g,estimatedRtt:C,edgeUrl:Q})):(k(typeof Q=="string","Edge URL is expected to be a string"),this.connectionImpl=yield oo.start(this.emitter,this.logger,V(S({},this.config),{connectInfo:g,estimatedRtt:C,edgeUrl:Q}))),A.reset(),ft(this,Ig)._++,a(this,se,0),a(this,sg,Date.now()),s(this,gg)||a(this,gg,s(this,sg)),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 W?this.emitter.emit("error",g):g instanceof Error&&this.emitter.emit("error",new W(g.message,{code:"start_failed",isFatal:!1}))}if((t=this.connectionImpl)==null||t.unload(),this.connectionImpl=void 0,!s(this,vt))break;if(!(yield this.config.reconnectHandler({reconnectRetries:s(this,se)}))){this.emitter.emit("error",Vn());break}if(yield Ye(1e3),!s(this,vt))break}a(this,ig,void 0)})},I(Bg,"PING_TIMEOUT",1e3),I(Bg,"create",(A,t,e)=>new Bg(A,t,e));let no=Bg;const ao=()=>({video:V(S({},fB()),{bitRate:ne()}),audio:{bitRate:ne()}}),_l=()=>({width:window.innerWidth,height:window.innerHeight,bitRate:ne()}),Cg=class Cg{constructor(A,t,e,g){I(this,"emitter");I(this,"timers",new RA);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,Cg.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(S({},t),{video:S(S({},t.video),A.video),audio:S(S({},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,E,c;const A=this.sizeBasedResolutionCapEnabled?V(S({},ao()),{video:_l()}):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=(E=g==null?void 0:g.bitRate)!=null?E:A.video.bitRate,A.audio.bitRate=(c=B==null?void 0:B.bitRate)!=null?c:A.audio.bitRate,ve(A,this.currentCap)?this.currentCap=S({},A):(this.currentCap=S({},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(Cg,"CHECK_SIZE_INTERVAL",1e3),I(Cg,"create",(A,t,e,g)=>new Cg(A,t,e,g));let Eo=Cg;const $l=5,Au=100,tu=1e3;class ro{constructor(A,t,e,g){I(this,"timers",RA.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,Au),this.timers.setInterval(this.emitDecodeRate,tu),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=oe((C=A==null?void 0:A.decodeTime.items())!=null?C:[]),g=oe((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=oe((B=A==null?void 0:A.decodeTime.items())!=null?B:[]),e=oe((C=A==null?void 0:A.transportTime.items())!=null?C:[]),g=oe((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 W("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 W("No known decoder context",{code:"no_known_decoder_context",isFatal:!1});if(this.isSuspended)return;t.sampleDuration=A.duration/A.timescale*1e3;const{decoderContext:e,buffer:g}=t,B=A.timestamp/A.timescale*1e3,C=A.duration/A.timescale*1e3,Q=g[g.length-1];!Q||B-$l>Q.end?g.push({start:B,end:B+C}):B+C*5<Q.end?t.buffer=[{start:B,end:B+C}]:Q.end=B+C,e.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",Pn(!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,E,c,h;if(!A)A=Q.buffer;else{const l=(E=(o=Q.buffer[Q.buffer.length-1])==null?void 0:o.end)!=null?E: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(()=>lw);C.set(Q.type,{buffer:[],decoderContext:yield o.create(48e3,2),decodeTime:new L(100),transportTime:new L(100),sampleDuration:40});break}case"video":{const{H264DecoderWorkerContext:o}=yield Promise.resolve().then(()=>ww);C.set(Q.type,{buffer:[],decoderContext:yield o.create(B),decodeTime:new L(100),transportTime:new L(100),sampleDuration:40});break}}return new ro(A,t,C,g)})}}const XC=class XC{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(XC,"create",A=>new XC(A));let co=XC;const eu=i=>(A,t,e)=>A.timestamp<=t||A.timestampAdded<=e-i,Le=class Le{constructor(A,t,e){I(this,"logger");I(this,"emitter");I(this,"waitingEvents",[]);I(this,"isTriggered",eu(Le.EVENT_TIMEOUT));I(this,"timeSource");I(this,"timers",new RA);I(this,"load",()=>{this.timers.setInterval(this.onBufferedStateChanged,Le.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(S({},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(Le,"EVENT_TIMEOUT",5e3),I(Le,"EVENT_CHECK_INTERVAL",20),I(Le,"create",(A,t,e)=>new Le(A,t,e));let ho=Le;const mt=class mt{constructor(A){I(this,"emitter");I(this,"timers",RA.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 Kr(20),this.bytesReceived.set(A,e)),t>0&&(this.lastBytesUpdated=Date.now(),this.timeoutInterval||(this.timeoutInterval=this.timers.setInterval(this.checkTimeout,mt.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,mt.UPDATE_RECEIVED_BYTES_INTERVAL))});I(this,"checkTimeout",()=>{const A=Date.now()-this.lastBytesUpdated;if(this.totalBytesReceived()===0&&A>mt.NO_DATA_ERROR_TIMEOUT){this.emitter.emit("error",wc()),this.emitter.emit("reconnect","no incoming data"),this.clearTimeoutInterval();return}A>mt.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(mt,"NO_DATA_ERROR_TIMEOUT",20*1e3),I(mt,"NO_DATA_TIMEOUT",5*1e3),I(mt,"UPDATE_RECEIVED_BYTES_INTERVAL",1e3),I(mt,"create",A=>new mt(A));let lo=mt;const iu=()=>window.AudioContext||window.webkitAudioContext,jC=class jC extends $A{constructor(){super();I(this,"context",new(iu()));I(this,"timers",RA.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,dc())])}catch(t){throw this.suspend().catch(y),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},jC.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(jC,"CHECK_INTERVAL",1e3);let uo=jC;const zC=class zC extends $A{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 L(500));I(this,"unplayedBufferSources",new L(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 W("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 E=0;E<t;E++)o[E]=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(S({},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 uo,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(y),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(zC,"create",(t,e,g)=>new zC(t,e,g));let CC=zC;class Pa{constructor(){n(this,Je,[]);a(this,Je,[])}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,Je).push(B),B}set language(A){s(this,Je).forEach(t=>{t.language===A?t.mode="showing":t.mode="hidden"})}get language(){var A;return(A=s(this,Je).find(t=>t.mode==="showing"))==null?void 0:A.language}getActiveCues(A){const t=s(this,Je).find(e=>e.mode==="showing");return t?t.cues.filter(({startTime:e,endTime:g})=>A>=e&&A<=g):[]}}Je=new WeakMap;const Ve=(i,A)=>{let t;for(t=A;i>1;i--)t+=A;return t};class Iu{constructor(){I(this,"audio");I(this,"unmute",()=>this.audio.play().catch(y));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"+Ve(23,"A")+"WGluZwAAAA8AAAACAAACcQCA"+Ve(16,"gICA")+Ve(66,"/")+"8AAABhTEFNRTMuMTAwA8MAAAAAAAAAABQgJAUHQQAB9AAAAnGMHkkI"+Ve(320,"A")+"//sQxAADgnABGiAAQBCqgCRMAAgEAH"+Ve(15,"/")+"7+n/9FTuQsQH//////2NG0jWUGlio5gLQTOtIoeR2WX////X4s9Atb/JRVCbBUpeRUq"+Ve(18,"/")+"9RUi0f2jn/+xDECgPCjAEQAABN4AAANIAAAAQVTEFNRTMuMTAw"+Ve(97,"V")+"Q==",this.audio.loop=!1,this.audio.load();else throw new Error("Failed to create audio tag")}}class gu{constructor(){n(this,gt);n(this,CB,[]);n(this,Kt,document.createElement("canvas"));n(this,bA);n(this,bi,window.devicePixelRatio||1);I(this,"config",{backgroundColor:"rgba(0,0,0,0.6)",textPadding:8,fontSize:"28px",lineGap:16});const A=s(this,Kt).getContext("2d",{alpha:!0});if(!A)throw new Error("Failed to create 2d context");a(this,bA,A),d(this,gt,hg).call(this)}get canvas(){return s(this,Kt)}setActiveCues(A){a(this,CB,A)}render(A,t=!1){const e=s(this,CB).flatMap(Q=>Q.text.split(`
3
3
  `).flatMap(E=>d(this,gt,kr).call(this,E,A.width)).map(E=>{d(this,gt,hg).call(this);const c=s(this,bA).measureText(E);return{text:E,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,gt,Gr).call(this,g,B),s(this,bA).clearRect(0,0,s(this,Kt).width,s(this,Kt).height);for(const{size:Q,text:o}of e)d(this,gt,hg).call(this),s(this,bA).fillStyle=this.config.backgroundColor,s(this,bA).fillRect(0,C,Q.width,Q.height),d(this,gt,hg).call(this),s(this,bA).fillText(o,this.config.textPadding,C+this.config.textPadding),C+=Q.height+this.config.lineGap;t&&(s(this,bA).strokeStyle="red",s(this,bA).strokeRect(0,0,A.width,s(this,Kt).height))}}CB=new WeakMap,Kt=new WeakMap,bA=new WeakMap,bi=new WeakMap,gt=new WeakSet,Gr=function(A,t){s(this,Kt).width=A*s(this,bi),s(this,Kt).height=t*s(this,bi),s(this,bA).scale(s(this,bi),s(this,bi)),this.canvas.style.width=`${A}px`,this.canvas.style.height=`${t}px`},hg=function(){s(this,bA).fillStyle="white",s(this,bA).textAlign="left",s(this,bA).textBaseline="top",s(this,bA).font=`${this.config.fontSize} sans-serif`},kr=function(A,t){const e=[],g=A.split(" ");let B="";for(;g.length>0;){d(this,gt,hg).call(this);let C=0;for(;s(this,bA).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 su=`
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
- `,Za={width:256,codedWidth:256,height:144,codedHeight:144},Xa={preserveDrawingBuffer:!1,alpha:!1,depth:!1,stencil:!1,antialias:!1,premultipliedAlpha:!1},aB=class aB extends $A{constructor(){super();I(this,"canvas",document.createElement("canvas"));I(this,"context",xa(this.canvas,Xa));I(this,"pixelShader",ji(this.context,this.context.FRAGMENT_SHADER,Oa));I(this,"vertexShader",ji(this.context,this.context.VERTEX_SHADER,Va));I(this,"buffer",Wa(this.context,aB.SQUARE_VERTICES));I(this,"program",wo(this.context,this.vertexShader,this.pixelShader));I(this,"textures",{y:Ze(this.context),u:Ze(this.context),v:Ze(this.context)});I(this,"textRenderer");I(this,"size",Za);I(this,"onContextLost",t=>{this.textRenderer=void 0;const e=new Error(t instanceof WebGLContextEvent?t.statusMessage:"webgl context lost");this.emit("context lost",Sc(e)),t.preventDefault()});I(this,"onContextRestored",()=>{this.emit("context restored"),this.context=xa(this.canvas,Xa),this.pixelShader=ji(this.context,this.context.FRAGMENT_SHADER,Oa),this.vertexShader=ji(this.context,this.context.VERTEX_SHADER,Va),this.buffer=Wa(this.context,aB.SQUARE_VERTICES),this.program=wo(this.context,this.vertexShader,this.pixelShader),this.textures={y:Ze(this.context),u:Ze(this.context),v:Ze(this.context)},this.load()});I(this,"load",()=>{this.context.useProgram(this.program),this.setupPositionVertexAttributes(),this.setSize(Za),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 Cu(this.context)),this.textRenderer}};I(aB,"SQUARE_VERTICES",new Float32Array([0,0,0,1,1,0,1,1]));let Do=aB;const AQ=class AQ{constructor(A,t,e,g){I(this,"oldTimestampLimit",400);I(this,"pool");I(this,"logger");I(this,"videoRenderer",new Do);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.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(AQ,"create",(A,t,e,g)=>new AQ(A,t,e,g));let QC=AQ;const tQ=class tQ{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 Iu);I(this,"_isPaused",!1);I(this,"isDisconnected",!1);I(this,"timers",new RA);I(this,"textTracks",new Pa);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",xn(!1,t))}this.videoPlayer.onDecodedFrame(A)});this.logger=t,this.emitter=A,this.pool=e,this.audioPlayer=CC.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=QC.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(y)}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(tQ,"create",(A,t,e,g,B)=>new tQ(A,t,e,g,B));let So=tQ;const eQ=class eQ{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 RA);I(this,"volumeState");I(this,"textTracks",new Pa);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",xn(!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(y),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=CC.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=QC.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(y)}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(eQ,"create",(A,t,e,g,B)=>new eQ(A,t,e,g,B));let mo=eQ;const Qu=()=>i=>ja(i.buffered.start(0),i.buffered.end(i.buffered.length-1)),ja=(i,A)=>t=>t.remove(Math.max(0,i),Math.min(Number.POSITIVE_INFINITY,A)),za=i=>A=>A.appendBuffer(i),ou=i=>A=>A.changeType(i),nu=i=>A=>i(A);class au{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 xi(za(t),e,g);this.commandQueue.push(C),this.currentInit=t}const B=new xi(za(A),e,g);this.commandQueue.push(B),this.handleQueue()}));I(this,"execute",A=>new Promise((t,e)=>{const g=new xi(nu(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 xi(ou(A),t,e);this.commandQueue.push(g),this.handleQueue()}));I(this,"removeBuffer",(A,t)=>new Promise((e,g)=>{const B=new xi(ja(A,t),e,g);this.commandQueue.push(B),this.handleQueue()}));I(this,"flush",()=>new Promise((A,t)=>{const e=new xi(Qu,A,t);this.commandQueue.push(e),this.handleQueue()}));this.sourceBuffer=A,this.sourceBuffer.addEventListener("updateend",this.handleQueue)}}class _a extends $A{constructor(){super();I(this,"MediaSource",ot());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 au(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(_a,"isTypeSupported",t=>{var e,g;return(g=(e=ot())==null?void 0:e.isTypeSupported(t))!=null?g:!1});class $a{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 Eu(i,{mediaSource:A,mimeType:t,codec:e}){return V(S({},i),{state:"initialized",mimeType:t,codec:e,sourceBuffer:A.addSourceBuffer(t),isWorkingOnPendingSamples:!1,sequenceNumber:0,lastBufferCleanupTime:Date.now()})}function AE({initSegments:i,pendingSamples:A}){return{state:"uninitialized",initSegments:i!=null?i:new $a,sequenceNumber:0,isWorkingOnPendingSamples:!1,hasFirstSync:!!A,pendingSamples:A!=null?A:[],consecutiveQuotaExceededErrorCount:0,successfulAppendCalls:0}}const iQ=class iQ{constructor(A,t,e){I(this,"maxChunkSize",20);I(this,"minConsecutiveErrorsBeforeEmit",5);I(this,"maxSecondsInBuffer",60);I(this,"logger");I(this,"timers",RA.create());I(this,"emitter");I(this,"mediaElement");I(this,"mediaSource",new _a);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,E;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&&!((E=g[0])!=null&&E.isSync);)g.shift();this.trackContexts.set(e,AE({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=AE({pendingSamples:[],initSegments:new $a}),this.trackContexts.set(e.type,g)),g.state==="initialized"?e.mimeType!==g.mimeType&&(yield g.sourceBuffer.changeType(e.mimeType)):this.trackContexts.set(e.type,Eu(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 pB(A.type,A.renditionId);e.state==="initialized"&&(e.mimeType=t);const g=sd(A.codec,A.data,A.timescale);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 cc(e.renditionId,e.channelId);if(!g)throw pB(e.type,e.renditionId);if(g.state==="uninitialized")throw hc(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 E=g.previousSample;if(E&&E.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 E of A)"initData"in E&&(yield g.sourceBuffer.appendBuffer(E.data,E.initData));else{const E=ad(A,o++);yield g.sourceBuffer.appendBuffer(E)}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(),E=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 f=this.trackContexts.get(C);if(!f)throw pB(C);f.state==="initialized"&&t&&(f.mimeType=t,f.initSegments.set(g,B,o));const U={fragmented:!0,type:C,data:Q,initData:o,timestamp:E,duration:h,timescale:c,channelId:g,renditionId:B,isSync:l,codec:e,fragment:A,compositionTimeOffset:m};this.onCodedSample(U)});I(this,"onCodedSample",A=>{if(A.duration===0)return;const t=this.trackContexts.get(A.type);if(!t)throw pB(A.type,A.renditionId);if(!(!t.hasFirstSync&&!A.isSync)){if(this.hasAddedInitialPosterFrame&&A.isSync&&A.type==="video"){this.hasAddedInitialPosterFrame=!1;const e=S({},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||ru(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=Wn(!1,e,t.consecutiveQuotaExceededErrorCount,A.type);this.emitter.emit("error",g)}}else{const g=Wn(!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=rc(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(y)}}this.logger.debug("source ended")});this.logger=A,this.mediaElement=e,this.emitter=t}};I(iQ,"create",(A,t,e)=>{const g=new iQ(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 yo=iQ;const tE=(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},ru=(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],E=i.pendingSamples[Q+1];if(o&&(e.push(o),E)){if(tE(o,E))break;const c=(o.timestamp+o.duration)/o.timescale;if(E.timestamp/E.timescale-c>.1)break}if(Q===t-1)break}const B=e[0];if(!B)break;const C=i.previousSample?tE(i.previousSample,B):!0;yield A(e,C),i.pendingSamples=i.pendingSamples.slice(g+1),i.previousSample=e[e.length-1]}i.isWorkingOnPendingSamples=!1}),IQ=class IQ{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(IQ,"create",(A,t)=>new IQ(A,t));let fo=IQ;const gQ=class gQ{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=>void(this.targetBufferTime=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",E=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,E!==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)}};I(gQ,"create",(A,t,e,g)=>new gQ(A,t,e,g));let po=gQ;const Fo=()=>({upgradesFromLevel:[],downgradesFromLevel:[],bufferingRanges:[],activeRanges:[],decodeRate:Number.MAX_SAFE_INTEGER}),cu=()=>({levels:{},levelDowngrades:[],levelUpgrades:[],bufferFullness:0,general:Fo()}),sQ=class sQ{constructor(A,t){I(this,"minBufferFullnessLengthForRegression",6);I(this,"logger");I(this,"emitter");I(this,"timers",RA.create());I(this,"metrics",cu());I(this,"bufferFullness",new L(30));I(this,"bufferFullnessRegression");I(this,"currentLevel");I(this,"isSuspended",!1);I(this,"_fatalQosCount",0);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)});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.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,"activeRatios",()=>{const A=new Map,t=Vi(this.metrics.general.activeRanges);if(Object.entries(this.metrics.levels).forEach(([e,g])=>{A.set(e,t?Vi(g.activeRanges)/t:0)}),!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=Vi(this.metrics.general.bufferingRanges);if(Object.entries(this.metrics.levels).forEach(([e,g])=>{A.set(e,t?Vi(g.bufferingRanges)/t:0)}),!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=>mn(this.metrics.general.bufferingRanges,A));I(this,"timeSpentActiveLast",A=>mn(this.metrics.general.activeRanges,A));I(this,"timeSpentPlayingInAtLeastLevelRatio",A=>{var o,E,c,h;const t=this.timeSpentBuffering(),e=this.timeActive(),g=this.bufferingRatios(),B=this.activeRatios(),C=((E=(o=A.video)==null?void 0:o.bitRate)!=null?E: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,U;return((f=B.get(m.toString()))!=null?f:0)-((U=g.get(m.toString()))!=null?U:0)*Q+l},0)});I(this,"timeSpentBuffering",()=>Vi(this.metrics.general.bufferingRanges));I(this,"timeActive",()=>Vi(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,E,c,h,l,m,f,U,b,Y,N;const t=((Q=(C=(B=A.from)==null?void 0:B.video)==null?void 0:C.bitRate)!=null?Q:0)+((c=(E=(o=A.from)==null?void 0:o.audio)==null?void 0:E.bitRate)!=null?c:0),e=((m=(l=(h=A.to)==null?void 0:h.video)==null?void 0:l.bitRate)!=null?m:0)+((b=(U=(f=A.to)==null?void 0:f.audio)==null?void 0:U.bitRate)!=null?b: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 v=(Y=this.metrics.levels[t])!=null?Y:Fo();t<e?v.upgradesFromLevel.push(Date.now()):v.downgradesFromLevel.push(Date.now()),Ke(v.activeRanges);const T=v.bufferingRanges[v.bufferingRanges.length-1];g=!!T&&!T.end,Ke(v.bufferingRanges),this.metrics.levels[t]=v}if(A.to){const v=(N=this.metrics.levels[e])!=null?N:Fo();Oi(v.activeRanges),g&&Oi(v.bufferingRanges),this.metrics.levels[e]=v,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,"calculateLinearRegression",()=>vr(this.bufferFullness.items().map((A,t)=>({x:t,y:A}))));I(this,"stopBuffering",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Ke(A.bufferingRanges)}Ke(this.metrics.general.bufferingRanges)});I(this,"startBuffering",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Oi(A.bufferingRanges)}Oi(this.metrics.general.bufferingRanges)});I(this,"unsetActive",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Ke(A.activeRanges)}Ke(this.metrics.general.activeRanges)});this.logger=t,this.emitter=A}get fatalQosCount(){return this._fatalQosCount}setActive(){if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Oi(A.activeRanges)}Oi(this.metrics.general.activeRanges)}};I(sQ,"create",(A,t)=>new sQ(A,t));let Go=sQ;const BQ=class BQ{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&&Te(e))return e});I(this,"getAudioRenditions",A=>{const t=this.renditions.get(A);return t==null?void 0:t.filter(g=>Pe(g))});I(this,"getVideoRenditions",A=>{const t=this.renditions.get(A);return t==null?void 0:t.filter(g=>Te(g))});I(this,"getAudioRendition",(A,t=this.getCurrentSubscription().channelId)=>{const e=this.getRendition(A,t);if(e&&Pe(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,E,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:(E=A==null?void 0:A.audio)==null?void 0:E.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 E;const{channelId:e,initiator:g}=A,B=this.getRenditionLevel(t),C=new Set;((E=this.renditions.get(e))!=null?E:[]).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(Te).filter(h=>t&&h.codec===t.codec),Q=B.filter(Pe).filter(h=>e&&h.codec===e.codec&&h.language===e.language),o=Math.max(C.length,Q.length),E=[];for(let h=0;h<o;h++){const l=C[Math.min(C.length-1,h)],m=Q[Math.min(Q.length-1,h)];E.push({audio:m,video:l})}return E});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(BQ,"create",(A,t)=>new BQ(A,t));let ko=BQ;const yg=i=>JSON.parse(JSON.stringify(i)),hu=1e4,CQ=class CQ{constructor(A,t,e){I(this,"logger");I(this,"timers",new RA);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=yg(this.currentSubscription):this.currentSubscription=yg(A),this._isSwitchingSubscription=this.isNewSubscription()});I(this,"scheduleSubscriptionChange",()=>{this.targetSubscription=yg(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=yg(this.currentSubscription),this.emitter.emit("channel switch timeout",t))},hu),this.pendingSubscriptionTimeoutId=this.timers.setTimeout(()=>this.emitter.emit("send signal",{type:"subscribe",subscription:this.getTargetSubscription()}),0))});this.logger=A,this.targetSubscription=t,this.currentSubscription=yg(t),this.emitter=e,this.emitter.on("subscription changed",this.onSubscriptionChanged)}};I(CQ,"create",(A,t,e)=>new CQ(A,e,t));let Ro=CQ;const eE=5e3,du=()=>Ti()||pA()||VA(),iE=()=>du()?100:0,IE=i=>A=>A>i,QQ=class QQ{constructor(A,t,e,g,B){I(this,"emitter");I(this,"logger");I(this,"playbackSource");I(this,"bufferSource");I(this,"keyframeTimestamps",new L(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:iE(),minOvershootAllowed:iE(),maxOvershootAllowed:500});I(this,"maxTimeSyncDifferenceTolerance",150);I(this,"timers",RA.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-eE);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-eE);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(IE(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(IE(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 E=this.currentSyncMaxBehind;this.syncMaxBehindMultiplier+=this.syncMaxBehindMultiplierStep,E!==this.currentSyncMaxBehind&&this.logger.info("Increasing max drift behind allowed",{from:E,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(S({},t),{localTimestamp:e,timeDifferences:new L(12)}));return}const C=t.wallclockTime-g.wallclockTime,Q=t.timestamp-g.timestamp,o=e-g.localTimestamp,E=Q-o;if(g.timeDifferences.push(E),this.logger.debug("Timing info",{rtt:this.rtt,channelId:A,syncInfo:t,localTimestamp:e,diffFromEstimated:E,timestampDelta:Q,wallclockDelta:C,localWallclockDelta:o}),Math.abs(E)>=this.bufferSource.getTargetBufferTime()*2){this.logger.info("Resetting sync info",{diffFromEstimated:E}),this.channelSyncInfo.set(A,V(S({},t),{localTimestamp:e,timeDifferences:new L(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=Wi(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(QQ,"create",(A,t,e,g,B)=>new QQ(A,t,e,g,B));let Uo=QQ;const lu={enabled:!0,interval:3e4,includeErrors:!0,includeEvents:!0,includeStats:!0,maxRetries:10,maxErrorReports:50,maxEvents:50},No=(i,A)=>V(S({},A),{type:i,timestamp:new Date().toISOString(),discriminator:"web"}),oQ=class oQ{constructor(A,t,e,g){I(this,"logger");I(this,"timers",new RA);I(this,"emitter");I(this,"options");I(this,"parentContext");I(this,"unsentLines",new L(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=No("stats",V(S(S({},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=No("event",S(S({},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 Un(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 W){if(this.errorCount++,this.errorCount>e)return;const g=this.parentContext.getStatistics();this.unsentLines.push(No("error",S(S({},g),A.toStringifiable())))}});this.logger=A,this.emitter=t,this.options=S(S({},lu),e),this.parentContext=g}};I(oQ,"create",(A,t,e,g)=>new oQ(A,t,e,g));let oC=oQ;const nQ=class nQ{constructor(A,t,e){I(this,"logger");I(this,"element");I(this,"documentState");I(this,"timers",new RA);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(nQ,"create",(A,t,e)=>new nQ(A,t,e));let nC=nQ;const uu=6,wu=i=>{let A=[i],t=0,e=0,g=!1;const B=(Q,o)=>{var b,Y,N;Q.flags&&Sg(Q.flags)&&(t=(b=Q.compositionTimeOffset)!=null?b:0),Q.timestamp+=t,Q.compositionTimeOffset=((Y=Q.compositionTimeOffset)!=null?Y:0)-t;const E=Q.timestamp/Q.timescale,h=o.flags&&Sg(o.flags)?(N=o.compositionTimeOffset)!=null?N:0:t,m=(o.timestamp+h)/o.timescale,f=Math.max(0,Math.round((m-E)*Q.timescale));return f>0&&(e=f),V(S({},Q),{duration:f>0?f:e})};return(Q,o=!1)=>{if(Q.flags&&Sg(Q.flags)&&o&&(g=!g),!(o&&A.length<uu&&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),[]}},Du=(i,A,t)=>{if(Te(A))return S(V(S({},i),{type:"video",codec:A.codec,isSync:Sg(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(S({},i),{type:"audio",channels:A.channels,sampleRate:A.sampleRate,codec:A.codec,language:A.language,isSync:Sg(i.flags),data:i.payload,duration:0})};class Su{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,E,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((N,v)=>N.brand.localeCompare(v.brand));const m=[...(Q=this.highEntropyValues.fullVersionList)!=null?Q:[]];m.sort((N,v)=>N.brand.localeCompare(v.brand));const f=m.map(N=>N.version),U=l.map(N=>N.brand),b=l.map(N=>N.version),Y=parseInt((E=(o=this.highEntropyValues.platformVersion)==null?void 0:o.split(".")[0])!=null?E:"1");return S({userAgentLegacy:window.navigator.userAgent,ua:{browser:{brands:U,fullVersionBrands:f,majorVersions:b},device:this.highEntropyValues.model||"Other",os:{family:this.highEntropyValues.platform||"Other",version:(c=this.highEntropyValues.platformVersion)!=null?c:"1",major_version:Number.isFinite(Y)?Y:0}}},g)}else return S({userAgent:window.navigator.userAgent},g)}}const mu=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},st=class st extends $A{constructor(t){super();I(this,"pictureInPicture");I(this,"drm");I(this,"browser",yQ());I(this,"options");I(this,"element");I(this,"playbackSource");I(this,"emitter",new $A);I(this,"logger");I(this,"modules");I(this,"clientIp");I(this,"sessionId");I(this,"clientId",pn());I(this,"_channels",[]);I(this,"createdAt",Date.now());I(this,"hasCalledConnect",!1);I(this,"latestEmittedLanguages",[]);I(this,"wakeLock");I(this,"pool",new p(st.MAX_POOL_SIZE));I(this,"userAgentInformation",new Su);I(this,"encryptedMediaExtensions");n(this,Li,0);n(this,zA,[]);I(this,"sampleProcessingSesssions",new Map);I(this,"sizes",new Map);I(this,"isSuspended",!0);I(this,"disconnectTimeout");n(this,Ji);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 E;this.sessionId=pn();const e=this.modules.subscription.getTargetSubscription(),g=t.channels.find(c=>c.channelId===e.channelId);if(this.emitter.emit("connect info",t),this._channels=t.channels,this.updateTextTracks((E=g==null?void 0:g.renditions)!=null?E:[]),!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 On("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,zA).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,zA).push(C)}else if(this.mediaElement instanceof HTMLVideoElement){const C=this.mediaElement.addTextTrack(g.kind,g.label||g.language,g.language);s(this,zA).push(C)}}});for(const g of s(this,zA))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,zA).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(Pe(Q))return!0;if(!Te(Q)||!this.isSupportedVideoCodecProfile(Q.codec,Q.codecString))return!1;if(!this.willUseMediaSource()){const m=this.options.get("advanced"),f=(c=m.wasmDecodingConstraint.bitRate)!=null?c:Number.MAX_SAFE_INTEGER,U=(h=m.wasmDecodingConstraint.width)!=null?h:Number.MAX_SAFE_INTEGER,b=(l=m.wasmDecodingConstraint.height)!=null?l:Number.MAX_SAFE_INTEGER;return Q.bitRate<=f&&Q.width<=U&&Q.height<=b}const o=yield fd(Q);if(!o.supported||Q.codec=="av1"&&!o.smooth&&!o.powerEfficient)return!1;const E=this.options.getOverride("maxVideoBitRate",this.channelId);return E?E>=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=Math.min(this.options.get("maxVideoBitRate"),st.INITIAL_MAX_BIT_RATE,e,this.targetSubscription.video.bitRate),B=Math.min(this.options.get("maxAudioBitRate"),st.INITIAL_MAX_BIT_RATE,e,this.targetSubscription.audio.bitRate),C=this.options.get("media")==="audio"?[]:this.options.get("videoCodecs",this.channelId),Q=this.supportedAudioCodecs(),o=t.renditions.filter(Pe),E=t.renditions.filter(Te),c=Q.find(f=>o.find(U=>U.codec===f)!==void 0),h=C.find(f=>E.find(U=>U.codec===f)!==void 0),l=o.map(f=>f.language);if(this.logger.debug("supported and selected codecs",{audioCodecs:Q,videoCodecs:C,audioCodec:c,videoCodec:h}),h){const f=this.options.get("maxSize");this.modules.subscription.setVideoConstraint(S({codec:h,bitRate:this.abrEnabled?g:this.options.get("maxVideoBitRate")},f))}c&&(this.modules.subscription.setAudioConstraint({codec:c,bitRate:this.abrEnabled?B:this.options.get("maxAudioBitRate"),language:this.options.get("language")}),(!l.includes(this.options.get("language"))||this.language===void 0)&&this.modules.subscription.setLanguage(l[0])),this.alignSizeAndBitRate(this.targetSubscription);const m=this.modules.subscription.getTargetSubscription();this.emitter.emit("subscription changed",{to:m,from:this.modules.subscription.getCurrentSubscription()})});I(this,"isSupportedVideoCodecProfile",(t,e)=>{if(this.willUseMediaSource()){const g=ot();return g?g.isTypeSupported(xe({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.browser.supportsMp4Opus&&this.options.get("mseOpusEnabled")||!this.willUseMediaSource())&&t.push("opus"),this.willUseMediaSource()&&t.push("aac"),t});I(this,"initializeDecodingModule",()=>r(this,null,function*(){var g,B;const t=this.currentRenditionLevel,e=[];if(!t)throw new W("No currentRenditionLevel",{code:"no_current_rendition_level",isFatal:!1});if(t!=null&&t.video&&e.push({type:"video",mimeType:xe(t.video),codec:t.video.codec}),t!=null&&t.audio&&e.push({type:"audio",codec:t.audio.codec,mimeType:xe(t.audio)}),e.length===0)throw new W("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 p(st.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",()=>{yd(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(),st.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",()=>Object.values(this.modules).reduce((t,e)=>e&&"getStatistics"in e?S(S({},t),e.getStatistics()):t,this.getRuntimeInfo()));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 S({uptime:Date.now()-this.createdAt,version:"4.1.2-7-gc4e751c6",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 md(S(S({},ic),mc(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=kA.get();B.setLevel(this.options.get("logLevel")),B.setDebug(!1),this.logger=B;const C=fo.create(this.emitter,this.logger.createContext("PictureInPictureModule")),Q=RA.create(),o=no.create(this.emitter,this.logger.createContext("ConnectionModule"),{reconnectHandler:this.options.get("reconnectHandler"),options:this.options,onConnectInfo:this.onConnectInfo}),E=Ro.create(this.logger.createContext("SubscriptionModule"),this.emitter,g),c=ko.create(this.emitter,E),h=Go.create(this.emitter,this.logger.createContext("QualityOfServiceModule")),l=po.create(this.emitter,this.logger.createContext("PlaybackModule"),this,this.options.get("minBufferTime"));this.encryptedMediaExtensions=new ia(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),f=this.options.get("poster"),U=f===!0?this.getThumbnailUrl():f||void 0;let b,Y,N;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:U});w.on("buffer state",R=>this.emitter.emit("buffer state",R)),w.on("needs user input",R=>this.emitter.emit("needs user input",R)),w.on("volume state",R=>this.emit("volume state",R)),w.on("media element state",R=>this.onMediaElementState(R)),this.element=w.element,this.playbackSource=w,ia.isSupported()&&this.encryptedMediaExtensions.attach(w.element),b=yo.create(this.logger.createContext("MseModule"),this.emitter,this.element),this.options.get("pauseSupportEnabled")||(Y=nC.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=mo.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:U}),R=w.element();this.element=R.element,this.playbackSource=w,N=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")||(Y=nC.create(this.logger.createContext("UnpauseModule"),R,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,N=w,this.options.get("iosWakeLockEnabled")&&(this.wakeLock=new ud)}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 v=this.browser.platform.isIOS&&!this.browser.platform.isIpadOS,T=Uo.create(this.emitter,this.logger.createContext("SyncModule"),this.playbackSource,l,this.willUseMediaSource()&&!v),P=(this.options.get("edgeUrl")||this.options.get("url")).replace("wss://","https://").replace("ws://","http://").replace("//lb.","//errors."),X=new URL("/telemetry",P).toString(),yA=oC.create(this.logger.createContext("TelemetryModule"),this.emitter,{url:X,enabled:this.options.get("telemetryEnabled"),includeStats:!1,interval:5e3},this);this.modules={telemetry:yA,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,documentState:m,connection:o,playback:l,pictureInPicture:C,timer:Q,subscription:E,renditions:c,qualityOfService:h,mseModule:b,unpause:Y,canvasModule:N},this.modules.adaptivity.isEnabled=this.options.get("abrEnabled"),this.emitter.on("page active",w=>{var R;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(),(R=this.modules.canvasModule)==null||R.unsuspend()):this.modules.connection.disconnect():(this.disconnectTimeout&&this.modules.timer.clearInterval(this.disconnectTimeout),this.disconnectTimeout=this.modules.timer.setInterval(()=>{const x=this.playbackState==="paused"||this.muted;this.connectionState==="connected"&&x&&(this.emitter.emit("flush buffers"),this.modules.connection.disconnect("Page inactive timeout"))},st.DISCONNECT_TIMEOUT)))});let BA;this.emitter.on("context switch complete",()=>{BA||(BA=window.setTimeout(()=>{window.clearTimeout(BA),BA=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 eA,O,j;const x=((O=(eA=w.telemetry)==null?void 0:eA.probability)!=null?O:1)>=Math.random();w.telemetry&&((j=this.modules.telemetry)==null||j.unload(),this.modules.telemetry=oC.create(this.logger.createContext("TelemetryModule"),this.emitter,V(S({},w.telemetry),{enabled:this.options.get("telemetryEnabled")&&x}),this),this.modules.telemetry.load())}),this.emitter.on("adapt level",w=>{var MA,F,K,AA,CA;this.logger.debug("adapt level",{direction:w});const R=this.modules.renditions.getRenditionLevels(),x=this.modules.renditions.getRenditionLevel(),eA=R.findIndex(M=>M===x),O=R.length-1;let j=eA;switch(w){case"upgrade":{const M=Math.min(eA+1,O),sA=R[M],ng=(MA=this.modules.connection.estimatedBandwidth)!=null?MA:ne(),ag=((K=(F=sA==null?void 0:sA.audio)==null?void 0:F.bitRate)!=null?K:0)+((CA=(AA=sA==null?void 0:sA.video)==null?void 0:AA.bitRate)!=null?CA:0),cB=ng*2>ag;sA&&cB&&this.modules.adaptivity.isQoSOk(sA)&&(j=M)}break;case"downgrade":j=Math.max(eA-1,0);break;case"double downgrade":j=Math.max(eA-2,0);break;case"reconnect":if(eA===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 j=0}if(j===eA)return;const oA=R[j];this.alignSizeAndBitRate(V(S({},this.targetSubscription),{video:S(S({},this.targetSubscription.video),oA==null?void 0:oA.video),audio:S(S({},this.targetSubscription.audio),oA==null?void 0:oA.audio)})),this.emitter.emit("adapted level")}),this.emitter.on("text track data",w=>{const R=s(this,zA).find(j=>j.language===w.language),eA=this.modules.sync.getTimeshiftOffset()/1e3,O=eA-s(this,Li);if(a(this,Li,eA),R){if(R.cues)for(const j of R.cues)j.startTime-=O,j.endTime-=O;for(const j of w.cues){const oA=new VTTCue(j.startTime-eA,j.endTime-eA,j.text);R.addCue(oA)}}}),this.emitter.on("received signal",w=>{var eA;const R=w,x=this.modules.subscription.getCurrentSubscription();switch(this.logger.debug("received",S({},R)),R.type){case"client ip":this.clientIp=R.ip;break;case"renditions":this.updateTextTracks(R.renditions),a(this,Ji,this.filterRenditions(R.renditions).then(O=>{this.emitter.emit("renditions",{renditions:O,channelId:this.currentSubscription.channelId}),this.emit("rendition levels",this.modules.renditions.getRenditionLevels()),this.emitLanguagesIfChanged()}).finally(()=>{a(this,Ji,void 0)}));break;case"subscription changed":try{mu(R.subscription)}catch(O){this.emitter.emit("error",new W("Subscription failed validation",{source:O instanceof Error?O:void 0,isFatal:!1,code:"subscription_failed_validation"}))}this.emitter.emit("subscription changed",{reset:R.reset,to:R.subscription,from:this.modules.subscription.getCurrentSubscription()}),R.reset&&x.channelId!==R.subscription.channelId&&(this.emit("error",Xn(R.subscription.channelId)),this.emit("channel switch failed",{channelId:x.channelId})),this.modules.sync.timeshiftOnAudio=!((eA=R.subscription.video)!=null&&eA.codec),this.modules.adaptivity.reset();break;case"timing info":this.modules.sync.updateChannelSyncInfo(R.timingInfo.channelId,R.timingInfo),this.emit("server wallclock time",R.timingInfo.wallclockTime);break}}),this.emitter.on("channel switch timeout",w=>{this.emit("error",Xn(w)),this.emit("channel switch failed",{channelId:this.currentSubscription.channelId})}),this.emitter.on("received data",w=>{const R=this.modules.subscription.getCurrentSubscription(),x=dd(w);if(!R){this.logger.warn("Received unwanted message",S({},x));return}Bt(V(S({},x),{channelId:R.channelId}))}),this.emitter.on("received moq data",w=>{var j,oA,MA;const R=w.payload.mediaType(),x=w.channelId,eA=w.renditionId,O=this.modules.sync.processFragment(x,w.payload);if(w.switchInfo.channelId&&(w.switchInfo.drmTransition&&this.emitter.emit("error",jn("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(R,w.payload.rawBytes().byteLength),O.fragment().emsgs.forEach(F=>{if(!F.presentationTime)return;const K=xc(F.data);K&&this.modules.event.addEvent({id:F.id,timestamp:F.presentationTime/F.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:K.txx.value,type:"metadata"})}),this.modules.decoder){const F=(j=O.header().init().moov.traks[0])==null?void 0:j.mdia.minf.stbl.stsd,K=(oA=F==null?void 0:F.avc1)==null?void 0:oA.avcC.bytes,AA=(MA=F==null?void 0:F.codec)!=null?MA:"h264";if(K){const CA=K.buffer.slice(K.byteOffset,K.byteOffset+K.byteLength);if(R==="text")throw new Error("Subtitles are not supported");this.emitter.emit("init segment",{initSegment:{channelId:x,renditionId:eA,data:CA,timescale:1e3,type:R,codec:AA},mimeType:R})}for(let CA=0;CA<O.samplesCount();CA++){const M=O.sample(CA);M&&this.emitter.emit("coded sample",V(S({},M),{renditionId:eA,channelId:x,data:M.data.buffer.slice(M.data.byteOffset,M.data.byteOffset+M.data.byteLength)}))}}else this.emitter.emit("fragment",{mimeType:w.mimeType,codec:w.codec,fragment:O,channelId:x,renditionId:eA})});const fA=this.options.get("container");fA&&this.attach(fA),this.logger.info("Created Vindral instance",{options:this.options});const Bt=w=>r(this,null,function*(){const R=w.channelId;s(this,Ji)&&(yield s(this,Ji));const x=this.modules.renditions.getRendition(w.renditionId,R);if(!rd(w.flags)){if(cd(w.flags)){const O=new TextDecoder().decode(w.payload),j=this.modules.sync.getTimeshiftOffset();if(w.renditionId!==0){const oA=fn(O);if(oA&&oA.language!==void 0){const F=new ha().parse(oA.content||""),K=j/1e3,AA=s(this,zA).find(M=>M.language===oA.language),CA=K-s(this,Li);if(a(this,Li,K),AA){if(AA.cues)for(const M of AA.cues)M.startTime-=CA,M.endTime-=CA;for(const M of F){const sA=new VTTCue(M.startTime-K,M.endTime-K,M.text);AA.addCue(sA)}}}}else this.modules.event.addEvent({timestamp:w.timestamp/w.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:O,type:"metadata"})}else if(x!=null&&x.codec){const eA=D(x.codec);if(eA==="text")throw new Error("Subtitles are not supported");if(this.modules.incomingData.add(eA,w.payload.byteLength),Ed(w.flags)){const O=V(S({type:eA,data:w.payload,codec:x.codec},w),{channelId:R}),j=Bd(O.codec,O.payload);j&&this.sizes.set(O.renditionId,j);const oA=xe({codec:x.codec,codecString:x.codecString});this.emitter.emit("init segment",{initSegment:O,mimeType:oA}),this.emit("initialized media")}else{const O=Du(w,x,this.sizes.get(w.renditionId));let j=this.sampleProcessingSesssions.get(eA);if(!j)j=wu(this.modules.sync.processSample(O)),this.sampleProcessingSesssions.set(eA,j);else{const oA=j(this.modules.sync.processSample(O),this.isSwitchingRenditionLevel&&O.type==="video");let MA=O;oA.forEach(F=>{this.modules.event.extractEvent(F,MA),this.emitter.emit("coded sample",F),MA=F})}}}}});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"),fB())||(this.maxSize=this.options.get("maxSize")),this.options.get("burstEnabled")&&E.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,zA).forEach(e=>{e.label===t?e.mode="showing":e.mode="hidden"}),this.emitter.emit("text track",t)}get textTracks(){return s(this,zA).filter(t=>t.mode!=="disabled").map(t=>t.label)}get textTrack(){var t;return(t=s(this,zA).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(E=>E.language===C),o=e.find(E=>(B==null?void 0:B.find(c=>c.codec===E))!==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:fB();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:ne()}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:ne()}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(S({},t),{video:S({},t.video),audio:S({},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),E=C==null?void 0:C.find(h=>h.language),c=(C==null?void 0:C.length)&&C[0]||void 0;o||(E?(this.logger.debug("Randomizing language since target did not have current language"),this.modules.subscription.setAudioBitRate(E.bitRate),this.modules.subscription.setLanguage(E.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")}};Li=new WeakMap,zA=new WeakMap,Ji=new WeakMap,I(st,"MAX_POOL_SIZE",10),I(st,"INITIAL_MAX_BIT_RATE",2.5*1e3*1e3),I(st,"DISCONNECT_TIMEOUT",15*1e3),I(st,"REMOVE_CUE_THRESHOLD",1e3*10);let aC=st;const EC={buffering:"_buffering_1ccif_1","buffering-fullscreen":"_buffering-fullscreen_1ccif_16",hidden:"_hidden_1ccif_25","buffering-indicator":"_buffering-indicator_1ccif_31"};class At{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 bo=EC.hidden,yu=EC.buffering,gE=EC["buffering-fullscreen"],fu=EC["buffering-indicator"];class sE extends At{constructor(){super(document.createElement("div"));I(this,"indicator",document.createElement("div"));I(this,"isHidden",()=>this.element.classList.contains(bo));I(this,"setHidden",t=>t?this.hide():this.show());I(this,"hide",()=>this.element.classList.add(bo));I(this,"show",()=>this.element.classList.remove(bo));I(this,"fullscreen",t=>{t?this.element.classList.add(gE):this.element.classList.remove(gE)});this.element.className=yu,this.indicator.className=fu,this.element.appendChild(this.indicator)}}class BE extends $A{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}})}}const CE={bar:"_bar_zames_1",hidden:"_hidden_zames_45"},fg={"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"},pu={"icon-button":"_icon-button_5fg7v_1"},QE={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
+ `,Za={width:256,codedWidth:256,height:144,codedHeight:144},Xa={preserveDrawingBuffer:!1,alpha:!1,depth:!1,stencil:!1,antialias:!1,premultipliedAlpha:!1},aB=class aB extends $A{constructor(){super();I(this,"canvas",document.createElement("canvas"));I(this,"context",xa(this.canvas,Xa));I(this,"pixelShader",ji(this.context,this.context.FRAGMENT_SHADER,Oa));I(this,"vertexShader",ji(this.context,this.context.VERTEX_SHADER,Va));I(this,"buffer",Wa(this.context,aB.SQUARE_VERTICES));I(this,"program",wo(this.context,this.vertexShader,this.pixelShader));I(this,"textures",{y:Ze(this.context),u:Ze(this.context),v:Ze(this.context)});I(this,"textRenderer");I(this,"size",Za);I(this,"onContextLost",t=>{this.textRenderer=void 0;const e=new Error(t instanceof WebGLContextEvent?t.statusMessage:"webgl context lost");this.emit("context lost",Sc(e)),t.preventDefault()});I(this,"onContextRestored",()=>{this.emit("context restored"),this.context=xa(this.canvas,Xa),this.pixelShader=ji(this.context,this.context.FRAGMENT_SHADER,Oa),this.vertexShader=ji(this.context,this.context.VERTEX_SHADER,Va),this.buffer=Wa(this.context,aB.SQUARE_VERTICES),this.program=wo(this.context,this.vertexShader,this.pixelShader),this.textures={y:Ze(this.context),u:Ze(this.context),v:Ze(this.context)},this.load()});I(this,"load",()=>{this.context.useProgram(this.program),this.setupPositionVertexAttributes(),this.setSize(Za),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 Cu(this.context)),this.textRenderer}};I(aB,"SQUARE_VERTICES",new Float32Array([0,0,0,1,1,0,1,1]));let Do=aB;const AQ=class AQ{constructor(A,t,e,g){I(this,"oldTimestampLimit",400);I(this,"pool");I(this,"logger");I(this,"videoRenderer",new Do);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.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(AQ,"create",(A,t,e,g)=>new AQ(A,t,e,g));let QC=AQ;const tQ=class tQ{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 Iu);I(this,"_isPaused",!1);I(this,"isDisconnected",!1);I(this,"timers",new RA);I(this,"textTracks",new Pa);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",xn(!1,t))}this.videoPlayer.onDecodedFrame(A)});this.logger=t,this.emitter=A,this.pool=e,this.audioPlayer=CC.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=QC.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(y)}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(tQ,"create",(A,t,e,g,B)=>new tQ(A,t,e,g,B));let So=tQ;const eQ=class eQ{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 RA);I(this,"volumeState");I(this,"textTracks",new Pa);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",xn(!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(y),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=CC.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=QC.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(y)}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(eQ,"create",(A,t,e,g,B)=>new eQ(A,t,e,g,B));let mo=eQ;const Qu=()=>i=>ja(i.buffered.start(0),i.buffered.end(i.buffered.length-1)),ja=(i,A)=>t=>t.remove(Math.max(0,i),Math.min(Number.POSITIVE_INFINITY,A)),za=i=>A=>A.appendBuffer(i),ou=i=>A=>A.changeType(i),nu=i=>A=>i(A);class au{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 xi(za(t),e,g);this.commandQueue.push(C),this.currentInit=t}const B=new xi(za(A),e,g);this.commandQueue.push(B),this.handleQueue()}));I(this,"execute",A=>new Promise((t,e)=>{const g=new xi(nu(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 xi(ou(A),t,e);this.commandQueue.push(g),this.handleQueue()}));I(this,"removeBuffer",(A,t)=>new Promise((e,g)=>{const B=new xi(ja(A,t),e,g);this.commandQueue.push(B),this.handleQueue()}));I(this,"flush",()=>new Promise((A,t)=>{const e=new xi(Qu,A,t);this.commandQueue.push(e),this.handleQueue()}));this.sourceBuffer=A,this.sourceBuffer.addEventListener("updateend",this.handleQueue)}}class _a extends $A{constructor(){super();I(this,"MediaSource",ot());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 au(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(_a,"isTypeSupported",t=>{var e,g;return(g=(e=ot())==null?void 0:e.isTypeSupported(t))!=null?g:!1});class $a{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 Eu(i,{mediaSource:A,mimeType:t,codec:e}){return V(S({},i),{state:"initialized",mimeType:t,codec:e,sourceBuffer:A.addSourceBuffer(t),isWorkingOnPendingSamples:!1,sequenceNumber:0,lastBufferCleanupTime:Date.now()})}function AE({initSegments:i,pendingSamples:A}){return{state:"uninitialized",initSegments:i!=null?i:new $a,sequenceNumber:0,isWorkingOnPendingSamples:!1,hasFirstSync:!!A,pendingSamples:A!=null?A:[],consecutiveQuotaExceededErrorCount:0,successfulAppendCalls:0}}const iQ=class iQ{constructor(A,t,e){I(this,"maxChunkSize",20);I(this,"minConsecutiveErrorsBeforeEmit",5);I(this,"maxSecondsInBuffer",60);I(this,"logger");I(this,"timers",RA.create());I(this,"emitter");I(this,"mediaElement");I(this,"mediaSource",new _a);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,E;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&&!((E=g[0])!=null&&E.isSync);)g.shift();this.trackContexts.set(e,AE({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=AE({pendingSamples:[],initSegments:new $a}),this.trackContexts.set(e.type,g)),g.state==="initialized"?e.mimeType!==g.mimeType&&(yield g.sourceBuffer.changeType(e.mimeType)):this.trackContexts.set(e.type,Eu(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 pB(A.type,A.renditionId);e.state==="initialized"&&(e.mimeType=t);const g=sd({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 cc(e.renditionId,e.channelId);if(!g)throw pB(e.type,e.renditionId);if(g.state==="uninitialized")throw hc(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 E=g.previousSample;if(E&&E.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 E of A)"initData"in E&&(yield g.sourceBuffer.appendBuffer(E.data,E.initData));else{const E=ad(A,o++);yield g.sourceBuffer.appendBuffer(E)}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(),E=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 f=this.trackContexts.get(C);if(!f)throw pB(C);f.state==="initialized"&&t&&(f.mimeType=t,f.initSegments.set(g,B,o));const U={fragmented:!0,type:C,data:Q,initData:o,timestamp:E,duration:h,timescale:c,channelId:g,renditionId:B,isSync:l,codec:e,fragment:A,compositionTimeOffset:m};this.onCodedSample(U)});I(this,"onCodedSample",A=>{if(A.duration===0)return;const t=this.trackContexts.get(A.type);if(!t)throw pB(A.type,A.renditionId);if(!(!t.hasFirstSync&&!A.isSync)){if(this.hasAddedInitialPosterFrame&&A.isSync&&A.type==="video"){this.hasAddedInitialPosterFrame=!1;const e=S({},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||ru(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=Wn(!1,e,t.consecutiveQuotaExceededErrorCount,A.type);this.emitter.emit("error",g)}}else{const g=Wn(!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=rc(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(y)}}this.logger.debug("source ended")});this.logger=A,this.mediaElement=e,this.emitter=t}};I(iQ,"create",(A,t,e)=>{const g=new iQ(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 yo=iQ;const tE=(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},ru=(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],E=i.pendingSamples[Q+1];if(o&&(e.push(o),E)){if(tE(o,E))break;const c=(o.timestamp+o.duration)/o.timescale;if(E.timestamp/E.timescale-c>.1)break}if(Q===t-1)break}const B=e[0];if(!B)break;const C=i.previousSample?tE(i.previousSample,B):!0;yield A(e,C),i.pendingSamples=i.pendingSamples.slice(g+1),i.previousSample=e[e.length-1]}i.isWorkingOnPendingSamples=!1}),IQ=class IQ{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(IQ,"create",(A,t)=>new IQ(A,t));let fo=IQ;const gQ=class gQ{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=>void(this.targetBufferTime=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",E=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,E!==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)}};I(gQ,"create",(A,t,e,g)=>new gQ(A,t,e,g));let po=gQ;const Fo=()=>({upgradesFromLevel:[],downgradesFromLevel:[],bufferingRanges:[],activeRanges:[],decodeRate:Number.MAX_SAFE_INTEGER}),cu=()=>({levels:{},levelDowngrades:[],levelUpgrades:[],bufferFullness:0,general:Fo()}),sQ=class sQ{constructor(A,t){I(this,"minBufferFullnessLengthForRegression",6);I(this,"logger");I(this,"emitter");I(this,"timers",RA.create());I(this,"metrics",cu());I(this,"bufferFullness",new L(30));I(this,"bufferFullnessRegression");I(this,"currentLevel");I(this,"isSuspended",!1);I(this,"_fatalQosCount",0);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)});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.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,"activeRatios",()=>{const A=new Map,t=Vi(this.metrics.general.activeRanges);if(Object.entries(this.metrics.levels).forEach(([e,g])=>{A.set(e,t?Vi(g.activeRanges)/t:0)}),!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=Vi(this.metrics.general.bufferingRanges);if(Object.entries(this.metrics.levels).forEach(([e,g])=>{A.set(e,t?Vi(g.bufferingRanges)/t:0)}),!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=>mn(this.metrics.general.bufferingRanges,A));I(this,"timeSpentActiveLast",A=>mn(this.metrics.general.activeRanges,A));I(this,"timeSpentPlayingInAtLeastLevelRatio",A=>{var o,E,c,h;const t=this.timeSpentBuffering(),e=this.timeActive(),g=this.bufferingRatios(),B=this.activeRatios(),C=((E=(o=A.video)==null?void 0:o.bitRate)!=null?E: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,U;return((f=B.get(m.toString()))!=null?f:0)-((U=g.get(m.toString()))!=null?U:0)*Q+l},0)});I(this,"timeSpentBuffering",()=>Vi(this.metrics.general.bufferingRanges));I(this,"timeActive",()=>Vi(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,E,c,h,l,m,f,U,b,Y,N;const t=((Q=(C=(B=A.from)==null?void 0:B.video)==null?void 0:C.bitRate)!=null?Q:0)+((c=(E=(o=A.from)==null?void 0:o.audio)==null?void 0:E.bitRate)!=null?c:0),e=((m=(l=(h=A.to)==null?void 0:h.video)==null?void 0:l.bitRate)!=null?m:0)+((b=(U=(f=A.to)==null?void 0:f.audio)==null?void 0:U.bitRate)!=null?b: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 v=(Y=this.metrics.levels[t])!=null?Y:Fo();t<e?v.upgradesFromLevel.push(Date.now()):v.downgradesFromLevel.push(Date.now()),Ke(v.activeRanges);const T=v.bufferingRanges[v.bufferingRanges.length-1];g=!!T&&!T.end,Ke(v.bufferingRanges),this.metrics.levels[t]=v}if(A.to){const v=(N=this.metrics.levels[e])!=null?N:Fo();Oi(v.activeRanges),g&&Oi(v.bufferingRanges),this.metrics.levels[e]=v,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,"calculateLinearRegression",()=>vr(this.bufferFullness.items().map((A,t)=>({x:t,y:A}))));I(this,"stopBuffering",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Ke(A.bufferingRanges)}Ke(this.metrics.general.bufferingRanges)});I(this,"startBuffering",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Oi(A.bufferingRanges)}Oi(this.metrics.general.bufferingRanges)});I(this,"unsetActive",()=>{if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Ke(A.activeRanges)}Ke(this.metrics.general.activeRanges)});this.logger=t,this.emitter=A}get fatalQosCount(){return this._fatalQosCount}setActive(){if(this.currentLevel){const A=this.metrics.levels[this.currentLevel];A&&Oi(A.activeRanges)}Oi(this.metrics.general.activeRanges)}};I(sQ,"create",(A,t)=>new sQ(A,t));let Go=sQ;const BQ=class BQ{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&&Te(e))return e});I(this,"getAudioRenditions",A=>{const t=this.renditions.get(A);return t==null?void 0:t.filter(g=>Pe(g))});I(this,"getVideoRenditions",A=>{const t=this.renditions.get(A);return t==null?void 0:t.filter(g=>Te(g))});I(this,"getAudioRendition",(A,t=this.getCurrentSubscription().channelId)=>{const e=this.getRendition(A,t);if(e&&Pe(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,E,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:(E=A==null?void 0:A.audio)==null?void 0:E.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 E;const{channelId:e,initiator:g}=A,B=this.getRenditionLevel(t),C=new Set;((E=this.renditions.get(e))!=null?E:[]).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(Te).filter(h=>t&&h.codec===t.codec),Q=B.filter(Pe).filter(h=>e&&h.codec===e.codec&&h.language===e.language),o=Math.max(C.length,Q.length),E=[];for(let h=0;h<o;h++){const l=C[Math.min(C.length-1,h)],m=Q[Math.min(Q.length-1,h)];E.push({audio:m,video:l})}return E});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(BQ,"create",(A,t)=>new BQ(A,t));let ko=BQ;const yg=i=>JSON.parse(JSON.stringify(i)),hu=1e4,CQ=class CQ{constructor(A,t,e){I(this,"logger");I(this,"timers",new RA);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=yg(this.currentSubscription):this.currentSubscription=yg(A),this._isSwitchingSubscription=this.isNewSubscription()});I(this,"scheduleSubscriptionChange",()=>{this.targetSubscription=yg(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=yg(this.currentSubscription),this.emitter.emit("channel switch timeout",t))},hu),this.pendingSubscriptionTimeoutId=this.timers.setTimeout(()=>this.emitter.emit("send signal",{type:"subscribe",subscription:this.getTargetSubscription()}),0))});this.logger=A,this.targetSubscription=t,this.currentSubscription=yg(t),this.emitter=e,this.emitter.on("subscription changed",this.onSubscriptionChanged)}};I(CQ,"create",(A,t,e)=>new CQ(A,e,t));let Ro=CQ;const eE=5e3,du=()=>Ti()||pA()||VA(),iE=()=>du()?100:0,IE=i=>A=>A>i,QQ=class QQ{constructor(A,t,e,g,B){I(this,"emitter");I(this,"logger");I(this,"playbackSource");I(this,"bufferSource");I(this,"keyframeTimestamps",new L(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:iE(),minOvershootAllowed:iE(),maxOvershootAllowed:500});I(this,"maxTimeSyncDifferenceTolerance",150);I(this,"timers",RA.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-eE);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-eE);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(IE(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(IE(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 E=this.currentSyncMaxBehind;this.syncMaxBehindMultiplier+=this.syncMaxBehindMultiplierStep,E!==this.currentSyncMaxBehind&&this.logger.info("Increasing max drift behind allowed",{from:E,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(S({},t),{localTimestamp:e,timeDifferences:new L(12)}));return}const C=t.wallclockTime-g.wallclockTime,Q=t.timestamp-g.timestamp,o=e-g.localTimestamp,E=Q-o;if(g.timeDifferences.push(E),this.logger.debug("Timing info",{rtt:this.rtt,channelId:A,syncInfo:t,localTimestamp:e,diffFromEstimated:E,timestampDelta:Q,wallclockDelta:C,localWallclockDelta:o}),Math.abs(E)>=this.bufferSource.getTargetBufferTime()*2){this.logger.info("Resetting sync info",{diffFromEstimated:E}),this.channelSyncInfo.set(A,V(S({},t),{localTimestamp:e,timeDifferences:new L(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=Wi(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(QQ,"create",(A,t,e,g,B)=>new QQ(A,t,e,g,B));let Uo=QQ;const lu={enabled:!0,interval:3e4,includeErrors:!0,includeEvents:!0,includeStats:!0,maxRetries:10,maxErrorReports:50,maxEvents:50},No=(i,A)=>V(S({},A),{type:i,timestamp:new Date().toISOString(),discriminator:"web"}),oQ=class oQ{constructor(A,t,e,g){I(this,"logger");I(this,"timers",new RA);I(this,"emitter");I(this,"options");I(this,"parentContext");I(this,"unsentLines",new L(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=No("stats",V(S(S({},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=No("event",S(S({},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 Un(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 W){if(this.errorCount++,this.errorCount>e)return;const g=this.parentContext.getStatistics();this.unsentLines.push(No("error",S(S({},g),A.toStringifiable())))}});this.logger=A,this.emitter=t,this.options=S(S({},lu),e),this.parentContext=g}};I(oQ,"create",(A,t,e,g)=>new oQ(A,t,e,g));let oC=oQ;const nQ=class nQ{constructor(A,t,e){I(this,"logger");I(this,"element");I(this,"documentState");I(this,"timers",new RA);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(nQ,"create",(A,t,e)=>new nQ(A,t,e));let nC=nQ;const uu=6,wu=i=>{let A=[i],t=0,e=0,g=!1;const B=(Q,o)=>{var b,Y,N;Q.flags&&Sg(Q.flags)&&(t=(b=Q.compositionTimeOffset)!=null?b:0),Q.timestamp+=t,Q.compositionTimeOffset=((Y=Q.compositionTimeOffset)!=null?Y:0)-t;const E=Q.timestamp/Q.timescale,h=o.flags&&Sg(o.flags)?(N=o.compositionTimeOffset)!=null?N:0:t,m=(o.timestamp+h)/o.timescale,f=Math.max(0,Math.round((m-E)*Q.timescale));return f>0&&(e=f),V(S({},Q),{duration:f>0?f:e})};return(Q,o=!1)=>{if(Q.flags&&Sg(Q.flags)&&o&&(g=!g),!(o&&A.length<uu&&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),[]}},Du=(i,A,t)=>{if(Te(A))return S(V(S({},i),{type:"video",codec:A.codec,isSync:Sg(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(S({},i),{type:"audio",channels:A.channels,sampleRate:A.sampleRate,codec:A.codec,language:A.language,isSync:Sg(i.flags),data:i.payload,duration:0})};class Su{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,E,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((N,v)=>N.brand.localeCompare(v.brand));const m=[...(Q=this.highEntropyValues.fullVersionList)!=null?Q:[]];m.sort((N,v)=>N.brand.localeCompare(v.brand));const f=m.map(N=>N.version),U=l.map(N=>N.brand),b=l.map(N=>N.version),Y=parseInt((E=(o=this.highEntropyValues.platformVersion)==null?void 0:o.split(".")[0])!=null?E:"1");return S({userAgentLegacy:window.navigator.userAgent,ua:{browser:{brands:U,fullVersionBrands:f,majorVersions:b},device:this.highEntropyValues.model||"Other",os:{family:this.highEntropyValues.platform||"Other",version:(c=this.highEntropyValues.platformVersion)!=null?c:"1",major_version:Number.isFinite(Y)?Y:0}}},g)}else return S({userAgent:window.navigator.userAgent},g)}}const mu=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},st=class st extends $A{constructor(t){super();I(this,"pictureInPicture");I(this,"drm");I(this,"browser",yQ());I(this,"options");I(this,"element");I(this,"playbackSource");I(this,"emitter",new $A);I(this,"logger");I(this,"modules");I(this,"clientIp");I(this,"sessionId");I(this,"clientId",pn());I(this,"_channels",[]);I(this,"createdAt",Date.now());I(this,"hasCalledConnect",!1);I(this,"latestEmittedLanguages",[]);I(this,"wakeLock");I(this,"pool",new p(st.MAX_POOL_SIZE));I(this,"userAgentInformation",new Su);I(this,"encryptedMediaExtensions");n(this,Li,0);n(this,zA,[]);I(this,"sampleProcessingSesssions",new Map);I(this,"sizes",new Map);I(this,"isSuspended",!0);I(this,"disconnectTimeout");n(this,Ji);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 E;this.sessionId=pn();const e=this.modules.subscription.getTargetSubscription(),g=t.channels.find(c=>c.channelId===e.channelId);if(this.emitter.emit("connect info",t),this._channels=t.channels,this.updateTextTracks((E=g==null?void 0:g.renditions)!=null?E:[]),!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 On("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,zA).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,zA).push(C)}else if(this.mediaElement instanceof HTMLVideoElement){const C=this.mediaElement.addTextTrack(g.kind,g.label||g.language,g.language);s(this,zA).push(C)}}});for(const g of s(this,zA))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,zA).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(Pe(Q))return!0;if(!Te(Q)||!this.isSupportedVideoCodecProfile(Q.codec,Q.codecString))return!1;if(!this.willUseMediaSource()){const m=this.options.get("advanced"),f=(c=m.wasmDecodingConstraint.bitRate)!=null?c:Number.MAX_SAFE_INTEGER,U=(h=m.wasmDecodingConstraint.width)!=null?h:Number.MAX_SAFE_INTEGER,b=(l=m.wasmDecodingConstraint.height)!=null?l:Number.MAX_SAFE_INTEGER;return Q.bitRate<=f&&Q.width<=U&&Q.height<=b}const o=yield fd(Q);if(!o.supported||Q.codec=="av1"&&!o.smooth&&!o.powerEfficient)return!1;const E=this.options.getOverride("maxVideoBitRate",this.channelId);return E?E>=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=Math.min(this.options.get("maxVideoBitRate"),st.INITIAL_MAX_BIT_RATE,e,this.targetSubscription.video.bitRate),B=Math.min(this.options.get("maxAudioBitRate"),st.INITIAL_MAX_BIT_RATE,e,this.targetSubscription.audio.bitRate),C=this.options.get("media")==="audio"?[]:this.options.get("videoCodecs",this.channelId),Q=this.supportedAudioCodecs(),o=t.renditions.filter(Pe),E=t.renditions.filter(Te),c=Q.find(f=>o.find(U=>U.codec===f)!==void 0),h=C.find(f=>E.find(U=>U.codec===f)!==void 0),l=o.map(f=>f.language);if(this.logger.debug("supported and selected codecs",{audioCodecs:Q,videoCodecs:C,audioCodec:c,videoCodec:h}),h){const f=this.options.get("maxSize");this.modules.subscription.setVideoConstraint(S({codec:h,bitRate:this.abrEnabled?g:this.options.get("maxVideoBitRate")},f))}c&&(this.modules.subscription.setAudioConstraint({codec:c,bitRate:this.abrEnabled?B:this.options.get("maxAudioBitRate"),language:this.options.get("language")}),(!l.includes(this.options.get("language"))||this.language===void 0)&&this.modules.subscription.setLanguage(l[0])),this.alignSizeAndBitRate(this.targetSubscription);const m=this.modules.subscription.getTargetSubscription();this.emitter.emit("subscription changed",{to:m,from:this.modules.subscription.getCurrentSubscription()})});I(this,"isSupportedVideoCodecProfile",(t,e)=>{if(this.willUseMediaSource()){const g=ot();return g?g.isTypeSupported(xe({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.browser.supportsMp4Opus&&this.options.get("mseOpusEnabled")||!this.willUseMediaSource())&&t.push("opus"),this.willUseMediaSource()&&t.push("aac"),t});I(this,"initializeDecodingModule",()=>r(this,null,function*(){var g,B;const t=this.currentRenditionLevel,e=[];if(!t)throw new W("No currentRenditionLevel",{code:"no_current_rendition_level",isFatal:!1});if(t!=null&&t.video&&e.push({type:"video",mimeType:xe(t.video),codec:t.video.codec}),t!=null&&t.audio&&e.push({type:"audio",codec:t.audio.codec,mimeType:xe(t.audio)}),e.length===0)throw new W("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 p(st.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",()=>{yd(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(),st.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",()=>Object.values(this.modules).reduce((t,e)=>e&&"getStatistics"in e?S(S({},t),e.getStatistics()):t,this.getRuntimeInfo()));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 S({uptime:Date.now()-this.createdAt,version:"4.1.2-9-g04c36ea5",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 md(S(S({},ic),mc(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=kA.get();B.setLevel(this.options.get("logLevel")),B.setDebug(!1),this.logger=B;const C=fo.create(this.emitter,this.logger.createContext("PictureInPictureModule")),Q=RA.create(),o=no.create(this.emitter,this.logger.createContext("ConnectionModule"),{reconnectHandler:this.options.get("reconnectHandler"),options:this.options,onConnectInfo:this.onConnectInfo}),E=Ro.create(this.logger.createContext("SubscriptionModule"),this.emitter,g),c=ko.create(this.emitter,E),h=Go.create(this.emitter,this.logger.createContext("QualityOfServiceModule")),l=po.create(this.emitter,this.logger.createContext("PlaybackModule"),this,this.options.get("minBufferTime"));this.encryptedMediaExtensions=new ia(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),f=this.options.get("poster"),U=f===!0?this.getThumbnailUrl():f||void 0;let b,Y,N;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:U});w.on("buffer state",R=>this.emitter.emit("buffer state",R)),w.on("needs user input",R=>this.emitter.emit("needs user input",R)),w.on("volume state",R=>this.emit("volume state",R)),w.on("media element state",R=>this.onMediaElementState(R)),this.element=w.element,this.playbackSource=w,ia.isSupported()&&this.encryptedMediaExtensions.attach(w.element),b=yo.create(this.logger.createContext("MseModule"),this.emitter,this.element),this.options.get("pauseSupportEnabled")||(Y=nC.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=mo.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:U}),R=w.element();this.element=R.element,this.playbackSource=w,N=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")||(Y=nC.create(this.logger.createContext("UnpauseModule"),R,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,N=w,this.options.get("iosWakeLockEnabled")&&(this.wakeLock=new ud)}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 v=this.browser.platform.isIOS&&!this.browser.platform.isIpadOS,T=Uo.create(this.emitter,this.logger.createContext("SyncModule"),this.playbackSource,l,this.willUseMediaSource()&&!v),P=(this.options.get("edgeUrl")||this.options.get("url")).replace("wss://","https://").replace("ws://","http://").replace("//lb.","//errors."),X=new URL("/telemetry",P).toString(),yA=oC.create(this.logger.createContext("TelemetryModule"),this.emitter,{url:X,enabled:this.options.get("telemetryEnabled"),includeStats:!1,interval:5e3},this);this.modules={telemetry:yA,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,documentState:m,connection:o,playback:l,pictureInPicture:C,timer:Q,subscription:E,renditions:c,qualityOfService:h,mseModule:b,unpause:Y,canvasModule:N},this.modules.adaptivity.isEnabled=this.options.get("abrEnabled"),this.emitter.on("page active",w=>{var R;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(),(R=this.modules.canvasModule)==null||R.unsuspend()):this.modules.connection.disconnect():(this.disconnectTimeout&&this.modules.timer.clearInterval(this.disconnectTimeout),this.disconnectTimeout=this.modules.timer.setInterval(()=>{const x=this.playbackState==="paused"||this.muted;this.connectionState==="connected"&&x&&(this.emitter.emit("flush buffers"),this.modules.connection.disconnect("Page inactive timeout"))},st.DISCONNECT_TIMEOUT)))});let BA;this.emitter.on("context switch complete",()=>{BA||(BA=window.setTimeout(()=>{window.clearTimeout(BA),BA=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 eA,O,j;const x=((O=(eA=w.telemetry)==null?void 0:eA.probability)!=null?O:1)>=Math.random();w.telemetry&&((j=this.modules.telemetry)==null||j.unload(),this.modules.telemetry=oC.create(this.logger.createContext("TelemetryModule"),this.emitter,V(S({},w.telemetry),{enabled:this.options.get("telemetryEnabled")&&x}),this),this.modules.telemetry.load())}),this.emitter.on("adapt level",w=>{var MA,F,K,AA,CA;this.logger.debug("adapt level",{direction:w});const R=this.modules.renditions.getRenditionLevels(),x=this.modules.renditions.getRenditionLevel(),eA=R.findIndex(M=>M===x),O=R.length-1;let j=eA;switch(w){case"upgrade":{const M=Math.min(eA+1,O),sA=R[M],ng=(MA=this.modules.connection.estimatedBandwidth)!=null?MA:ne(),ag=((K=(F=sA==null?void 0:sA.audio)==null?void 0:F.bitRate)!=null?K:0)+((CA=(AA=sA==null?void 0:sA.video)==null?void 0:AA.bitRate)!=null?CA:0),cB=ng*2>ag;sA&&cB&&this.modules.adaptivity.isQoSOk(sA)&&(j=M)}break;case"downgrade":j=Math.max(eA-1,0);break;case"double downgrade":j=Math.max(eA-2,0);break;case"reconnect":if(eA===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 j=0}if(j===eA)return;const oA=R[j];this.alignSizeAndBitRate(V(S({},this.targetSubscription),{video:S(S({},this.targetSubscription.video),oA==null?void 0:oA.video),audio:S(S({},this.targetSubscription.audio),oA==null?void 0:oA.audio)})),this.emitter.emit("adapted level")}),this.emitter.on("text track data",w=>{const R=s(this,zA).find(j=>j.language===w.language),eA=this.modules.sync.getTimeshiftOffset()/1e3,O=eA-s(this,Li);if(a(this,Li,eA),R){if(R.cues)for(const j of R.cues)j.startTime-=O,j.endTime-=O;for(const j of w.cues){const oA=new VTTCue(j.startTime-eA,j.endTime-eA,j.text);R.addCue(oA)}}}),this.emitter.on("received signal",w=>{var eA;const R=w,x=this.modules.subscription.getCurrentSubscription();switch(this.logger.debug("received",S({},R)),R.type){case"client ip":this.clientIp=R.ip;break;case"renditions":this.updateTextTracks(R.renditions),a(this,Ji,this.filterRenditions(R.renditions).then(O=>{this.emitter.emit("renditions",{renditions:O,channelId:this.currentSubscription.channelId}),this.emit("rendition levels",this.modules.renditions.getRenditionLevels()),this.emitLanguagesIfChanged()}).finally(()=>{a(this,Ji,void 0)}));break;case"subscription changed":try{mu(R.subscription)}catch(O){this.emitter.emit("error",new W("Subscription failed validation",{source:O instanceof Error?O:void 0,isFatal:!1,code:"subscription_failed_validation"}))}this.emitter.emit("subscription changed",{reset:R.reset,to:R.subscription,from:this.modules.subscription.getCurrentSubscription()}),R.reset&&x.channelId!==R.subscription.channelId&&(this.emit("error",Xn(R.subscription.channelId)),this.emit("channel switch failed",{channelId:x.channelId})),this.modules.sync.timeshiftOnAudio=!((eA=R.subscription.video)!=null&&eA.codec),this.modules.adaptivity.reset();break;case"timing info":this.modules.sync.updateChannelSyncInfo(R.timingInfo.channelId,R.timingInfo),this.emit("server wallclock time",R.timingInfo.wallclockTime);break}}),this.emitter.on("channel switch timeout",w=>{this.emit("error",Xn(w)),this.emit("channel switch failed",{channelId:this.currentSubscription.channelId})}),this.emitter.on("received data",w=>{const R=this.modules.subscription.getCurrentSubscription(),x=dd(w);if(!R){this.logger.warn("Received unwanted message",S({},x));return}Bt(V(S({},x),{channelId:R.channelId}))}),this.emitter.on("received moq data",w=>{var j,oA,MA;const R=w.payload.mediaType(),x=w.channelId,eA=w.renditionId,O=this.modules.sync.processFragment(x,w.payload);if(w.switchInfo.channelId&&(w.switchInfo.drmTransition&&this.emitter.emit("error",jn("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(R,w.payload.rawBytes().byteLength),O.fragment().emsgs.forEach(F=>{if(!F.presentationTime)return;const K=xc(F.data);K&&this.modules.event.addEvent({id:F.id,timestamp:F.presentationTime/F.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:K.txx.value,type:"metadata"})}),this.modules.decoder){const F=(j=O.header().init().moov.traks[0])==null?void 0:j.mdia.minf.stbl.stsd,K=(oA=F==null?void 0:F.avc1)==null?void 0:oA.avcC.bytes,AA=(MA=F==null?void 0:F.codec)!=null?MA:"h264";if(K){const CA=K.buffer.slice(K.byteOffset,K.byteOffset+K.byteLength);if(R==="text")throw new Error("Subtitles are not supported");this.emitter.emit("init segment",{initSegment:{channelId:x,renditionId:eA,data:CA,timescale:1e3,type:R,codec:AA},mimeType:R})}for(let CA=0;CA<O.samplesCount();CA++){const M=O.sample(CA);M&&this.emitter.emit("coded sample",V(S({},M),{renditionId:eA,channelId:x,data:M.data.buffer.slice(M.data.byteOffset,M.data.byteOffset+M.data.byteLength)}))}}else this.emitter.emit("fragment",{mimeType:w.mimeType,codec:w.codec,fragment:O,channelId:x,renditionId:eA})});const fA=this.options.get("container");fA&&this.attach(fA),this.logger.info("Created Vindral instance",{options:this.options});const Bt=w=>r(this,null,function*(){const R=w.channelId;s(this,Ji)&&(yield s(this,Ji));const x=this.modules.renditions.getRendition(w.renditionId,R);if(!rd(w.flags)){if(cd(w.flags)){const O=new TextDecoder().decode(w.payload),j=this.modules.sync.getTimeshiftOffset();if(w.renditionId!==0){const oA=fn(O);if(oA&&oA.language!==void 0){const F=new ha().parse(oA.content||""),K=j/1e3,AA=s(this,zA).find(M=>M.language===oA.language),CA=K-s(this,Li);if(a(this,Li,K),AA){if(AA.cues)for(const M of AA.cues)M.startTime-=CA,M.endTime-=CA;for(const M of F){const sA=new VTTCue(M.startTime-K,M.endTime-K,M.text);AA.addCue(sA)}}}}else this.modules.event.addEvent({timestamp:w.timestamp/w.timescale*1e3-this.modules.sync.getTimeshiftOffset(),content:O,type:"metadata"})}else if(x!=null&&x.codec){const eA=D(x.codec);if(eA==="text")throw new Error("Subtitles are not supported");if(this.modules.incomingData.add(eA,w.payload.byteLength),Ed(w.flags)){const O=V(S({type:eA,data:w.payload,codec:x.codec},w),{channelId:R}),j=Bd(O.codec,O.payload);j&&this.sizes.set(O.renditionId,j);const oA=xe({codec:x.codec,codecString:x.codecString});this.emitter.emit("init segment",{initSegment:O,mimeType:oA}),this.emit("initialized media")}else{const O=Du(w,x,this.sizes.get(w.renditionId));let j=this.sampleProcessingSesssions.get(eA);if(!j)j=wu(this.modules.sync.processSample(O)),this.sampleProcessingSesssions.set(eA,j);else{const oA=j(this.modules.sync.processSample(O),this.isSwitchingRenditionLevel&&O.type==="video");let MA=O;oA.forEach(F=>{this.modules.event.extractEvent(F,MA),this.emitter.emit("coded sample",F),MA=F})}}}}});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"),fB())||(this.maxSize=this.options.get("maxSize")),this.options.get("burstEnabled")&&E.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,zA).forEach(e=>{e.label===t?e.mode="showing":e.mode="hidden"}),this.emitter.emit("text track",t)}get textTracks(){return s(this,zA).filter(t=>t.mode!=="disabled").map(t=>t.label)}get textTrack(){var t;return(t=s(this,zA).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(E=>E.language===C),o=e.find(E=>(B==null?void 0:B.find(c=>c.codec===E))!==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:fB();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:ne()}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:ne()}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(S({},t),{video:S({},t.video),audio:S({},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),E=C==null?void 0:C.find(h=>h.language),c=(C==null?void 0:C.length)&&C[0]||void 0;o||(E?(this.logger.debug("Randomizing language since target did not have current language"),this.modules.subscription.setAudioBitRate(E.bitRate),this.modules.subscription.setLanguage(E.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")}};Li=new WeakMap,zA=new WeakMap,Ji=new WeakMap,I(st,"MAX_POOL_SIZE",10),I(st,"INITIAL_MAX_BIT_RATE",2.5*1e3*1e3),I(st,"DISCONNECT_TIMEOUT",15*1e3),I(st,"REMOVE_CUE_THRESHOLD",1e3*10);let aC=st;const EC={buffering:"_buffering_1ccif_1","buffering-fullscreen":"_buffering-fullscreen_1ccif_16",hidden:"_hidden_1ccif_25","buffering-indicator":"_buffering-indicator_1ccif_31"};class At{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 bo=EC.hidden,yu=EC.buffering,gE=EC["buffering-fullscreen"],fu=EC["buffering-indicator"];class sE extends At{constructor(){super(document.createElement("div"));I(this,"indicator",document.createElement("div"));I(this,"isHidden",()=>this.element.classList.contains(bo));I(this,"setHidden",t=>t?this.hide():this.show());I(this,"hide",()=>this.element.classList.add(bo));I(this,"show",()=>this.element.classList.remove(bo));I(this,"fullscreen",t=>{t?this.element.classList.add(gE):this.element.classList.remove(gE)});this.element.className=yu,this.indicator.className=fu,this.element.appendChild(this.indicator)}}class BE extends $A{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}})}}const CE={bar:"_bar_zames_1",hidden:"_hidden_zames_45"},fg={"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"},pu={"icon-button":"_icon-button_5fg7v_1"},QE={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>