@vkontakte/videoplayer-core 2.0.111-dev.2c18acf4.0 → 2.0.111-dev.974e99b3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2018.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.111-dev.2c18acf4.0
3
- * Mon, 16 Sep 2024 09:48:10 GMT
2
+ * @vkontakte/videoplayer-core v2.0.111-dev.974e99b3.0
3
+ * Thu, 19 Sep 2024 08:04:36 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-111/doc/
5
5
  */
6
- var tv=Object.create;var Cc=Object.defineProperty;var rv=Object.getOwnPropertyDescriptor;var iv=Object.getOwnPropertyNames;var av=Object.getPrototypeOf,sv=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var nv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of iv(e))!sv.call(a,i)&&i!==t&&Cc(a,i,{get:()=>e[i],enumerable:!(r=rv(e,i))||r.enumerable});return a};var He=(a,e,t)=>(t=a!=null?tv(av(a)):{},nv(e||!a||!a.__esModule?Cc(t,"default",{value:a,enumerable:!0}):t,a));var ve=m((eL,qc)=>{"use strict";qc.exports=function(a){try{return!!a()}catch(e){return!0}}});var qr=m((tL,Uc)=>{"use strict";var fv=ve();Uc.exports=!fv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ce=m((rL,Gc)=>{"use strict";var Hc=qr(),jc=Function.prototype,mn=jc.call,mv=Hc&&jc.bind.bind(mn,mn);Gc.exports=Hc?mv:function(a){return function(){return mn.apply(a,arguments)}}});var tr=m((iL,Yc)=>{"use strict";var Wc=ce(),bv=Wc({}.toString),gv=Wc("".slice);Yc.exports=function(a){return gv(bv(a),8,-1)}});var zc=m((aL,Qc)=>{"use strict";var Sv=ce(),vv=ve(),yv=tr(),bn=Object,Tv=Sv("".split);Qc.exports=vv(function(){return!bn("z").propertyIsEnumerable(0)})?function(a){return yv(a)==="String"?Tv(a,""):bn(a)}:bn});var rr=m((sL,Kc)=>{"use strict";Kc.exports=function(a){return a==null}});var Ur=m((nL,Jc)=>{"use strict";var Iv=rr(),Ev=TypeError;Jc.exports=function(a){if(Iv(a))throw new Ev("Can't call method on "+a);return a}});var ir=m((oL,Xc)=>{"use strict";var xv=zc(),Pv=Ur();Xc.exports=function(a){return xv(Pv(a))}});var gn=m((uL,Zc)=>{"use strict";Zc.exports=function(){}});var $t=m((cL,el)=>{"use strict";el.exports={}});var Y=m((Sn,tl)=>{"use strict";var Hr=function(a){return a&&a.Math===Math&&a};tl.exports=Hr(typeof globalThis=="object"&&globalThis)||Hr(typeof window=="object"&&window)||Hr(typeof self=="object"&&self)||Hr(typeof global=="object"&&global)||Hr(typeof Sn=="object"&&Sn)||function(){return this}()||Function("return this")()});var W=m((lL,rl)=>{"use strict";var vn=typeof document=="object"&&document.all;rl.exports=typeof vn=="undefined"&&vn!==void 0?function(a){return typeof a=="function"||a===vn}:function(a){return typeof a=="function"}});var sl=m((dL,al)=>{"use strict";var Av=Y(),wv=W(),il=Av.WeakMap;al.exports=wv(il)&&/native code/.test(String(il))});var Pe=m((pL,nl)=>{"use strict";var kv=W();nl.exports=function(a){return typeof a=="object"?a!==null:kv(a)}});var Ae=m((hL,ol)=>{"use strict";var Rv=ve();ol.exports=!Rv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ea=m((fL,cl)=>{"use strict";var $v=Y(),ul=Pe(),yn=$v.document,Lv=ul(yn)&&ul(yn.createElement);cl.exports=function(a){return Lv?yn.createElement(a):{}}});var Tn=m((mL,ll)=>{"use strict";var Mv=Ae(),Cv=ve(),Dv=Ea();ll.exports=!Mv&&!Cv(function(){return Object.defineProperty(Dv("div"),"a",{get:function(){return 7}}).a!==7})});var In=m((bL,dl)=>{"use strict";var Bv=Ae(),Ov=ve();dl.exports=Bv&&Ov(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var je=m((gL,pl)=>{"use strict";var Vv=Pe(),_v=String,Nv=TypeError;pl.exports=function(a){if(Vv(a))return a;throw new Nv(_v(a)+" is not an object")}});var ye=m((SL,hl)=>{"use strict";var Fv=qr(),xa=Function.prototype.call;hl.exports=Fv?xa.bind(xa):function(){return xa.apply(xa,arguments)}});var Pa=m((vL,fl)=>{"use strict";fl.exports={}});var Ye=m((yL,bl)=>{"use strict";var En=Pa(),xn=Y(),qv=W(),ml=function(a){return qv(a)?a:void 0};bl.exports=function(a,e){return arguments.length<2?ml(En[a])||ml(xn[a]):En[a]&&En[a][e]||xn[a]&&xn[a][e]}});var jr=m((TL,gl)=>{"use strict";var Uv=ce();gl.exports=Uv({}.isPrototypeOf)});var ar=m((IL,yl)=>{"use strict";var Hv=Y(),Sl=Hv.navigator,vl=Sl&&Sl.userAgent;yl.exports=vl?String(vl):""});var An=m((EL,Al)=>{"use strict";var Pl=Y(),Pn=ar(),Tl=Pl.process,Il=Pl.Deno,El=Tl&&Tl.versions||Il&&Il.version,xl=El&&El.v8,Be,Aa;xl&&(Be=xl.split("."),Aa=Be[0]>0&&Be[0]<4?1:+(Be[0]+Be[1]));!Aa&&Pn&&(Be=Pn.match(/Edge\/(\d+)/),(!Be||Be[1]>=74)&&(Be=Pn.match(/Chrome\/(\d+)/),Be&&(Aa=+Be[1])));Al.exports=Aa});var wn=m((xL,kl)=>{"use strict";var wl=An(),jv=ve(),Gv=Y(),Wv=Gv.String;kl.exports=!!Object.getOwnPropertySymbols&&!jv(function(){var a=Symbol("symbol detection");return!Wv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&wl&&wl<41})});var kn=m((PL,Rl)=>{"use strict";var Yv=wn();Rl.exports=Yv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Rn=m((AL,$l)=>{"use strict";var Qv=Ye(),zv=W(),Kv=jr(),Jv=kn(),Xv=Object;$l.exports=Jv?function(a){return typeof a=="symbol"}:function(a){var e=Qv("Symbol");return zv(e)&&Kv(e.prototype,Xv(a))}});var Gr=m((wL,Ll)=>{"use strict";var Zv=String;Ll.exports=function(a){try{return Zv(a)}catch(e){return"Object"}}});var Qe=m((kL,Ml)=>{"use strict";var ey=W(),ty=Gr(),ry=TypeError;Ml.exports=function(a){if(ey(a))return a;throw new ry(ty(a)+" is not a function")}});var Wr=m((RL,Cl)=>{"use strict";var iy=Qe(),ay=rr();Cl.exports=function(a,e){var t=a[e];return ay(t)?void 0:iy(t)}});var Bl=m(($L,Dl)=>{"use strict";var $n=ye(),Ln=W(),Mn=Pe(),sy=TypeError;Dl.exports=function(a,e){var t,r;if(e==="string"&&Ln(t=a.toString)&&!Mn(r=$n(t,a))||Ln(t=a.valueOf)&&!Mn(r=$n(t,a))||e!=="string"&&Ln(t=a.toString)&&!Mn(r=$n(t,a)))return r;throw new sy("Can't convert object to primitive value")}});var Oe=m((LL,Ol)=>{"use strict";Ol.exports=!0});var Nl=m((ML,_l)=>{"use strict";var Vl=Y(),ny=Object.defineProperty;_l.exports=function(a,e){try{ny(Vl,a,{value:e,configurable:!0,writable:!0})}catch(t){Vl[a]=e}return e}});var Yr=m((CL,Ul)=>{"use strict";var oy=Oe(),uy=Y(),cy=Nl(),Fl="__core-js_shared__",ql=Ul.exports=uy[Fl]||cy(Fl,{});(ql.versions||(ql.versions=[])).push({version:"3.38.0",mode:oy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Cn=m((DL,jl)=>{"use strict";var Hl=Yr();jl.exports=function(a,e){return Hl[a]||(Hl[a]=e||{})}});var Qr=m((BL,Gl)=>{"use strict";var ly=Ur(),dy=Object;Gl.exports=function(a){return dy(ly(a))}});var Ve=m((OL,Wl)=>{"use strict";var py=ce(),hy=Qr(),fy=py({}.hasOwnProperty);Wl.exports=Object.hasOwn||function(e,t){return fy(hy(e),t)}});var Dn=m((VL,Yl)=>{"use strict";var my=ce(),by=0,gy=Math.random(),Sy=my(1 .toString);Yl.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Sy(++by+gy,36)}});var te=m((_L,zl)=>{"use strict";var vy=Y(),yy=Cn(),Ql=Ve(),Ty=Dn(),Iy=wn(),Ey=kn(),sr=vy.Symbol,Bn=yy("wks"),xy=Ey?sr.for||sr:sr&&sr.withoutSetter||Ty;zl.exports=function(a){return Ql(Bn,a)||(Bn[a]=Iy&&Ql(sr,a)?sr[a]:xy("Symbol."+a)),Bn[a]}});var Zl=m((NL,Xl)=>{"use strict";var Py=ye(),Kl=Pe(),Jl=Rn(),Ay=Wr(),wy=Bl(),ky=te(),Ry=TypeError,$y=ky("toPrimitive");Xl.exports=function(a,e){if(!Kl(a)||Jl(a))return a;var t=Ay(a,$y),r;if(t){if(e===void 0&&(e="default"),r=Py(t,a,e),!Kl(r)||Jl(r))return r;throw new Ry("Can't convert object to primitive value")}return e===void 0&&(e="number"),wy(a,e)}});var On=m((FL,ed)=>{"use strict";var Ly=Zl(),My=Rn();ed.exports=function(a){var e=Ly(a,"string");return My(e)?e:e+""}});var Lt=m(rd=>{"use strict";var Cy=Ae(),Dy=Tn(),By=In(),wa=je(),td=On(),Oy=TypeError,Vn=Object.defineProperty,Vy=Object.getOwnPropertyDescriptor,_n="enumerable",Nn="configurable",Fn="writable";rd.f=Cy?By?function(e,t,r){if(wa(e),t=td(t),wa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Fn in r&&!r[Fn]){var i=Vy(e,t);i&&i[Fn]&&(e[t]=r.value,r={configurable:Nn in r?r[Nn]:i[Nn],enumerable:_n in r?r[_n]:i[_n],writable:!1})}return Vn(e,t,r)}:Vn:function(e,t,r){if(wa(e),t=td(t),wa(r),Dy)try{return Vn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Oy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var zr=m((UL,id)=>{"use strict";id.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var nr=m((HL,ad)=>{"use strict";var _y=Ae(),Ny=Lt(),Fy=zr();ad.exports=_y?function(a,e,t){return Ny.f(a,e,Fy(1,t))}:function(a,e,t){return a[e]=t,a}});var ka=m((jL,nd)=>{"use strict";var qy=Cn(),Uy=Dn(),sd=qy("keys");nd.exports=function(a){return sd[a]||(sd[a]=Uy(a))}});var Ra=m((GL,od)=>{"use strict";od.exports={}});var jn=m((WL,ld)=>{"use strict";var Hy=sl(),cd=Y(),jy=Pe(),Gy=nr(),qn=Ve(),Un=Yr(),Wy=ka(),Yy=Ra(),ud="Object already initialized",Hn=cd.TypeError,Qy=cd.WeakMap,$a,Kr,La,zy=function(a){return La(a)?Kr(a):$a(a,{})},Ky=function(a){return function(e){var t;if(!jy(e)||(t=Kr(e)).type!==a)throw new Hn("Incompatible receiver, "+a+" required");return t}};Hy||Un.state?(_e=Un.state||(Un.state=new Qy),_e.get=_e.get,_e.has=_e.has,_e.set=_e.set,$a=function(a,e){if(_e.has(a))throw new Hn(ud);return e.facade=a,_e.set(a,e),e},Kr=function(a){return _e.get(a)||{}},La=function(a){return _e.has(a)}):(Mt=Wy("state"),Yy[Mt]=!0,$a=function(a,e){if(qn(a,Mt))throw new Hn(ud);return e.facade=a,Gy(a,Mt,e),e},Kr=function(a){return qn(a,Mt)?a[Mt]:{}},La=function(a){return qn(a,Mt)});var _e,Mt;ld.exports={set:$a,get:Kr,has:La,enforce:zy,getterFor:Ky}});var Gn=m((YL,fd)=>{"use strict";var Jy=qr(),hd=Function.prototype,dd=hd.apply,pd=hd.call;fd.exports=typeof Reflect=="object"&&Reflect.apply||(Jy?pd.bind(dd):function(){return pd.apply(dd,arguments)})});var Wn=m((QL,md)=>{"use strict";var Xy=tr(),Zy=ce();md.exports=function(a){if(Xy(a)==="Function")return Zy(a)}});var vd=m(Sd=>{"use strict";var bd={}.propertyIsEnumerable,gd=Object.getOwnPropertyDescriptor,eT=gd&&!bd.call({1:2},1);Sd.f=eT?function(e){var t=gd(this,e);return!!t&&t.enumerable}:bd});var Id=m(Td=>{"use strict";var tT=Ae(),rT=ye(),iT=vd(),aT=zr(),sT=ir(),nT=On(),oT=Ve(),uT=Tn(),yd=Object.getOwnPropertyDescriptor;Td.f=tT?yd:function(e,t){if(e=sT(e),t=nT(t),uT)try{return yd(e,t)}catch(r){}if(oT(e,t))return aT(!rT(iT.f,e,t),e[t])}});var Yn=m((JL,Ed)=>{"use strict";var cT=ve(),lT=W(),dT=/#|\.prototype\./,Jr=function(a,e){var t=hT[pT(a)];return t===mT?!0:t===fT?!1:lT(e)?cT(e):!!e},pT=Jr.normalize=function(a){return String(a).replace(dT,".").toLowerCase()},hT=Jr.data={},fT=Jr.NATIVE="N",mT=Jr.POLYFILL="P";Ed.exports=Jr});var Xr=m((XL,Pd)=>{"use strict";var xd=Wn(),bT=Qe(),gT=qr(),ST=xd(xd.bind);Pd.exports=function(a,e){return bT(a),e===void 0?a:gT?ST(a,e):function(){return a.apply(e,arguments)}}});var we=m((ZL,wd)=>{"use strict";var Zr=Y(),vT=Gn(),yT=Wn(),TT=W(),IT=Id().f,ET=Yn(),or=Pa(),xT=Xr(),ur=nr(),Ad=Ve();Yr();var PT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return vT(a,this,arguments)};return e.prototype=a.prototype,e};wd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Zr:i?Zr[t]:Zr[t]&&Zr[t].prototype,o=r?or:or[t]||ur(or,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,y;for(p in e)c=ET(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Ad(n,p),f=o[p],l&&(a.dontCallGetSet?(y=IT(n,p),b=y&&y.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&l?g=xT(h,Zr):a.wrap&&l?g=PT(h):s&&TT(h)?g=yT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&ur(g,"sham",!0),ur(o,p,g),s&&(d=t+"Prototype",Ad(or,d)||ur(or,d,{}),ur(or[d],p,h),a.real&&u&&(c||!u[p])&&ur(u,p,h)))}});var $d=m((eM,Rd)=>{"use strict";var Qn=Ae(),AT=Ve(),kd=Function.prototype,wT=Qn&&Object.getOwnPropertyDescriptor,zn=AT(kd,"name"),kT=zn&&function(){}.name==="something",RT=zn&&(!Qn||Qn&&wT(kd,"name").configurable);Rd.exports={EXISTS:zn,PROPER:kT,CONFIGURABLE:RT}});var Md=m((tM,Ld)=>{"use strict";var $T=Math.ceil,LT=Math.floor;Ld.exports=Math.trunc||function(e){var t=+e;return(t>0?LT:$T)(t)}});var Ma=m((rM,Cd)=>{"use strict";var MT=Md();Cd.exports=function(a){var e=+a;return e!==e||e===0?0:MT(e)}});var Bd=m((iM,Dd)=>{"use strict";var CT=Ma(),DT=Math.max,BT=Math.min;Dd.exports=function(a,e){var t=CT(a);return t<0?DT(t+e,0):BT(t,e)}});var Vd=m((aM,Od)=>{"use strict";var OT=Ma(),VT=Math.min;Od.exports=function(a){var e=OT(a);return e>0?VT(e,9007199254740991):0}});var Ca=m((sM,_d)=>{"use strict";var _T=Vd();_d.exports=function(a){return _T(a.length)}});var qd=m((nM,Fd)=>{"use strict";var NT=ir(),FT=Bd(),qT=Ca(),Nd=function(a){return function(e,t,r){var i=NT(e),s=qT(i);if(s===0)return!a&&-1;var n=FT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Fd.exports={includes:Nd(!0),indexOf:Nd(!1)}});var jd=m((oM,Hd)=>{"use strict";var UT=ce(),Kn=Ve(),HT=ir(),jT=qd().indexOf,GT=Ra(),Ud=UT([].push);Hd.exports=function(a,e){var t=HT(a),r=0,i=[],s;for(s in t)!Kn(GT,s)&&Kn(t,s)&&Ud(i,s);for(;e.length>r;)Kn(t,s=e[r++])&&(~jT(i,s)||Ud(i,s));return i}});var Jn=m((uM,Gd)=>{"use strict";Gd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Yd=m((cM,Wd)=>{"use strict";var WT=jd(),YT=Jn();Wd.exports=Object.keys||function(e){return WT(e,YT)}});var zd=m(Qd=>{"use strict";var QT=Ae(),zT=In(),KT=Lt(),JT=je(),XT=ir(),ZT=Yd();Qd.f=QT&&!zT?Object.defineProperties:function(e,t){JT(e);for(var r=XT(t),i=ZT(t),s=i.length,n=0,o;s>n;)KT.f(e,o=i[n++],r[o]);return e}});var Xn=m((dM,Kd)=>{"use strict";var eI=Ye();Kd.exports=eI("document","documentElement")});var ro=m((pM,ip)=>{"use strict";var tI=je(),rI=zd(),Jd=Jn(),iI=Ra(),aI=Xn(),sI=Ea(),nI=ka(),Xd=">",Zd="<",eo="prototype",to="script",tp=nI("IE_PROTO"),Zn=function(){},rp=function(a){return Zd+to+Xd+a+Zd+"/"+to+Xd},ep=function(a){a.write(rp("")),a.close();var e=a.parentWindow.Object;return a=null,e},oI=function(){var a=sI("iframe"),e="java"+to+":",t;return a.style.display="none",aI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(rp("document.F=Object")),t.close(),t.F},Da,Ba=function(){try{Da=new ActiveXObject("htmlfile")}catch(e){}Ba=typeof document!="undefined"?document.domain&&Da?ep(Da):oI():ep(Da);for(var a=Jd.length;a--;)delete Ba[eo][Jd[a]];return Ba()};iI[tp]=!0;ip.exports=Object.create||function(e,t){var r;return e!==null?(Zn[eo]=tI(e),r=new Zn,Zn[eo]=null,r[tp]=e):r=Ba(),t===void 0?r:rI.f(r,t)}});var sp=m((hM,ap)=>{"use strict";var uI=ve();ap.exports=!uI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ao=m((fM,op)=>{"use strict";var cI=Ve(),lI=W(),dI=Qr(),pI=ka(),hI=sp(),np=pI("IE_PROTO"),io=Object,fI=io.prototype;op.exports=hI?io.getPrototypeOf:function(a){var e=dI(a);if(cI(e,np))return e[np];var t=e.constructor;return lI(t)&&e instanceof t?t.prototype:e instanceof io?fI:null}});var cr=m((mM,up)=>{"use strict";var mI=nr();up.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:mI(a,e,t),a}});var uo=m((bM,dp)=>{"use strict";var bI=ve(),gI=W(),SI=Pe(),vI=ro(),cp=ao(),yI=cr(),TI=te(),II=Oe(),oo=TI("iterator"),lp=!1,ze,so,no;[].keys&&(no=[].keys(),"next"in no?(so=cp(cp(no)),so!==Object.prototype&&(ze=so)):lp=!0);var EI=!SI(ze)||bI(function(){var a={};return ze[oo].call(a)!==a});EI?ze={}:II&&(ze=vI(ze));gI(ze[oo])||yI(ze,oo,function(){return this});dp.exports={IteratorPrototype:ze,BUGGY_SAFARI_ITERATORS:lp}});var Oa=m((gM,hp)=>{"use strict";var xI=te(),PI=xI("toStringTag"),pp={};pp[PI]="z";hp.exports=String(pp)==="[object z]"});var ei=m((SM,fp)=>{"use strict";var AI=Oa(),wI=W(),Va=tr(),kI=te(),RI=kI("toStringTag"),$I=Object,LI=Va(function(){return arguments}())==="Arguments",MI=function(a,e){try{return a[e]}catch(t){}};fp.exports=AI?Va:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=MI(e=$I(a),RI))=="string"?t:LI?Va(e):(r=Va(e))==="Object"&&wI(e.callee)?"Arguments":r}});var bp=m((vM,mp)=>{"use strict";var CI=Oa(),DI=ei();mp.exports=CI?{}.toString:function(){return"[object "+DI(this)+"]"}});var ti=m((yM,Sp)=>{"use strict";var BI=Oa(),OI=Lt().f,VI=nr(),_I=Ve(),NI=bp(),FI=te(),gp=FI("toStringTag");Sp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(_I(i,gp)||OI(i,gp,{configurable:!0,value:e}),r&&!BI&&VI(i,"toString",NI))}});var yp=m((TM,vp)=>{"use strict";var qI=uo().IteratorPrototype,UI=ro(),HI=zr(),jI=ti(),GI=$t(),WI=function(){return this};vp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=UI(qI,{next:HI(+!r,t)}),jI(a,i,!1,!0),GI[i]=WI,a}});var Ip=m((IM,Tp)=>{"use strict";var YI=ce(),QI=Qe();Tp.exports=function(a,e,t){try{return YI(QI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var xp=m((EM,Ep)=>{"use strict";var zI=Pe();Ep.exports=function(a){return zI(a)||a===null}});var Ap=m((xM,Pp)=>{"use strict";var KI=xp(),JI=String,XI=TypeError;Pp.exports=function(a){if(KI(a))return a;throw new XI("Can't set "+JI(a)+" as a prototype")}});var co=m((PM,wp)=>{"use strict";var ZI=Ip(),eE=Pe(),tE=Ur(),rE=Ap();wp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=ZI(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return tE(i),rE(s),eE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var _p=m((AM,Vp)=>{"use strict";var iE=we(),aE=ye(),_a=Oe(),Bp=$d(),sE=W(),nE=yp(),kp=ao(),Rp=co(),oE=ti(),uE=nr(),lo=cr(),cE=te(),$p=$t(),Op=uo(),lE=Bp.PROPER,dE=Bp.CONFIGURABLE,Lp=Op.IteratorPrototype,Na=Op.BUGGY_SAFARI_ITERATORS,ri=cE("iterator"),Mp="keys",ii="values",Cp="entries",Dp=function(){return this};Vp.exports=function(a,e,t,r,i,s,n){nE(t,e,r);var o=function(y){if(y===i&&p)return p;if(!Na&&y&&y in l)return l[y];switch(y){case Mp:return function(){return new t(this,y)};case ii:return function(){return new t(this,y)};case Cp:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[ri]||l["@@iterator"]||i&&l[i],p=!Na&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=kp(h.call(new a)),f!==Object.prototype&&f.next&&(!_a&&kp(f)!==Lp&&(Rp?Rp(f,Lp):sE(f[ri])||lo(f,ri,Dp)),oE(f,u,!0,!0),_a&&($p[u]=Dp))),lE&&i===ii&&d&&d.name!==ii&&(!_a&&dE?uE(l,"name",ii):(c=!0,p=function(){return aE(d,this)})),i)if(b={values:o(ii),keys:s?p:o(Mp),entries:o(Cp)},n)for(g in b)(Na||c||!(g in l))&&lo(l,g,b[g]);else iE({target:e,proto:!0,forced:Na||c},b);return(!_a||n)&&l[ri]!==p&&lo(l,ri,p,{name:i}),$p[e]=p,b}});var Fp=m((wM,Np)=>{"use strict";Np.exports=function(a,e){return{value:a,done:e}}});var ho=m((kM,Gp)=>{"use strict";var pE=ir(),po=gn(),qp=$t(),Hp=jn(),hE=Lt().f,fE=_p(),Fa=Fp(),mE=Oe(),bE=Ae(),jp="Array Iterator",gE=Hp.set,SE=Hp.getterFor(jp);Gp.exports=fE(Array,"Array",function(a,e){gE(this,{type:jp,target:pE(a),index:0,kind:e})},function(){var a=SE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Fa(void 0,!0);switch(a.kind){case"keys":return Fa(t,!1);case"values":return Fa(e[t],!1)}return Fa([t,e[t]],!1)},"values");var Up=qp.Arguments=qp.Array;po("keys");po("values");po("entries");if(!mE&&bE&&Up.name!=="values")try{hE(Up,"name",{value:"values"})}catch(a){}});var Yp=m((RM,Wp)=>{"use strict";var vE=te(),yE=$t(),TE=vE("iterator"),IE=Array.prototype;Wp.exports=function(a){return a!==void 0&&(yE.Array===a||IE[TE]===a)}});var fo=m(($M,zp)=>{"use strict";var EE=ei(),Qp=Wr(),xE=rr(),PE=$t(),AE=te(),wE=AE("iterator");zp.exports=function(a){if(!xE(a))return Qp(a,wE)||Qp(a,"@@iterator")||PE[EE(a)]}});var Jp=m((LM,Kp)=>{"use strict";var kE=ye(),RE=Qe(),$E=je(),LE=Gr(),ME=fo(),CE=TypeError;Kp.exports=function(a,e){var t=arguments.length<2?ME(a):e;if(RE(t))return $E(kE(t,a));throw new CE(LE(a)+" is not iterable")}});var eh=m((MM,Zp)=>{"use strict";var DE=ye(),Xp=je(),BE=Wr();Zp.exports=function(a,e,t){var r,i;Xp(a);try{if(r=BE(a,"return"),!r){if(e==="throw")throw t;return t}r=DE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Xp(r),t}});var Ua=m((CM,ah)=>{"use strict";var OE=Xr(),VE=ye(),_E=je(),NE=Gr(),FE=Yp(),qE=Ca(),th=jr(),UE=Jp(),HE=fo(),rh=eh(),jE=TypeError,qa=function(a,e){this.stopped=a,this.result=e},ih=qa.prototype;ah.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=OE(e,r),c,l,d,p,h,f,b,g=function(I){return c&&rh(c,"normal",I),new qa(!0,I)},y=function(I){return i?(_E(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)c=a.iterator;else if(n)c=a;else{if(l=HE(a),!l)throw new jE(NE(a)+" is not iterable");if(FE(l)){for(d=0,p=qE(a);p>d;d++)if(h=y(a[d]),h&&th(ih,h))return h;return new qa(!1)}c=UE(a,l)}for(f=s?a.next:c.next;!(b=VE(f,c)).done;){try{h=y(b.value)}catch(I){rh(c,"throw",I)}if(typeof h=="object"&&h&&th(ih,h))return h}return new qa(!1)}});var nh=m((DM,sh)=>{"use strict";var GE=Ae(),WE=Lt(),YE=zr();sh.exports=function(a,e,t){GE?WE.f(a,e,YE(0,t)):a[e]=t}});var oh=m(()=>{"use strict";var QE=we(),zE=Ua(),KE=nh();QE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return zE(e,function(r,i){KE(t,r,i)},{AS_ENTRIES:!0}),t}})});var ch=m((VM,uh)=>{"use strict";ho();oh();var JE=Pa();uh.exports=JE.Object.fromEntries});var dh=m((_M,lh)=>{"use strict";lh.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var hh=m(()=>{"use strict";ho();var XE=dh(),ZE=Y(),ex=ti(),ph=$t();for(Ha in XE)ex(ZE[Ha],Ha),ph[Ha]=ph.Array;var Ha});var mh=m((qM,fh)=>{"use strict";var tx=ch();hh();fh.exports=tx});var mo=m((UM,bh)=>{"use strict";var rx=mh();bh.exports=rx});var gh=m(()=>{"use strict"});var bo=m((GM,Sh)=>{"use strict";var ai=Y(),ix=ar(),ax=tr(),ja=function(a){return ix.slice(0,a.length)===a};Sh.exports=function(){return ja("Bun/")?"BUN":ja("Cloudflare-Workers")?"CLOUDFLARE":ja("Deno/")?"DENO":ja("Node.js/")?"NODE":ai.Bun&&typeof Bun.version=="string"?"BUN":ai.Deno&&typeof Deno.version=="object"?"DENO":ax(ai.process)==="process"?"NODE":ai.window&&ai.document?"BROWSER":"REST"}()});var Ga=m((WM,vh)=>{"use strict";var sx=bo();vh.exports=sx==="NODE"});var Th=m((YM,yh)=>{"use strict";var nx=Lt();yh.exports=function(a,e,t){return nx.f(a,e,t)}});var xh=m((QM,Eh)=>{"use strict";var ox=Ye(),ux=Th(),cx=te(),lx=Ae(),Ih=cx("species");Eh.exports=function(a){var e=ox(a);lx&&e&&!e[Ih]&&ux(e,Ih,{configurable:!0,get:function(){return this}})}});var Ah=m((zM,Ph)=>{"use strict";var dx=jr(),px=TypeError;Ph.exports=function(a,e){if(dx(e,a))return a;throw new px("Incorrect invocation")}});var So=m((KM,wh)=>{"use strict";var hx=ce(),fx=W(),go=Yr(),mx=hx(Function.toString);fx(go.inspectSource)||(go.inspectSource=function(a){return mx(a)});wh.exports=go.inspectSource});var Ch=m((JM,Mh)=>{"use strict";var bx=ce(),gx=ve(),kh=W(),Sx=ei(),vx=Ye(),yx=So(),Rh=function(){},$h=vx("Reflect","construct"),vo=/^\s*(?:class|function)\b/,Tx=bx(vo.exec),Ix=!vo.test(Rh),si=function(e){if(!kh(e))return!1;try{return $h(Rh,[],e),!0}catch(t){return!1}},Lh=function(e){if(!kh(e))return!1;switch(Sx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ix||!!Tx(vo,yx(e))}catch(t){return!0}};Lh.sham=!0;Mh.exports=!$h||gx(function(){var a;return si(si.call)||!si(Object)||!si(function(){a=!0})||a})?Lh:si});var Bh=m((XM,Dh)=>{"use strict";var Ex=Ch(),xx=Gr(),Px=TypeError;Dh.exports=function(a){if(Ex(a))return a;throw new Px(xx(a)+" is not a constructor")}});var yo=m((ZM,Vh)=>{"use strict";var Oh=je(),Ax=Bh(),wx=rr(),kx=te(),Rx=kx("species");Vh.exports=function(a,e){var t=Oh(a).constructor,r;return t===void 0||wx(r=Oh(t)[Rx])?e:Ax(r)}});var Nh=m((eC,_h)=>{"use strict";var $x=ce();_h.exports=$x([].slice)});var qh=m((tC,Fh)=>{"use strict";var Lx=TypeError;Fh.exports=function(a,e){if(a<e)throw new Lx("Not enough arguments");return a}});var To=m((rC,Uh)=>{"use strict";var Mx=ar();Uh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Mx)});var $o=m((iC,Jh)=>{"use strict";var Te=Y(),Cx=Gn(),Dx=Xr(),Hh=W(),Bx=Ve(),Kh=ve(),jh=Xn(),Ox=Nh(),Gh=Ea(),Vx=qh(),_x=To(),Nx=Ga(),wo=Te.setImmediate,ko=Te.clearImmediate,Fx=Te.process,Io=Te.Dispatch,qx=Te.Function,Wh=Te.MessageChannel,Ux=Te.String,Eo=0,ni={},Yh="onreadystatechange",oi,Ct,xo,Po;Kh(function(){oi=Te.location});var Ro=function(a){if(Bx(ni,a)){var e=ni[a];delete ni[a],e()}},Ao=function(a){return function(){Ro(a)}},Qh=function(a){Ro(a.data)},zh=function(a){Te.postMessage(Ux(a),oi.protocol+"//"+oi.host)};(!wo||!ko)&&(wo=function(e){Vx(arguments.length,1);var t=Hh(e)?e:qx(e),r=Ox(arguments,1);return ni[++Eo]=function(){Cx(t,void 0,r)},Ct(Eo),Eo},ko=function(e){delete ni[e]},Nx?Ct=function(a){Fx.nextTick(Ao(a))}:Io&&Io.now?Ct=function(a){Io.now(Ao(a))}:Wh&&!_x?(xo=new Wh,Po=xo.port2,xo.port1.onmessage=Qh,Ct=Dx(Po.postMessage,Po)):Te.addEventListener&&Hh(Te.postMessage)&&!Te.importScripts&&oi&&oi.protocol!=="file:"&&!Kh(zh)?(Ct=zh,Te.addEventListener("message",Qh,!1)):Yh in Gh("script")?Ct=function(a){jh.appendChild(Gh("script"))[Yh]=function(){jh.removeChild(this),Ro(a)}}:Ct=function(a){setTimeout(Ao(a),0)});Jh.exports={set:wo,clear:ko}});var ef=m((aC,Zh)=>{"use strict";var Xh=Y(),Hx=Ae(),jx=Object.getOwnPropertyDescriptor;Zh.exports=function(a){if(!Hx)return Xh[a];var e=jx(Xh,a);return e&&e.value}});var Lo=m((sC,rf)=>{"use strict";var tf=function(){this.head=null,this.tail=null};tf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};rf.exports=tf});var sf=m((nC,af)=>{"use strict";var Gx=ar();af.exports=/ipad|iphone|ipod/i.test(Gx)&&typeof Pebble!="undefined"});var of=m((oC,nf)=>{"use strict";var Wx=ar();nf.exports=/web0s(?!.*chrome)/i.test(Wx)});var ff=m((uC,hf)=>{"use strict";var dr=Y(),Yx=ef(),uf=Xr(),Mo=$o().set,Qx=Lo(),zx=To(),Kx=sf(),Jx=of(),Co=Ga(),cf=dr.MutationObserver||dr.WebKitMutationObserver,lf=dr.document,df=dr.process,Wa=dr.Promise,Oo=Yx("queueMicrotask"),lr,Do,Bo,Ya,pf;Oo||(ui=new Qx,ci=function(){var a,e;for(Co&&(a=df.domain)&&a.exit();e=ui.get();)try{e()}catch(t){throw ui.head&&lr(),t}a&&a.enter()},!zx&&!Co&&!Jx&&cf&&lf?(Do=!0,Bo=lf.createTextNode(""),new cf(ci).observe(Bo,{characterData:!0}),lr=function(){Bo.data=Do=!Do}):!Kx&&Wa&&Wa.resolve?(Ya=Wa.resolve(void 0),Ya.constructor=Wa,pf=uf(Ya.then,Ya),lr=function(){pf(ci)}):Co?lr=function(){df.nextTick(ci)}:(Mo=uf(Mo,dr),lr=function(){Mo(ci)}),Oo=function(a){ui.head||lr(),ui.add(a)});var ui,ci;hf.exports=Oo});var bf=m((cC,mf)=>{"use strict";mf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Qa=m((lC,gf)=>{"use strict";gf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Dt=m((dC,Sf)=>{"use strict";var Xx=Y();Sf.exports=Xx.Promise});var pr=m((pC,If)=>{"use strict";var Zx=Y(),li=Dt(),eP=W(),tP=Yn(),rP=So(),iP=te(),vf=bo(),aP=Oe(),Vo=An(),yf=li&&li.prototype,sP=iP("species"),_o=!1,Tf=eP(Zx.PromiseRejectionEvent),nP=tP("Promise",function(){var a=rP(li),e=a!==String(li);if(!e&&Vo===66||aP&&!(yf.catch&&yf.finally))return!0;if(!Vo||Vo<51||!/native code/.test(a)){var t=new li(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[sP]=r,_o=t.then(function(){})instanceof r,!_o)return!0}return!e&&(vf==="BROWSER"||vf==="DENO")&&!Tf});If.exports={CONSTRUCTOR:nP,REJECTION_EVENT:Tf,SUBCLASSING:_o}});var hr=m((hC,xf)=>{"use strict";var Ef=Qe(),oP=TypeError,uP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new oP("Bad Promise constructor");e=r,t=i}),this.resolve=Ef(e),this.reject=Ef(t)};xf.exports.f=function(a){return new uP(a)}});var Hf=m(()=>{"use strict";var cP=we(),lP=Oe(),Xa=Ga(),dt=Y(),gr=ye(),Pf=cr(),Af=co(),dP=ti(),pP=xh(),hP=Qe(),Ja=W(),fP=Pe(),mP=Ah(),bP=yo(),Lf=$o().set,Ho=ff(),gP=bf(),SP=Qa(),vP=Lo(),Mf=jn(),Za=Dt(),jo=pr(),Cf=hr(),es="Promise",Df=jo.CONSTRUCTOR,yP=jo.REJECTION_EVENT,TP=jo.SUBCLASSING,No=Mf.getterFor(es),IP=Mf.set,fr=Za&&Za.prototype,Bt=Za,za=fr,Bf=dt.TypeError,Fo=dt.document,Go=dt.process,qo=Cf.f,EP=qo,xP=!!(Fo&&Fo.createEvent&&dt.dispatchEvent),Of="unhandledrejection",PP="rejectionhandled",wf=0,Vf=1,AP=2,Wo=1,_f=2,Ka,kf,wP,Rf,Nf=function(a){var e;return fP(a)&&Ja(e=a.then)?e:!1},Ff=function(a,e){var t=e.value,r=e.state===Vf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===_f&&RP(e),e.rejection=Wo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Bf("Promise-chain cycle")):(c=Nf(u))?gr(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},qf=function(a,e){a.notified||(a.notified=!0,Ho(function(){for(var t=a.reactions,r;r=t.get();)Ff(r,a);a.notified=!1,e&&!a.rejection&&kP(a)}))},Uf=function(a,e,t){var r,i;xP?(r=Fo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),dt.dispatchEvent(r)):r={promise:e,reason:t},!yP&&(i=dt["on"+a])?i(r):a===Of&&gP("Unhandled promise rejection",t)},kP=function(a){gr(Lf,dt,function(){var e=a.facade,t=a.value,r=$f(a),i;if(r&&(i=SP(function(){Xa?Go.emit("unhandledRejection",t,e):Uf(Of,e,t)}),a.rejection=Xa||$f(a)?_f:Wo,i.error))throw i.value})},$f=function(a){return a.rejection!==Wo&&!a.parent},RP=function(a){gr(Lf,dt,function(){var e=a.facade;Xa?Go.emit("rejectionHandled",e):Uf(PP,e,a.value)})},mr=function(a,e,t){return function(r){a(e,r,t)}},br=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=AP,qf(a,!0))},Uo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Bf("Promise can't be resolved itself");var r=Nf(e);r?Ho(function(){var i={done:!1};try{gr(r,e,mr(Uo,i,a),mr(br,i,a))}catch(s){br(i,s,a)}}):(a.value=e,a.state=Vf,qf(a,!1))}catch(i){br({done:!1},i,a)}}};if(Df&&(Bt=function(e){mP(this,za),hP(e),gr(Ka,this);var t=No(this);try{e(mr(Uo,t),mr(br,t))}catch(r){br(t,r)}},za=Bt.prototype,Ka=function(e){IP(this,{type:es,done:!1,notified:!1,parent:!1,reactions:new vP,rejection:!1,state:wf,value:void 0})},Ka.prototype=Pf(za,"then",function(e,t){var r=No(this),i=qo(bP(this,Bt));return r.parent=!0,i.ok=Ja(e)?e:!0,i.fail=Ja(t)&&t,i.domain=Xa?Go.domain:void 0,r.state===wf?r.reactions.add(i):Ho(function(){Ff(i,r)}),i.promise}),kf=function(){var a=new Ka,e=No(a);this.promise=a,this.resolve=mr(Uo,e),this.reject=mr(br,e)},Cf.f=qo=function(a){return a===Bt||a===wP?new kf(a):EP(a)},!lP&&Ja(Za)&&fr!==Object.prototype)){Rf=fr.then,TP||Pf(fr,"then",function(e,t){var r=this;return new Bt(function(i,s){gr(Rf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete fr.constructor}catch(a){}Af&&Af(fr,za)}cP({global:!0,constructor:!0,wrap:!0,forced:Df},{Promise:Bt});dP(Bt,es,!1,!0);pP(es)});var Qf=m((bC,Yf)=>{"use strict";var $P=te(),Gf=$P("iterator"),Wf=!1;try{jf=0,Yo={next:function(){return{done:!!jf++}},return:function(){Wf=!0}},Yo[Gf]=function(){return this},Array.from(Yo,function(){throw 2})}catch(a){}var jf,Yo;Yf.exports=function(a,e){try{if(!e&&!Wf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Gf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Qo=m((gC,zf)=>{"use strict";var LP=Dt(),MP=Qf(),CP=pr().CONSTRUCTOR;zf.exports=CP||!MP(function(a){LP.all(a).then(void 0,function(){})})});var Kf=m(()=>{"use strict";var DP=we(),BP=ye(),OP=Qe(),VP=hr(),_P=Qa(),NP=Ua(),FP=Qo();DP({target:"Promise",stat:!0,forced:FP},{all:function(e){var t=this,r=VP.f(t),i=r.resolve,s=r.reject,n=_P(function(){var o=OP(t.resolve),u=[],c=0,l=1;NP(e,function(d){var p=c++,h=!1;l++,BP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--l||i(u))},s)}),--l||i(u)});return n.error&&s(n.value),r.promise}})});var Xf=m(()=>{"use strict";var qP=we(),UP=Oe(),HP=pr().CONSTRUCTOR,Ko=Dt(),jP=Ye(),GP=W(),WP=cr(),Jf=Ko&&Ko.prototype;qP({target:"Promise",proto:!0,forced:HP,real:!0},{catch:function(a){return this.then(void 0,a)}});!UP&&GP(Ko)&&(zo=jP("Promise").prototype.catch,Jf.catch!==zo&&WP(Jf,"catch",zo,{unsafe:!0}));var zo});var Zf=m(()=>{"use strict";var YP=we(),QP=ye(),zP=Qe(),KP=hr(),JP=Qa(),XP=Ua(),ZP=Qo();YP({target:"Promise",stat:!0,forced:ZP},{race:function(e){var t=this,r=KP.f(t),i=r.reject,s=JP(function(){var n=zP(t.resolve);XP(e,function(o){QP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var em=m(()=>{"use strict";var eA=we(),tA=hr(),rA=pr().CONSTRUCTOR;eA({target:"Promise",stat:!0,forced:rA},{reject:function(e){var t=tA.f(this),r=t.reject;return r(e),t.promise}})});var Jo=m((AC,tm)=>{"use strict";var iA=je(),aA=Pe(),sA=hr();tm.exports=function(a,e){if(iA(a),aA(e)&&e.constructor===a)return e;var t=sA.f(a),r=t.resolve;return r(e),t.promise}});var am=m(()=>{"use strict";var nA=we(),oA=Ye(),rm=Oe(),uA=Dt(),im=pr().CONSTRUCTOR,cA=Jo(),lA=oA("Promise"),dA=rm&&!im;nA({target:"Promise",stat:!0,forced:rm||im},{resolve:function(e){return cA(dA&&this===lA?uA:this,e)}})});var sm=m(()=>{"use strict";Hf();Kf();Xf();Zf();em();am()});var cm=m(()=>{"use strict";var pA=we(),hA=Oe(),ts=Dt(),fA=ve(),om=Ye(),um=W(),mA=yo(),nm=Jo(),bA=cr(),Zo=ts&&ts.prototype,gA=!!ts&&fA(function(){Zo.finally.call({then:function(){}},function(){})});pA({target:"Promise",proto:!0,real:!0,forced:gA},{finally:function(a){var e=mA(this,om("Promise")),t=um(a);return this.then(t?function(r){return nm(e,a()).then(function(){return r})}:a,t?function(r){return nm(e,a()).then(function(){throw r})}:a)}});!hA&&um(ts)&&(Xo=om("Promise").prototype.finally,Zo.finally!==Xo&&bA(Zo,"finally",Xo,{unsafe:!0}));var Xo});var rs=m((CC,lm)=>{"use strict";var SA=Ye();lm.exports=SA});var pm=m((DC,dm)=>{"use strict";gh();sm();cm();var vA=rs();dm.exports=vA("Promise","finally")});var fm=m((BC,hm)=>{"use strict";var yA=pm();hm.exports=yA});var is=m((OC,mm)=>{"use strict";var TA=fm();mm.exports=TA});var Fm=m(()=>{"use strict";var KA=we(),JA=Qr(),XA=Ca(),ZA=Ma(),ew=gn();KA({target:"Array",proto:!0},{at:function(e){var t=JA(this),r=XA(t),i=ZA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});ew("at")});var Um=m((GD,qm)=>{"use strict";Fm();var tw=rs();qm.exports=tw("Array","at")});var jm=m((WD,Hm)=>{"use strict";var rw=Um();Hm.exports=rw});var fi=m((YD,Gm)=>{"use strict";var iw=jm();Gm.exports=iw});var Kb=m(()=>{"use strict"});var Jb=m(()=>{"use strict"});var Zb=m((YV,Xb)=>{"use strict";var ck=Pe(),lk=tr(),dk=te(),pk=dk("match");Xb.exports=function(a){var e;return ck(a)&&((e=a[pk])!==void 0?!!e:lk(a)==="RegExp")}});var tg=m((QV,eg)=>{"use strict";var hk=ei(),fk=String;eg.exports=function(a){if(hk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fk(a)}});var ig=m((zV,rg)=>{"use strict";var mk=je();rg.exports=function(){var a=mk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var ng=m((KV,sg)=>{"use strict";var bk=ye(),gk=Ve(),Sk=jr(),vk=ig(),ag=RegExp.prototype;sg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in ag)&&!gk(a,"flags")&&Sk(ag,a)?bk(vk,a):e}});var ug=m((JV,og)=>{"use strict";var Ru=ce(),yk=Qr(),Tk=Math.floor,wu=Ru("".charAt),Ik=Ru("".replace),ku=Ru("".slice),Ek=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xk=/\$([$&'`]|\d{1,2})/g;og.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=xk;return i!==void 0&&(i=yk(i),u=Ek),Ik(s,u,function(c,l){var d;switch(wu(l,0)){case"$":return"$";case"&":return a;case"`":return ku(e,0,t);case"'":return ku(e,n);case"<":d=i[ku(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Tk(p/10);return h===0?c:h<=o?r[h-1]===void 0?wu(l,1):r[h-1]+wu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var dg=m(()=>{"use strict";var Pk=we(),Ak=ye(),Lu=ce(),cg=Ur(),wk=W(),kk=rr(),Rk=Zb(),kr=tg(),$k=Wr(),Lk=ng(),Mk=ug(),Ck=te(),Dk=Oe(),Bk=Ck("replace"),Ok=TypeError,$u=Lu("".indexOf),Vk=Lu("".replace),lg=Lu("".slice),_k=Math.max;Pk({target:"String",proto:!0},{replaceAll:function(e,t){var r=cg(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!kk(e)){if(i=Rk(e),i&&(s=kr(cg(Lk(e))),!~$u(s,"g")))throw new Ok("`.replaceAll` does not allow non-global regexes");if(n=$k(e,Bk),n)return Ak(n,e,r,t);if(Dk&&i)return Vk(kr(r),e,t)}for(o=kr(r),u=kr(e),c=wk(t),c||(t=kr(t)),l=u.length,d=_k(1,l),p=$u(o,u);p!==-1;)h=c?kr(t(u,p,o)):Mk(u,o,p,[],void 0,t),b+=lg(o,f,p)+h,f=p+l,p=p+d>o.length?-1:$u(o,u,p+d);return f<o.length&&(b+=lg(o,f)),b}})});var hg=m((e_,pg)=>{"use strict";Kb();Jb();dg();var Nk=rs();pg.exports=Nk("String","replaceAll")});var mg=m((t_,fg)=>{"use strict";var Fk=hg();fg.exports=Fk});var gg=m((r_,bg)=>{"use strict";var qk=mg();bg.exports=qk});var Dc="2.0.111-dev.2c18acf4.0";var ue=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ue||{}),lt=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(lt||{});var ya=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ya||{}),dn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(dn||{});var pn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(pn||{});import{assertNever as Fc,assertNonNullable as ov,isNonNullable as Ta,ValueSubject as hn,Subject as uv,Subscription as cv,merge as lv,observableFrom as dv,fromEvent as Oc,map as Vc,tap as _c,filterChanged as pv,isNullable as fn,ErrorCategory as Nc}from"@vkontakte/videoplayer-shared";var Bc=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ia=class{constructor(e){this.connection$=new hn(void 0);this.castState$=new hn("NOT_AVAILABLE");this.errorEvent$=new uv;this.realCastState$=new hn("NOT_AVAILABLE");this.subscription=new cv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ta((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Bc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Nc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ta(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();fn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();fn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Oc(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Fc(i.sessionState)}})).add(lv(Oc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_c(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Vc(i=>i.castState)),dv([r.getCastState()])).pipe(pv(),Vc(hv),_c(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ta(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();ov(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(fn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ta(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Nc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},hv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Fc(a)}};var mS=He(mo(),1);var Pm=He(is(),1);import{assertNever as bm}from"@vkontakte/videoplayer-shared";var ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:bm(t)}return a},eu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:bm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as IA,Subject as as,merge as gm}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new as;this.transitionEnded$=new as;this.transitionUpdated$=new as;this.forceChanged$=new as;this.stateChangeStarted$=gm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=gm(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||IA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as EA}from"@vkontakte/videoplayer-shared";var Sm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return EA(a)}};import{assertNever as Sr,assertNonNullable as Ot,debounce as vm,ErrorCategory as ym,fromEvent as Vt,isNonNullable as Tm,map as Im,merge as Em,observableFrom as xA,Subject as PA,Subscription as tu,timeout as AA,getHighestQuality as wA}from"@vkontakte/videoplayer-shared";var kA=5,RA=5,$A=500,xm=7e3,di=class{constructor(e){this.subscription=new tu;this.loadMediaTimeoutSubscription=new tu;this.videoState=new M("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}default:Sr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Sm(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new tu;this.subscription.add(e),this.subscription.add(Em(this.videoState.stateChangeStarted$.pipe(Im(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Im(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new PA;e.add(i.pipe(vm($A)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>kA)&&i.next(o),s=o})),e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<RA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Sr(n)}}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Em(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xA(["init"])).pipe(vm(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var c;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];Ot(l);let d=wA(Object.keys(l));Ot(d);let p=l[d];Ot(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Ot(l),r=l.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Ot(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Ot(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Ot(l),r=ee(l.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:ym.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Sr(e)}let n=new chrome.cast.media.MediaInfo((c=this.params.meta.videoId)!=null?c:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Tm(o)&&(n.metadata.title=o),Tm(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(AA(xm).subscribe(()=>s(`timeout(${xm})`)))});(0,Pm.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ym.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as wm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as LA}from"@vkontakte/videoplayer-shared";var Am=a=>{try{a.pause(),a.playbackRate=0,LA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as MA,Subscription as CA}from"@vkontakte/videoplayer-shared";var ru=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},iu=window.WeakMap?new WeakMap:new ru,au=window.WeakMap?new WeakMap:new Map,DA=(a,e=20)=>{let t=0;return MA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},le=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?wm(t):(t=document.createElement("video"),a.appendChild(t)),iu.set(t,r);let i=new CA;return i.add(DA(t,e)),au.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},de=a=>{let e=au.get(a);e==null||e.unsubscribe(),au.delete(a);let t=iu.get(a);iu.delete(a),t?wm(a):Am(a)};import{assertNonNullable as pi,isNonNullable as We,isNullable as VA,fromEvent as vr,merge as km,observableFrom as Rm,filterChanged as $m,map as hi,Subject as Lm,Subscription as _A,ValueSubject as NA,ErrorCategory as FA}from"@vkontakte/videoplayer-shared";import{isNonNullable as su,isNullable as BA,Subscription as OA}from"@vkontakte/videoplayer-shared";var ss=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=BA(i),c=new OA;return i&&c.add(i.subscribe(l=>{let d=a.getState();r(l,d)&&a.setState(l)},s)),r(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},Ge=(a,e,t)=>ss(e,()=>a.loop,r=>{su(r)&&(a.loop=r)},{onError:t}),pe=(a,e,t,r)=>ss(e,()=>({muted:a.muted,volume:a.volume}),i=>{su(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),ke=(a,e,t,r)=>ss(e,()=>a.playbackRate,i=>{su(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),pt=ss;var qA=a=>["__",a.language,a.label].join("|"),UA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},nu=class a{constructor(){this.available$=new Lm;this.current$=new NA(void 0);this.error$=new Lm;this.subscription=new _A;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:FA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(pt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{We(s)&&this.setInternal(s)},{equal:(s,n)=>We(s)&&We(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(hi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(pt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{We(s)&&this.setExternal(s)},{equal:(s,n)=>We(s)&&We(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(hi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(pt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(pt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){pi(this.video);let{textTracks:e}=this.video;this.subscription.add(vr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(km(vr(e,"addtrack"),vr(e,"removetrack"),Rm(["init"])).pipe(hi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),$m((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(km(vr(e,"change"),Rm(["init"])).pipe(hi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),hi(r=>r&&this.htmlTextTrackToITextTrack(r).id),$m()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(vr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(vr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;We(t.align)&&(i.align=t.align),We(t.position)&&(i.position=t.position),We(t.size)&&(i.size=t.size),We(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){pi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:qA(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){pi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(VA(e)||!UA(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){pi(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){pi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Re=nu;var Je=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Mm=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ou=a=>{let e=Mm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Cm=a=>{let e=Mm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as ht,merge as Bm,filterChanged as jA,isNonNullable as Om,Subject as GA,filter as Vm,mapTo as _m,combine as WA,once as YA,ErrorCategory as QA,ValueSubject as Nm,clientChecker as zA}from"@vkontakte/videoplayer-shared";var HA=3,Dm=(a,e,t=HA)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var he=a=>{let e=S=>$e(a,S).pipe(_m(void 0)),r=Bm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>$e(a,S))).pipe(ht(S=>S.type==="ended"?a.readyState<2:a.readyState<3),jA()),i=Bm($e(a,"progress"),$e(a,"timeupdate")).pipe(ht(()=>Dm(a.buffered,a.currentTime))),s=zA.isSafari?WA({play:e("play").pipe(YA()),playing:e("playing")}).pipe(_m(void 0)):e("playing"),n=$e(a,"volumechange").pipe(ht(()=>({muted:a.muted,volume:a.volume}))),o=$e(a,"ratechange").pipe(ht(()=>a.playbackRate)),u=$e(a,"error").pipe(Vm(()=>!!(a.error||a.played.length)),ht(()=>{var v;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:QA.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(v=a.error)!=null?v:void 0}})),c=$e(a,"timeupdate").pipe(ht(()=>a.currentTime)),l=new GA,d=.3,p;c.subscribe(S=>{a.loop&&Om(p)&&Om(S)&&p>=a.duration-d&&S<=d&&l.next(p),p=S});let h=e("pause").pipe(Vm(()=>!a.error&&p!==a.duration)),f=$e(a,"enterpictureinpicture"),b=$e(a,"leavepictureinpicture"),g=new Nm(Cm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new Nm(ou(a));return $e(a,"fullscreenchange").pipe(ht(()=>ou(a))).subscribe(y),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:$e(a,"durationchange").pipe(ht(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as ft}from"@vkontakte/videoplayer-shared";var mt=a=>{switch(a){case"mobile":return ft.Q_144P;case"lowest":return ft.Q_240P;case"low":return ft.Q_360P;case"sd":case"medium":return ft.Q_480P;case"hd":case"high":return ft.Q_720P;case"fullhd":case"full":return ft.Q_1080P;case"quadhd":case"quad":return ft.Q_1440P;case"ultrahd":case"ultra":return ft.Q_2160P}};var _t=He(fi(),1);import{isNonNullable as fe,isNullable as cu,now as Zm,isHigher as lu,isHigherOrEqual as zm,isInvariantQuality as Km,isLower as du,isLowerOrEqual as Jm,videoSizeToQuality as aw,assertNotEmptyArray as eb,assertNonNullable as sw}from"@vkontakte/videoplayer-shared";var uu=!1,Xe={},Wm=a=>{uu=a},Ym=()=>{Xe={}},Qm=a=>{a(Xe)},mi=(a,e)=>{var t;uu&&(Xe.meta=(t=Xe.meta)!=null?t:{},Xe.meta[a]=e)},re=class{constructor(e){this.name=e}next(e){var r,i;if(!uu)return;Xe.series=(r=Xe.series)!=null?r:{};let t=(i=Xe.series[this.name])!=null?i:[];t.push([Date.now(),e]),Xe.series[this.name]=t}};var nw=new re("best_bitrate"),tb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var pu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),bi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Zm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},rb='Assertion "ABR Tracks is empty array" failed',ns=(a,e,t,r)=>{var u;let i=[...e].sort(pu(1)),s=[...t].sort(pu(1)),n=s.filter(c=>fe(c.bitrate)&&fe(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,_t.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,_t.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,_t.default)(n,-1):(0,_t.default)(s,0)},Xm=a=>"quality"in a,ib=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&Zm()-r.history[t.id]<=a.trackCooldown&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!i&&r.recordSelection(t),i&&(r!=null&&r.last)){let s=r.last;r==null||r.recordSwitch(s);let n=Xm(s)?"video":"audio",o=Xm(s)?s.quality:s.bitrate;return e({message:`
6
+ var tv=Object.create;var Cc=Object.defineProperty;var rv=Object.getOwnPropertyDescriptor;var iv=Object.getOwnPropertyNames;var av=Object.getPrototypeOf,sv=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var nv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of iv(e))!sv.call(a,i)&&i!==t&&Cc(a,i,{get:()=>e[i],enumerable:!(r=rv(e,i))||r.enumerable});return a};var He=(a,e,t)=>(t=a!=null?tv(av(a)):{},nv(e||!a||!a.__esModule?Cc(t,"default",{value:a,enumerable:!0}):t,a));var ve=m((eL,qc)=>{"use strict";qc.exports=function(a){try{return!!a()}catch(e){return!0}}});var qr=m((tL,Uc)=>{"use strict";var fv=ve();Uc.exports=!fv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ce=m((rL,Gc)=>{"use strict";var Hc=qr(),jc=Function.prototype,mn=jc.call,mv=Hc&&jc.bind.bind(mn,mn);Gc.exports=Hc?mv:function(a){return function(){return mn.apply(a,arguments)}}});var tr=m((iL,Yc)=>{"use strict";var Wc=ce(),bv=Wc({}.toString),gv=Wc("".slice);Yc.exports=function(a){return gv(bv(a),8,-1)}});var zc=m((aL,Qc)=>{"use strict";var Sv=ce(),vv=ve(),yv=tr(),bn=Object,Tv=Sv("".split);Qc.exports=vv(function(){return!bn("z").propertyIsEnumerable(0)})?function(a){return yv(a)==="String"?Tv(a,""):bn(a)}:bn});var rr=m((sL,Kc)=>{"use strict";Kc.exports=function(a){return a==null}});var Ur=m((nL,Jc)=>{"use strict";var Iv=rr(),Ev=TypeError;Jc.exports=function(a){if(Iv(a))throw new Ev("Can't call method on "+a);return a}});var ir=m((oL,Xc)=>{"use strict";var xv=zc(),Pv=Ur();Xc.exports=function(a){return xv(Pv(a))}});var gn=m((uL,Zc)=>{"use strict";Zc.exports=function(){}});var $t=m((cL,el)=>{"use strict";el.exports={}});var Y=m((Sn,tl)=>{"use strict";var Hr=function(a){return a&&a.Math===Math&&a};tl.exports=Hr(typeof globalThis=="object"&&globalThis)||Hr(typeof window=="object"&&window)||Hr(typeof self=="object"&&self)||Hr(typeof global=="object"&&global)||Hr(typeof Sn=="object"&&Sn)||function(){return this}()||Function("return this")()});var W=m((lL,rl)=>{"use strict";var vn=typeof document=="object"&&document.all;rl.exports=typeof vn=="undefined"&&vn!==void 0?function(a){return typeof a=="function"||a===vn}:function(a){return typeof a=="function"}});var sl=m((dL,al)=>{"use strict";var Av=Y(),wv=W(),il=Av.WeakMap;al.exports=wv(il)&&/native code/.test(String(il))});var Pe=m((pL,nl)=>{"use strict";var kv=W();nl.exports=function(a){return typeof a=="object"?a!==null:kv(a)}});var Ae=m((hL,ol)=>{"use strict";var Rv=ve();ol.exports=!Rv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ea=m((fL,cl)=>{"use strict";var $v=Y(),ul=Pe(),yn=$v.document,Lv=ul(yn)&&ul(yn.createElement);cl.exports=function(a){return Lv?yn.createElement(a):{}}});var Tn=m((mL,ll)=>{"use strict";var Mv=Ae(),Cv=ve(),Dv=Ea();ll.exports=!Mv&&!Cv(function(){return Object.defineProperty(Dv("div"),"a",{get:function(){return 7}}).a!==7})});var In=m((bL,dl)=>{"use strict";var Bv=Ae(),Ov=ve();dl.exports=Bv&&Ov(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var je=m((gL,pl)=>{"use strict";var Vv=Pe(),_v=String,Nv=TypeError;pl.exports=function(a){if(Vv(a))return a;throw new Nv(_v(a)+" is not an object")}});var ye=m((SL,hl)=>{"use strict";var Fv=qr(),xa=Function.prototype.call;hl.exports=Fv?xa.bind(xa):function(){return xa.apply(xa,arguments)}});var Pa=m((vL,fl)=>{"use strict";fl.exports={}});var Ye=m((yL,bl)=>{"use strict";var En=Pa(),xn=Y(),qv=W(),ml=function(a){return qv(a)?a:void 0};bl.exports=function(a,e){return arguments.length<2?ml(En[a])||ml(xn[a]):En[a]&&En[a][e]||xn[a]&&xn[a][e]}});var jr=m((TL,gl)=>{"use strict";var Uv=ce();gl.exports=Uv({}.isPrototypeOf)});var ar=m((IL,yl)=>{"use strict";var Hv=Y(),Sl=Hv.navigator,vl=Sl&&Sl.userAgent;yl.exports=vl?String(vl):""});var An=m((EL,Al)=>{"use strict";var Pl=Y(),Pn=ar(),Tl=Pl.process,Il=Pl.Deno,El=Tl&&Tl.versions||Il&&Il.version,xl=El&&El.v8,Oe,Aa;xl&&(Oe=xl.split("."),Aa=Oe[0]>0&&Oe[0]<4?1:+(Oe[0]+Oe[1]));!Aa&&Pn&&(Oe=Pn.match(/Edge\/(\d+)/),(!Oe||Oe[1]>=74)&&(Oe=Pn.match(/Chrome\/(\d+)/),Oe&&(Aa=+Oe[1])));Al.exports=Aa});var wn=m((xL,kl)=>{"use strict";var wl=An(),jv=ve(),Gv=Y(),Wv=Gv.String;kl.exports=!!Object.getOwnPropertySymbols&&!jv(function(){var a=Symbol("symbol detection");return!Wv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&wl&&wl<41})});var kn=m((PL,Rl)=>{"use strict";var Yv=wn();Rl.exports=Yv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Rn=m((AL,$l)=>{"use strict";var Qv=Ye(),zv=W(),Kv=jr(),Jv=kn(),Xv=Object;$l.exports=Jv?function(a){return typeof a=="symbol"}:function(a){var e=Qv("Symbol");return zv(e)&&Kv(e.prototype,Xv(a))}});var Gr=m((wL,Ll)=>{"use strict";var Zv=String;Ll.exports=function(a){try{return Zv(a)}catch(e){return"Object"}}});var Qe=m((kL,Ml)=>{"use strict";var ey=W(),ty=Gr(),ry=TypeError;Ml.exports=function(a){if(ey(a))return a;throw new ry(ty(a)+" is not a function")}});var Wr=m((RL,Cl)=>{"use strict";var iy=Qe(),ay=rr();Cl.exports=function(a,e){var t=a[e];return ay(t)?void 0:iy(t)}});var Bl=m(($L,Dl)=>{"use strict";var $n=ye(),Ln=W(),Mn=Pe(),sy=TypeError;Dl.exports=function(a,e){var t,r;if(e==="string"&&Ln(t=a.toString)&&!Mn(r=$n(t,a))||Ln(t=a.valueOf)&&!Mn(r=$n(t,a))||e!=="string"&&Ln(t=a.toString)&&!Mn(r=$n(t,a)))return r;throw new sy("Can't convert object to primitive value")}});var Ve=m((LL,Ol)=>{"use strict";Ol.exports=!0});var Nl=m((ML,_l)=>{"use strict";var Vl=Y(),ny=Object.defineProperty;_l.exports=function(a,e){try{ny(Vl,a,{value:e,configurable:!0,writable:!0})}catch(t){Vl[a]=e}return e}});var Yr=m((CL,Ul)=>{"use strict";var oy=Ve(),uy=Y(),cy=Nl(),Fl="__core-js_shared__",ql=Ul.exports=uy[Fl]||cy(Fl,{});(ql.versions||(ql.versions=[])).push({version:"3.38.0",mode:oy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Cn=m((DL,jl)=>{"use strict";var Hl=Yr();jl.exports=function(a,e){return Hl[a]||(Hl[a]=e||{})}});var Qr=m((BL,Gl)=>{"use strict";var ly=Ur(),dy=Object;Gl.exports=function(a){return dy(ly(a))}});var _e=m((OL,Wl)=>{"use strict";var py=ce(),hy=Qr(),fy=py({}.hasOwnProperty);Wl.exports=Object.hasOwn||function(e,t){return fy(hy(e),t)}});var Dn=m((VL,Yl)=>{"use strict";var my=ce(),by=0,gy=Math.random(),Sy=my(1 .toString);Yl.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Sy(++by+gy,36)}});var te=m((_L,zl)=>{"use strict";var vy=Y(),yy=Cn(),Ql=_e(),Ty=Dn(),Iy=wn(),Ey=kn(),sr=vy.Symbol,Bn=yy("wks"),xy=Ey?sr.for||sr:sr&&sr.withoutSetter||Ty;zl.exports=function(a){return Ql(Bn,a)||(Bn[a]=Iy&&Ql(sr,a)?sr[a]:xy("Symbol."+a)),Bn[a]}});var Zl=m((NL,Xl)=>{"use strict";var Py=ye(),Kl=Pe(),Jl=Rn(),Ay=Wr(),wy=Bl(),ky=te(),Ry=TypeError,$y=ky("toPrimitive");Xl.exports=function(a,e){if(!Kl(a)||Jl(a))return a;var t=Ay(a,$y),r;if(t){if(e===void 0&&(e="default"),r=Py(t,a,e),!Kl(r)||Jl(r))return r;throw new Ry("Can't convert object to primitive value")}return e===void 0&&(e="number"),wy(a,e)}});var On=m((FL,ed)=>{"use strict";var Ly=Zl(),My=Rn();ed.exports=function(a){var e=Ly(a,"string");return My(e)?e:e+""}});var Lt=m(rd=>{"use strict";var Cy=Ae(),Dy=Tn(),By=In(),wa=je(),td=On(),Oy=TypeError,Vn=Object.defineProperty,Vy=Object.getOwnPropertyDescriptor,_n="enumerable",Nn="configurable",Fn="writable";rd.f=Cy?By?function(e,t,r){if(wa(e),t=td(t),wa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Fn in r&&!r[Fn]){var i=Vy(e,t);i&&i[Fn]&&(e[t]=r.value,r={configurable:Nn in r?r[Nn]:i[Nn],enumerable:_n in r?r[_n]:i[_n],writable:!1})}return Vn(e,t,r)}:Vn:function(e,t,r){if(wa(e),t=td(t),wa(r),Dy)try{return Vn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new Oy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var zr=m((UL,id)=>{"use strict";id.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var nr=m((HL,ad)=>{"use strict";var _y=Ae(),Ny=Lt(),Fy=zr();ad.exports=_y?function(a,e,t){return Ny.f(a,e,Fy(1,t))}:function(a,e,t){return a[e]=t,a}});var ka=m((jL,nd)=>{"use strict";var qy=Cn(),Uy=Dn(),sd=qy("keys");nd.exports=function(a){return sd[a]||(sd[a]=Uy(a))}});var Ra=m((GL,od)=>{"use strict";od.exports={}});var jn=m((WL,ld)=>{"use strict";var Hy=sl(),cd=Y(),jy=Pe(),Gy=nr(),qn=_e(),Un=Yr(),Wy=ka(),Yy=Ra(),ud="Object already initialized",Hn=cd.TypeError,Qy=cd.WeakMap,$a,Kr,La,zy=function(a){return La(a)?Kr(a):$a(a,{})},Ky=function(a){return function(e){var t;if(!jy(e)||(t=Kr(e)).type!==a)throw new Hn("Incompatible receiver, "+a+" required");return t}};Hy||Un.state?(Ne=Un.state||(Un.state=new Qy),Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,$a=function(a,e){if(Ne.has(a))throw new Hn(ud);return e.facade=a,Ne.set(a,e),e},Kr=function(a){return Ne.get(a)||{}},La=function(a){return Ne.has(a)}):(Mt=Wy("state"),Yy[Mt]=!0,$a=function(a,e){if(qn(a,Mt))throw new Hn(ud);return e.facade=a,Gy(a,Mt,e),e},Kr=function(a){return qn(a,Mt)?a[Mt]:{}},La=function(a){return qn(a,Mt)});var Ne,Mt;ld.exports={set:$a,get:Kr,has:La,enforce:zy,getterFor:Ky}});var Gn=m((YL,fd)=>{"use strict";var Jy=qr(),hd=Function.prototype,dd=hd.apply,pd=hd.call;fd.exports=typeof Reflect=="object"&&Reflect.apply||(Jy?pd.bind(dd):function(){return pd.apply(dd,arguments)})});var Wn=m((QL,md)=>{"use strict";var Xy=tr(),Zy=ce();md.exports=function(a){if(Xy(a)==="Function")return Zy(a)}});var vd=m(Sd=>{"use strict";var bd={}.propertyIsEnumerable,gd=Object.getOwnPropertyDescriptor,eT=gd&&!bd.call({1:2},1);Sd.f=eT?function(e){var t=gd(this,e);return!!t&&t.enumerable}:bd});var Id=m(Td=>{"use strict";var tT=Ae(),rT=ye(),iT=vd(),aT=zr(),sT=ir(),nT=On(),oT=_e(),uT=Tn(),yd=Object.getOwnPropertyDescriptor;Td.f=tT?yd:function(e,t){if(e=sT(e),t=nT(t),uT)try{return yd(e,t)}catch(r){}if(oT(e,t))return aT(!rT(iT.f,e,t),e[t])}});var Yn=m((JL,Ed)=>{"use strict";var cT=ve(),lT=W(),dT=/#|\.prototype\./,Jr=function(a,e){var t=hT[pT(a)];return t===mT?!0:t===fT?!1:lT(e)?cT(e):!!e},pT=Jr.normalize=function(a){return String(a).replace(dT,".").toLowerCase()},hT=Jr.data={},fT=Jr.NATIVE="N",mT=Jr.POLYFILL="P";Ed.exports=Jr});var Xr=m((XL,Pd)=>{"use strict";var xd=Wn(),bT=Qe(),gT=qr(),ST=xd(xd.bind);Pd.exports=function(a,e){return bT(a),e===void 0?a:gT?ST(a,e):function(){return a.apply(e,arguments)}}});var we=m((ZL,wd)=>{"use strict";var Zr=Y(),vT=Gn(),yT=Wn(),TT=W(),IT=Id().f,ET=Yn(),or=Pa(),xT=Xr(),ur=nr(),Ad=_e();Yr();var PT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return vT(a,this,arguments)};return e.prototype=a.prototype,e};wd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Zr:i?Zr[t]:Zr[t]&&Zr[t].prototype,o=r?or:or[t]||ur(or,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,y;for(p in e)c=ET(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Ad(n,p),f=o[p],l&&(a.dontCallGetSet?(y=IT(n,p),b=y&&y.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&l?g=xT(h,Zr):a.wrap&&l?g=PT(h):s&&TT(h)?g=yT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&ur(g,"sham",!0),ur(o,p,g),s&&(d=t+"Prototype",Ad(or,d)||ur(or,d,{}),ur(or[d],p,h),a.real&&u&&(c||!u[p])&&ur(u,p,h)))}});var $d=m((eM,Rd)=>{"use strict";var Qn=Ae(),AT=_e(),kd=Function.prototype,wT=Qn&&Object.getOwnPropertyDescriptor,zn=AT(kd,"name"),kT=zn&&function(){}.name==="something",RT=zn&&(!Qn||Qn&&wT(kd,"name").configurable);Rd.exports={EXISTS:zn,PROPER:kT,CONFIGURABLE:RT}});var Md=m((tM,Ld)=>{"use strict";var $T=Math.ceil,LT=Math.floor;Ld.exports=Math.trunc||function(e){var t=+e;return(t>0?LT:$T)(t)}});var Ma=m((rM,Cd)=>{"use strict";var MT=Md();Cd.exports=function(a){var e=+a;return e!==e||e===0?0:MT(e)}});var Bd=m((iM,Dd)=>{"use strict";var CT=Ma(),DT=Math.max,BT=Math.min;Dd.exports=function(a,e){var t=CT(a);return t<0?DT(t+e,0):BT(t,e)}});var Vd=m((aM,Od)=>{"use strict";var OT=Ma(),VT=Math.min;Od.exports=function(a){var e=OT(a);return e>0?VT(e,9007199254740991):0}});var Ca=m((sM,_d)=>{"use strict";var _T=Vd();_d.exports=function(a){return _T(a.length)}});var qd=m((nM,Fd)=>{"use strict";var NT=ir(),FT=Bd(),qT=Ca(),Nd=function(a){return function(e,t,r){var i=NT(e),s=qT(i);if(s===0)return!a&&-1;var n=FT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Fd.exports={includes:Nd(!0),indexOf:Nd(!1)}});var jd=m((oM,Hd)=>{"use strict";var UT=ce(),Kn=_e(),HT=ir(),jT=qd().indexOf,GT=Ra(),Ud=UT([].push);Hd.exports=function(a,e){var t=HT(a),r=0,i=[],s;for(s in t)!Kn(GT,s)&&Kn(t,s)&&Ud(i,s);for(;e.length>r;)Kn(t,s=e[r++])&&(~jT(i,s)||Ud(i,s));return i}});var Jn=m((uM,Gd)=>{"use strict";Gd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Yd=m((cM,Wd)=>{"use strict";var WT=jd(),YT=Jn();Wd.exports=Object.keys||function(e){return WT(e,YT)}});var zd=m(Qd=>{"use strict";var QT=Ae(),zT=In(),KT=Lt(),JT=je(),XT=ir(),ZT=Yd();Qd.f=QT&&!zT?Object.defineProperties:function(e,t){JT(e);for(var r=XT(t),i=ZT(t),s=i.length,n=0,o;s>n;)KT.f(e,o=i[n++],r[o]);return e}});var Xn=m((dM,Kd)=>{"use strict";var eI=Ye();Kd.exports=eI("document","documentElement")});var ro=m((pM,ip)=>{"use strict";var tI=je(),rI=zd(),Jd=Jn(),iI=Ra(),aI=Xn(),sI=Ea(),nI=ka(),Xd=">",Zd="<",eo="prototype",to="script",tp=nI("IE_PROTO"),Zn=function(){},rp=function(a){return Zd+to+Xd+a+Zd+"/"+to+Xd},ep=function(a){a.write(rp("")),a.close();var e=a.parentWindow.Object;return a=null,e},oI=function(){var a=sI("iframe"),e="java"+to+":",t;return a.style.display="none",aI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(rp("document.F=Object")),t.close(),t.F},Da,Ba=function(){try{Da=new ActiveXObject("htmlfile")}catch(e){}Ba=typeof document!="undefined"?document.domain&&Da?ep(Da):oI():ep(Da);for(var a=Jd.length;a--;)delete Ba[eo][Jd[a]];return Ba()};iI[tp]=!0;ip.exports=Object.create||function(e,t){var r;return e!==null?(Zn[eo]=tI(e),r=new Zn,Zn[eo]=null,r[tp]=e):r=Ba(),t===void 0?r:rI.f(r,t)}});var sp=m((hM,ap)=>{"use strict";var uI=ve();ap.exports=!uI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ao=m((fM,op)=>{"use strict";var cI=_e(),lI=W(),dI=Qr(),pI=ka(),hI=sp(),np=pI("IE_PROTO"),io=Object,fI=io.prototype;op.exports=hI?io.getPrototypeOf:function(a){var e=dI(a);if(cI(e,np))return e[np];var t=e.constructor;return lI(t)&&e instanceof t?t.prototype:e instanceof io?fI:null}});var cr=m((mM,up)=>{"use strict";var mI=nr();up.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:mI(a,e,t),a}});var uo=m((bM,dp)=>{"use strict";var bI=ve(),gI=W(),SI=Pe(),vI=ro(),cp=ao(),yI=cr(),TI=te(),II=Ve(),oo=TI("iterator"),lp=!1,ze,so,no;[].keys&&(no=[].keys(),"next"in no?(so=cp(cp(no)),so!==Object.prototype&&(ze=so)):lp=!0);var EI=!SI(ze)||bI(function(){var a={};return ze[oo].call(a)!==a});EI?ze={}:II&&(ze=vI(ze));gI(ze[oo])||yI(ze,oo,function(){return this});dp.exports={IteratorPrototype:ze,BUGGY_SAFARI_ITERATORS:lp}});var Oa=m((gM,hp)=>{"use strict";var xI=te(),PI=xI("toStringTag"),pp={};pp[PI]="z";hp.exports=String(pp)==="[object z]"});var ei=m((SM,fp)=>{"use strict";var AI=Oa(),wI=W(),Va=tr(),kI=te(),RI=kI("toStringTag"),$I=Object,LI=Va(function(){return arguments}())==="Arguments",MI=function(a,e){try{return a[e]}catch(t){}};fp.exports=AI?Va:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=MI(e=$I(a),RI))=="string"?t:LI?Va(e):(r=Va(e))==="Object"&&wI(e.callee)?"Arguments":r}});var bp=m((vM,mp)=>{"use strict";var CI=Oa(),DI=ei();mp.exports=CI?{}.toString:function(){return"[object "+DI(this)+"]"}});var ti=m((yM,Sp)=>{"use strict";var BI=Oa(),OI=Lt().f,VI=nr(),_I=_e(),NI=bp(),FI=te(),gp=FI("toStringTag");Sp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(_I(i,gp)||OI(i,gp,{configurable:!0,value:e}),r&&!BI&&VI(i,"toString",NI))}});var yp=m((TM,vp)=>{"use strict";var qI=uo().IteratorPrototype,UI=ro(),HI=zr(),jI=ti(),GI=$t(),WI=function(){return this};vp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=UI(qI,{next:HI(+!r,t)}),jI(a,i,!1,!0),GI[i]=WI,a}});var Ip=m((IM,Tp)=>{"use strict";var YI=ce(),QI=Qe();Tp.exports=function(a,e,t){try{return YI(QI(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var xp=m((EM,Ep)=>{"use strict";var zI=Pe();Ep.exports=function(a){return zI(a)||a===null}});var Ap=m((xM,Pp)=>{"use strict";var KI=xp(),JI=String,XI=TypeError;Pp.exports=function(a){if(KI(a))return a;throw new XI("Can't set "+JI(a)+" as a prototype")}});var co=m((PM,wp)=>{"use strict";var ZI=Ip(),eE=Pe(),tE=Ur(),rE=Ap();wp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=ZI(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return tE(i),rE(s),eE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var _p=m((AM,Vp)=>{"use strict";var iE=we(),aE=ye(),_a=Ve(),Bp=$d(),sE=W(),nE=yp(),kp=ao(),Rp=co(),oE=ti(),uE=nr(),lo=cr(),cE=te(),$p=$t(),Op=uo(),lE=Bp.PROPER,dE=Bp.CONFIGURABLE,Lp=Op.IteratorPrototype,Na=Op.BUGGY_SAFARI_ITERATORS,ri=cE("iterator"),Mp="keys",ii="values",Cp="entries",Dp=function(){return this};Vp.exports=function(a,e,t,r,i,s,n){nE(t,e,r);var o=function(y){if(y===i&&p)return p;if(!Na&&y&&y in l)return l[y];switch(y){case Mp:return function(){return new t(this,y)};case ii:return function(){return new t(this,y)};case Cp:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[ri]||l["@@iterator"]||i&&l[i],p=!Na&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=kp(h.call(new a)),f!==Object.prototype&&f.next&&(!_a&&kp(f)!==Lp&&(Rp?Rp(f,Lp):sE(f[ri])||lo(f,ri,Dp)),oE(f,u,!0,!0),_a&&($p[u]=Dp))),lE&&i===ii&&d&&d.name!==ii&&(!_a&&dE?uE(l,"name",ii):(c=!0,p=function(){return aE(d,this)})),i)if(b={values:o(ii),keys:s?p:o(Mp),entries:o(Cp)},n)for(g in b)(Na||c||!(g in l))&&lo(l,g,b[g]);else iE({target:e,proto:!0,forced:Na||c},b);return(!_a||n)&&l[ri]!==p&&lo(l,ri,p,{name:i}),$p[e]=p,b}});var Fp=m((wM,Np)=>{"use strict";Np.exports=function(a,e){return{value:a,done:e}}});var ho=m((kM,Gp)=>{"use strict";var pE=ir(),po=gn(),qp=$t(),Hp=jn(),hE=Lt().f,fE=_p(),Fa=Fp(),mE=Ve(),bE=Ae(),jp="Array Iterator",gE=Hp.set,SE=Hp.getterFor(jp);Gp.exports=fE(Array,"Array",function(a,e){gE(this,{type:jp,target:pE(a),index:0,kind:e})},function(){var a=SE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Fa(void 0,!0);switch(a.kind){case"keys":return Fa(t,!1);case"values":return Fa(e[t],!1)}return Fa([t,e[t]],!1)},"values");var Up=qp.Arguments=qp.Array;po("keys");po("values");po("entries");if(!mE&&bE&&Up.name!=="values")try{hE(Up,"name",{value:"values"})}catch(a){}});var Yp=m((RM,Wp)=>{"use strict";var vE=te(),yE=$t(),TE=vE("iterator"),IE=Array.prototype;Wp.exports=function(a){return a!==void 0&&(yE.Array===a||IE[TE]===a)}});var fo=m(($M,zp)=>{"use strict";var EE=ei(),Qp=Wr(),xE=rr(),PE=$t(),AE=te(),wE=AE("iterator");zp.exports=function(a){if(!xE(a))return Qp(a,wE)||Qp(a,"@@iterator")||PE[EE(a)]}});var Jp=m((LM,Kp)=>{"use strict";var kE=ye(),RE=Qe(),$E=je(),LE=Gr(),ME=fo(),CE=TypeError;Kp.exports=function(a,e){var t=arguments.length<2?ME(a):e;if(RE(t))return $E(kE(t,a));throw new CE(LE(a)+" is not iterable")}});var eh=m((MM,Zp)=>{"use strict";var DE=ye(),Xp=je(),BE=Wr();Zp.exports=function(a,e,t){var r,i;Xp(a);try{if(r=BE(a,"return"),!r){if(e==="throw")throw t;return t}r=DE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Xp(r),t}});var Ua=m((CM,ah)=>{"use strict";var OE=Xr(),VE=ye(),_E=je(),NE=Gr(),FE=Yp(),qE=Ca(),th=jr(),UE=Jp(),HE=fo(),rh=eh(),jE=TypeError,qa=function(a,e){this.stopped=a,this.result=e},ih=qa.prototype;ah.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=OE(e,r),c,l,d,p,h,f,b,g=function(I){return c&&rh(c,"normal",I),new qa(!0,I)},y=function(I){return i?(_E(I),o?u(I[0],I[1],g):u(I[0],I[1])):o?u(I,g):u(I)};if(s)c=a.iterator;else if(n)c=a;else{if(l=HE(a),!l)throw new jE(NE(a)+" is not iterable");if(FE(l)){for(d=0,p=qE(a);p>d;d++)if(h=y(a[d]),h&&th(ih,h))return h;return new qa(!1)}c=UE(a,l)}for(f=s?a.next:c.next;!(b=VE(f,c)).done;){try{h=y(b.value)}catch(I){rh(c,"throw",I)}if(typeof h=="object"&&h&&th(ih,h))return h}return new qa(!1)}});var nh=m((DM,sh)=>{"use strict";var GE=Ae(),WE=Lt(),YE=zr();sh.exports=function(a,e,t){GE?WE.f(a,e,YE(0,t)):a[e]=t}});var oh=m(()=>{"use strict";var QE=we(),zE=Ua(),KE=nh();QE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return zE(e,function(r,i){KE(t,r,i)},{AS_ENTRIES:!0}),t}})});var ch=m((VM,uh)=>{"use strict";ho();oh();var JE=Pa();uh.exports=JE.Object.fromEntries});var dh=m((_M,lh)=>{"use strict";lh.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var hh=m(()=>{"use strict";ho();var XE=dh(),ZE=Y(),ex=ti(),ph=$t();for(Ha in XE)ex(ZE[Ha],Ha),ph[Ha]=ph.Array;var Ha});var mh=m((qM,fh)=>{"use strict";var tx=ch();hh();fh.exports=tx});var mo=m((UM,bh)=>{"use strict";var rx=mh();bh.exports=rx});var gh=m(()=>{"use strict"});var bo=m((GM,Sh)=>{"use strict";var ai=Y(),ix=ar(),ax=tr(),ja=function(a){return ix.slice(0,a.length)===a};Sh.exports=function(){return ja("Bun/")?"BUN":ja("Cloudflare-Workers")?"CLOUDFLARE":ja("Deno/")?"DENO":ja("Node.js/")?"NODE":ai.Bun&&typeof Bun.version=="string"?"BUN":ai.Deno&&typeof Deno.version=="object"?"DENO":ax(ai.process)==="process"?"NODE":ai.window&&ai.document?"BROWSER":"REST"}()});var Ga=m((WM,vh)=>{"use strict";var sx=bo();vh.exports=sx==="NODE"});var Th=m((YM,yh)=>{"use strict";var nx=Lt();yh.exports=function(a,e,t){return nx.f(a,e,t)}});var xh=m((QM,Eh)=>{"use strict";var ox=Ye(),ux=Th(),cx=te(),lx=Ae(),Ih=cx("species");Eh.exports=function(a){var e=ox(a);lx&&e&&!e[Ih]&&ux(e,Ih,{configurable:!0,get:function(){return this}})}});var Ah=m((zM,Ph)=>{"use strict";var dx=jr(),px=TypeError;Ph.exports=function(a,e){if(dx(e,a))return a;throw new px("Incorrect invocation")}});var So=m((KM,wh)=>{"use strict";var hx=ce(),fx=W(),go=Yr(),mx=hx(Function.toString);fx(go.inspectSource)||(go.inspectSource=function(a){return mx(a)});wh.exports=go.inspectSource});var Ch=m((JM,Mh)=>{"use strict";var bx=ce(),gx=ve(),kh=W(),Sx=ei(),vx=Ye(),yx=So(),Rh=function(){},$h=vx("Reflect","construct"),vo=/^\s*(?:class|function)\b/,Tx=bx(vo.exec),Ix=!vo.test(Rh),si=function(e){if(!kh(e))return!1;try{return $h(Rh,[],e),!0}catch(t){return!1}},Lh=function(e){if(!kh(e))return!1;switch(Sx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ix||!!Tx(vo,yx(e))}catch(t){return!0}};Lh.sham=!0;Mh.exports=!$h||gx(function(){var a;return si(si.call)||!si(Object)||!si(function(){a=!0})||a})?Lh:si});var Bh=m((XM,Dh)=>{"use strict";var Ex=Ch(),xx=Gr(),Px=TypeError;Dh.exports=function(a){if(Ex(a))return a;throw new Px(xx(a)+" is not a constructor")}});var yo=m((ZM,Vh)=>{"use strict";var Oh=je(),Ax=Bh(),wx=rr(),kx=te(),Rx=kx("species");Vh.exports=function(a,e){var t=Oh(a).constructor,r;return t===void 0||wx(r=Oh(t)[Rx])?e:Ax(r)}});var Nh=m((eC,_h)=>{"use strict";var $x=ce();_h.exports=$x([].slice)});var qh=m((tC,Fh)=>{"use strict";var Lx=TypeError;Fh.exports=function(a,e){if(a<e)throw new Lx("Not enough arguments");return a}});var To=m((rC,Uh)=>{"use strict";var Mx=ar();Uh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Mx)});var $o=m((iC,Jh)=>{"use strict";var Te=Y(),Cx=Gn(),Dx=Xr(),Hh=W(),Bx=_e(),Kh=ve(),jh=Xn(),Ox=Nh(),Gh=Ea(),Vx=qh(),_x=To(),Nx=Ga(),wo=Te.setImmediate,ko=Te.clearImmediate,Fx=Te.process,Io=Te.Dispatch,qx=Te.Function,Wh=Te.MessageChannel,Ux=Te.String,Eo=0,ni={},Yh="onreadystatechange",oi,Ct,xo,Po;Kh(function(){oi=Te.location});var Ro=function(a){if(Bx(ni,a)){var e=ni[a];delete ni[a],e()}},Ao=function(a){return function(){Ro(a)}},Qh=function(a){Ro(a.data)},zh=function(a){Te.postMessage(Ux(a),oi.protocol+"//"+oi.host)};(!wo||!ko)&&(wo=function(e){Vx(arguments.length,1);var t=Hh(e)?e:qx(e),r=Ox(arguments,1);return ni[++Eo]=function(){Cx(t,void 0,r)},Ct(Eo),Eo},ko=function(e){delete ni[e]},Nx?Ct=function(a){Fx.nextTick(Ao(a))}:Io&&Io.now?Ct=function(a){Io.now(Ao(a))}:Wh&&!_x?(xo=new Wh,Po=xo.port2,xo.port1.onmessage=Qh,Ct=Dx(Po.postMessage,Po)):Te.addEventListener&&Hh(Te.postMessage)&&!Te.importScripts&&oi&&oi.protocol!=="file:"&&!Kh(zh)?(Ct=zh,Te.addEventListener("message",Qh,!1)):Yh in Gh("script")?Ct=function(a){jh.appendChild(Gh("script"))[Yh]=function(){jh.removeChild(this),Ro(a)}}:Ct=function(a){setTimeout(Ao(a),0)});Jh.exports={set:wo,clear:ko}});var ef=m((aC,Zh)=>{"use strict";var Xh=Y(),Hx=Ae(),jx=Object.getOwnPropertyDescriptor;Zh.exports=function(a){if(!Hx)return Xh[a];var e=jx(Xh,a);return e&&e.value}});var Lo=m((sC,rf)=>{"use strict";var tf=function(){this.head=null,this.tail=null};tf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};rf.exports=tf});var sf=m((nC,af)=>{"use strict";var Gx=ar();af.exports=/ipad|iphone|ipod/i.test(Gx)&&typeof Pebble!="undefined"});var of=m((oC,nf)=>{"use strict";var Wx=ar();nf.exports=/web0s(?!.*chrome)/i.test(Wx)});var ff=m((uC,hf)=>{"use strict";var dr=Y(),Yx=ef(),uf=Xr(),Mo=$o().set,Qx=Lo(),zx=To(),Kx=sf(),Jx=of(),Co=Ga(),cf=dr.MutationObserver||dr.WebKitMutationObserver,lf=dr.document,df=dr.process,Wa=dr.Promise,Oo=Yx("queueMicrotask"),lr,Do,Bo,Ya,pf;Oo||(ui=new Qx,ci=function(){var a,e;for(Co&&(a=df.domain)&&a.exit();e=ui.get();)try{e()}catch(t){throw ui.head&&lr(),t}a&&a.enter()},!zx&&!Co&&!Jx&&cf&&lf?(Do=!0,Bo=lf.createTextNode(""),new cf(ci).observe(Bo,{characterData:!0}),lr=function(){Bo.data=Do=!Do}):!Kx&&Wa&&Wa.resolve?(Ya=Wa.resolve(void 0),Ya.constructor=Wa,pf=uf(Ya.then,Ya),lr=function(){pf(ci)}):Co?lr=function(){df.nextTick(ci)}:(Mo=uf(Mo,dr),lr=function(){Mo(ci)}),Oo=function(a){ui.head||lr(),ui.add(a)});var ui,ci;hf.exports=Oo});var bf=m((cC,mf)=>{"use strict";mf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Qa=m((lC,gf)=>{"use strict";gf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Dt=m((dC,Sf)=>{"use strict";var Xx=Y();Sf.exports=Xx.Promise});var pr=m((pC,If)=>{"use strict";var Zx=Y(),li=Dt(),eP=W(),tP=Yn(),rP=So(),iP=te(),vf=bo(),aP=Ve(),Vo=An(),yf=li&&li.prototype,sP=iP("species"),_o=!1,Tf=eP(Zx.PromiseRejectionEvent),nP=tP("Promise",function(){var a=rP(li),e=a!==String(li);if(!e&&Vo===66||aP&&!(yf.catch&&yf.finally))return!0;if(!Vo||Vo<51||!/native code/.test(a)){var t=new li(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[sP]=r,_o=t.then(function(){})instanceof r,!_o)return!0}return!e&&(vf==="BROWSER"||vf==="DENO")&&!Tf});If.exports={CONSTRUCTOR:nP,REJECTION_EVENT:Tf,SUBCLASSING:_o}});var hr=m((hC,xf)=>{"use strict";var Ef=Qe(),oP=TypeError,uP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new oP("Bad Promise constructor");e=r,t=i}),this.resolve=Ef(e),this.reject=Ef(t)};xf.exports.f=function(a){return new uP(a)}});var Hf=m(()=>{"use strict";var cP=we(),lP=Ve(),Xa=Ga(),dt=Y(),gr=ye(),Pf=cr(),Af=co(),dP=ti(),pP=xh(),hP=Qe(),Ja=W(),fP=Pe(),mP=Ah(),bP=yo(),Lf=$o().set,Ho=ff(),gP=bf(),SP=Qa(),vP=Lo(),Mf=jn(),Za=Dt(),jo=pr(),Cf=hr(),es="Promise",Df=jo.CONSTRUCTOR,yP=jo.REJECTION_EVENT,TP=jo.SUBCLASSING,No=Mf.getterFor(es),IP=Mf.set,fr=Za&&Za.prototype,Bt=Za,za=fr,Bf=dt.TypeError,Fo=dt.document,Go=dt.process,qo=Cf.f,EP=qo,xP=!!(Fo&&Fo.createEvent&&dt.dispatchEvent),Of="unhandledrejection",PP="rejectionhandled",wf=0,Vf=1,AP=2,Wo=1,_f=2,Ka,kf,wP,Rf,Nf=function(a){var e;return fP(a)&&Ja(e=a.then)?e:!1},Ff=function(a,e){var t=e.value,r=e.state===Vf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===_f&&RP(e),e.rejection=Wo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Bf("Promise-chain cycle")):(c=Nf(u))?gr(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},qf=function(a,e){a.notified||(a.notified=!0,Ho(function(){for(var t=a.reactions,r;r=t.get();)Ff(r,a);a.notified=!1,e&&!a.rejection&&kP(a)}))},Uf=function(a,e,t){var r,i;xP?(r=Fo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),dt.dispatchEvent(r)):r={promise:e,reason:t},!yP&&(i=dt["on"+a])?i(r):a===Of&&gP("Unhandled promise rejection",t)},kP=function(a){gr(Lf,dt,function(){var e=a.facade,t=a.value,r=$f(a),i;if(r&&(i=SP(function(){Xa?Go.emit("unhandledRejection",t,e):Uf(Of,e,t)}),a.rejection=Xa||$f(a)?_f:Wo,i.error))throw i.value})},$f=function(a){return a.rejection!==Wo&&!a.parent},RP=function(a){gr(Lf,dt,function(){var e=a.facade;Xa?Go.emit("rejectionHandled",e):Uf(PP,e,a.value)})},mr=function(a,e,t){return function(r){a(e,r,t)}},br=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=AP,qf(a,!0))},Uo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Bf("Promise can't be resolved itself");var r=Nf(e);r?Ho(function(){var i={done:!1};try{gr(r,e,mr(Uo,i,a),mr(br,i,a))}catch(s){br(i,s,a)}}):(a.value=e,a.state=Vf,qf(a,!1))}catch(i){br({done:!1},i,a)}}};if(Df&&(Bt=function(e){mP(this,za),hP(e),gr(Ka,this);var t=No(this);try{e(mr(Uo,t),mr(br,t))}catch(r){br(t,r)}},za=Bt.prototype,Ka=function(e){IP(this,{type:es,done:!1,notified:!1,parent:!1,reactions:new vP,rejection:!1,state:wf,value:void 0})},Ka.prototype=Pf(za,"then",function(e,t){var r=No(this),i=qo(bP(this,Bt));return r.parent=!0,i.ok=Ja(e)?e:!0,i.fail=Ja(t)&&t,i.domain=Xa?Go.domain:void 0,r.state===wf?r.reactions.add(i):Ho(function(){Ff(i,r)}),i.promise}),kf=function(){var a=new Ka,e=No(a);this.promise=a,this.resolve=mr(Uo,e),this.reject=mr(br,e)},Cf.f=qo=function(a){return a===Bt||a===wP?new kf(a):EP(a)},!lP&&Ja(Za)&&fr!==Object.prototype)){Rf=fr.then,TP||Pf(fr,"then",function(e,t){var r=this;return new Bt(function(i,s){gr(Rf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete fr.constructor}catch(a){}Af&&Af(fr,za)}cP({global:!0,constructor:!0,wrap:!0,forced:Df},{Promise:Bt});dP(Bt,es,!1,!0);pP(es)});var Qf=m((bC,Yf)=>{"use strict";var $P=te(),Gf=$P("iterator"),Wf=!1;try{jf=0,Yo={next:function(){return{done:!!jf++}},return:function(){Wf=!0}},Yo[Gf]=function(){return this},Array.from(Yo,function(){throw 2})}catch(a){}var jf,Yo;Yf.exports=function(a,e){try{if(!e&&!Wf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Gf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Qo=m((gC,zf)=>{"use strict";var LP=Dt(),MP=Qf(),CP=pr().CONSTRUCTOR;zf.exports=CP||!MP(function(a){LP.all(a).then(void 0,function(){})})});var Kf=m(()=>{"use strict";var DP=we(),BP=ye(),OP=Qe(),VP=hr(),_P=Qa(),NP=Ua(),FP=Qo();DP({target:"Promise",stat:!0,forced:FP},{all:function(e){var t=this,r=VP.f(t),i=r.resolve,s=r.reject,n=_P(function(){var o=OP(t.resolve),u=[],c=0,l=1;NP(e,function(d){var p=c++,h=!1;l++,BP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--l||i(u))},s)}),--l||i(u)});return n.error&&s(n.value),r.promise}})});var Xf=m(()=>{"use strict";var qP=we(),UP=Ve(),HP=pr().CONSTRUCTOR,Ko=Dt(),jP=Ye(),GP=W(),WP=cr(),Jf=Ko&&Ko.prototype;qP({target:"Promise",proto:!0,forced:HP,real:!0},{catch:function(a){return this.then(void 0,a)}});!UP&&GP(Ko)&&(zo=jP("Promise").prototype.catch,Jf.catch!==zo&&WP(Jf,"catch",zo,{unsafe:!0}));var zo});var Zf=m(()=>{"use strict";var YP=we(),QP=ye(),zP=Qe(),KP=hr(),JP=Qa(),XP=Ua(),ZP=Qo();YP({target:"Promise",stat:!0,forced:ZP},{race:function(e){var t=this,r=KP.f(t),i=r.reject,s=JP(function(){var n=zP(t.resolve);XP(e,function(o){QP(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var em=m(()=>{"use strict";var eA=we(),tA=hr(),rA=pr().CONSTRUCTOR;eA({target:"Promise",stat:!0,forced:rA},{reject:function(e){var t=tA.f(this),r=t.reject;return r(e),t.promise}})});var Jo=m((AC,tm)=>{"use strict";var iA=je(),aA=Pe(),sA=hr();tm.exports=function(a,e){if(iA(a),aA(e)&&e.constructor===a)return e;var t=sA.f(a),r=t.resolve;return r(e),t.promise}});var am=m(()=>{"use strict";var nA=we(),oA=Ye(),rm=Ve(),uA=Dt(),im=pr().CONSTRUCTOR,cA=Jo(),lA=oA("Promise"),dA=rm&&!im;nA({target:"Promise",stat:!0,forced:rm||im},{resolve:function(e){return cA(dA&&this===lA?uA:this,e)}})});var sm=m(()=>{"use strict";Hf();Kf();Xf();Zf();em();am()});var cm=m(()=>{"use strict";var pA=we(),hA=Ve(),ts=Dt(),fA=ve(),om=Ye(),um=W(),mA=yo(),nm=Jo(),bA=cr(),Zo=ts&&ts.prototype,gA=!!ts&&fA(function(){Zo.finally.call({then:function(){}},function(){})});pA({target:"Promise",proto:!0,real:!0,forced:gA},{finally:function(a){var e=mA(this,om("Promise")),t=um(a);return this.then(t?function(r){return nm(e,a()).then(function(){return r})}:a,t?function(r){return nm(e,a()).then(function(){throw r})}:a)}});!hA&&um(ts)&&(Xo=om("Promise").prototype.finally,Zo.finally!==Xo&&bA(Zo,"finally",Xo,{unsafe:!0}));var Xo});var rs=m((CC,lm)=>{"use strict";var SA=Ye();lm.exports=SA});var pm=m((DC,dm)=>{"use strict";gh();sm();cm();var vA=rs();dm.exports=vA("Promise","finally")});var fm=m((BC,hm)=>{"use strict";var yA=pm();hm.exports=yA});var is=m((OC,mm)=>{"use strict";var TA=fm();mm.exports=TA});var Fm=m(()=>{"use strict";var KA=we(),JA=Qr(),XA=Ca(),ZA=Ma(),ew=gn();KA({target:"Array",proto:!0},{at:function(e){var t=JA(this),r=XA(t),i=ZA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});ew("at")});var Um=m((GD,qm)=>{"use strict";Fm();var tw=rs();qm.exports=tw("Array","at")});var jm=m((WD,Hm)=>{"use strict";var rw=Um();Hm.exports=rw});var fi=m((YD,Gm)=>{"use strict";var iw=jm();Gm.exports=iw});var Kb=m(()=>{"use strict"});var Jb=m(()=>{"use strict"});var Zb=m((YV,Xb)=>{"use strict";var ck=Pe(),lk=tr(),dk=te(),pk=dk("match");Xb.exports=function(a){var e;return ck(a)&&((e=a[pk])!==void 0?!!e:lk(a)==="RegExp")}});var tg=m((QV,eg)=>{"use strict";var hk=ei(),fk=String;eg.exports=function(a){if(hk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fk(a)}});var ig=m((zV,rg)=>{"use strict";var mk=je();rg.exports=function(){var a=mk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var ng=m((KV,sg)=>{"use strict";var bk=ye(),gk=_e(),Sk=jr(),vk=ig(),ag=RegExp.prototype;sg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in ag)&&!gk(a,"flags")&&Sk(ag,a)?bk(vk,a):e}});var ug=m((JV,og)=>{"use strict";var Ru=ce(),yk=Qr(),Tk=Math.floor,wu=Ru("".charAt),Ik=Ru("".replace),ku=Ru("".slice),Ek=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xk=/\$([$&'`]|\d{1,2})/g;og.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=xk;return i!==void 0&&(i=yk(i),u=Ek),Ik(s,u,function(c,l){var d;switch(wu(l,0)){case"$":return"$";case"&":return a;case"`":return ku(e,0,t);case"'":return ku(e,n);case"<":d=i[ku(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Tk(p/10);return h===0?c:h<=o?r[h-1]===void 0?wu(l,1):r[h-1]+wu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var dg=m(()=>{"use strict";var Pk=we(),Ak=ye(),Lu=ce(),cg=Ur(),wk=W(),kk=rr(),Rk=Zb(),kr=tg(),$k=Wr(),Lk=ng(),Mk=ug(),Ck=te(),Dk=Ve(),Bk=Ck("replace"),Ok=TypeError,$u=Lu("".indexOf),Vk=Lu("".replace),lg=Lu("".slice),_k=Math.max;Pk({target:"String",proto:!0},{replaceAll:function(e,t){var r=cg(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!kk(e)){if(i=Rk(e),i&&(s=kr(cg(Lk(e))),!~$u(s,"g")))throw new Ok("`.replaceAll` does not allow non-global regexes");if(n=$k(e,Bk),n)return Ak(n,e,r,t);if(Dk&&i)return Vk(kr(r),e,t)}for(o=kr(r),u=kr(e),c=wk(t),c||(t=kr(t)),l=u.length,d=_k(1,l),p=$u(o,u);p!==-1;)h=c?kr(t(u,p,o)):Mk(u,o,p,[],void 0,t),b+=lg(o,f,p)+h,f=p+l,p=p+d>o.length?-1:$u(o,u,p+d);return f<o.length&&(b+=lg(o,f)),b}})});var hg=m((e_,pg)=>{"use strict";Kb();Jb();dg();var Nk=rs();pg.exports=Nk("String","replaceAll")});var mg=m((t_,fg)=>{"use strict";var Fk=hg();fg.exports=Fk});var gg=m((r_,bg)=>{"use strict";var qk=mg();bg.exports=qk});var Dc="2.0.111-dev.974e99b3.0";var ue=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ue||{}),lt=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(lt||{});var ya=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ya||{}),dn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(dn||{});var pn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(pn||{});import{assertNever as Fc,assertNonNullable as ov,isNonNullable as Ta,ValueSubject as hn,Subject as uv,Subscription as cv,merge as lv,observableFrom as dv,fromEvent as Oc,map as Vc,tap as _c,filterChanged as pv,isNullable as fn,ErrorCategory as Nc}from"@vkontakte/videoplayer-shared";var Bc=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ia=class{constructor(e){this.connection$=new hn(void 0);this.castState$=new hn("NOT_AVAILABLE");this.errorEvent$=new uv;this.realCastState$=new hn("NOT_AVAILABLE");this.subscription=new cv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ta((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Bc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Nc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ta(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();fn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();fn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Oc(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Fc(i.sessionState)}})).add(lv(Oc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_c(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Vc(i=>i.castState)),dv([r.getCastState()])).pipe(pv(),Vc(hv),_c(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ta(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();ov(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(fn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ta(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Nc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},hv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Fc(a)}};var mS=He(mo(),1);var Pm=He(is(),1);import{assertNever as bm}from"@vkontakte/videoplayer-shared";var ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:bm(t)}return a},eu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:bm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as IA,Subject as as,merge as gm}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new as;this.transitionEnded$=new as;this.transitionUpdated$=new as;this.forceChanged$=new as;this.stateChangeStarted$=gm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=gm(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||IA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as EA}from"@vkontakte/videoplayer-shared";var Sm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return EA(a)}};import{assertNever as Sr,assertNonNullable as Ot,debounce as vm,ErrorCategory as ym,fromEvent as Vt,isNonNullable as Tm,map as Im,merge as Em,observableFrom as xA,Subject as PA,Subscription as tu,timeout as AA,getHighestQuality as wA}from"@vkontakte/videoplayer-shared";var kA=5,RA=5,$A=500,xm=7e3,di=class{constructor(e){this.subscription=new tu;this.loadMediaTimeoutSubscription=new tu;this.videoState=new M("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Sr(e)}break}default:Sr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Sm(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new tu;this.subscription.add(e),this.subscription.add(Em(this.videoState.stateChangeStarted$.pipe(Im(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Im(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new PA;e.add(i.pipe(vm($A)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>kA)&&i.next(o),s=o})),e.add(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<RA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Sr(n)}}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Vt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Em(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xA(["init"])).pipe(vm(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),E(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&E(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var c;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];Ot(l);let d=wA(Object.keys(l));Ot(d);let p=l[d];Ot(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Ot(l),r=l.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];Ot(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Ot(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Ot(l),r=ee(l.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:ym.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Sr(e)}let n=new chrome.cast.media.MediaInfo((c=this.params.meta.videoId)!=null?c:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Tm(o)&&(n.metadata.title=o),Tm(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(AA(xm).subscribe(()=>s(`timeout(${xm})`)))});(0,Pm.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ym.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as wm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as LA}from"@vkontakte/videoplayer-shared";var Am=a=>{try{a.pause(),a.playbackRate=0,LA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as MA,Subscription as CA}from"@vkontakte/videoplayer-shared";var ru=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},iu=window.WeakMap?new WeakMap:new ru,au=window.WeakMap?new WeakMap:new Map,DA=(a,e=20)=>{let t=0;return MA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},le=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?wm(t):(t=document.createElement("video"),a.appendChild(t)),iu.set(t,r);let i=new CA;return i.add(DA(t,e)),au.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},de=a=>{let e=au.get(a);e==null||e.unsubscribe(),au.delete(a);let t=iu.get(a);iu.delete(a),t?wm(a):Am(a)};import{assertNonNullable as pi,isNonNullable as We,isNullable as VA,fromEvent as vr,merge as km,observableFrom as Rm,filterChanged as $m,map as hi,Subject as Lm,Subscription as _A,ValueSubject as NA,ErrorCategory as FA}from"@vkontakte/videoplayer-shared";import{isNonNullable as su,isNullable as BA,Subscription as OA}from"@vkontakte/videoplayer-shared";var ss=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=BA(i),c=new OA;return i&&c.add(i.subscribe(l=>{let d=a.getState();r(l,d)&&a.setState(l)},s)),r(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},Ge=(a,e,t)=>ss(e,()=>a.loop,r=>{su(r)&&(a.loop=r)},{onError:t}),pe=(a,e,t,r)=>ss(e,()=>({muted:a.muted,volume:a.volume}),i=>{su(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),ke=(a,e,t,r)=>ss(e,()=>a.playbackRate,i=>{su(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),pt=ss;var qA=a=>["__",a.language,a.label].join("|"),UA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},nu=class a{constructor(){this.available$=new Lm;this.current$=new NA(void 0);this.error$=new Lm;this.subscription=new _A;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:FA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(pt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{We(s)&&this.setInternal(s)},{equal:(s,n)=>We(s)&&We(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(hi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(pt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{We(s)&&this.setExternal(s)},{equal:(s,n)=>We(s)&&We(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(hi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(pt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(pt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){pi(this.video);let{textTracks:e}=this.video;this.subscription.add(vr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(km(vr(e,"addtrack"),vr(e,"removetrack"),Rm(["init"])).pipe(hi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),$m((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(km(vr(e,"change"),Rm(["init"])).pipe(hi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),hi(r=>r&&this.htmlTextTrackToITextTrack(r).id),$m()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(vr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(vr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;We(t.align)&&(i.align=t.align),We(t.position)&&(i.position=t.position),We(t.size)&&(i.size=t.size),We(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){pi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:qA(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){pi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(VA(e)||!UA(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){pi(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){pi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Re=nu;var Je=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Mm=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ou=a=>{let e=Mm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Cm=a=>{let e=Mm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as ht,merge as Bm,filterChanged as jA,isNonNullable as Om,Subject as GA,filter as Vm,mapTo as _m,combine as WA,once as YA,ErrorCategory as QA,ValueSubject as Nm,clientChecker as zA}from"@vkontakte/videoplayer-shared";var HA=3,Dm=(a,e,t=HA)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var he=a=>{let e=S=>$e(a,S).pipe(_m(void 0)),r=Bm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>$e(a,S))).pipe(ht(S=>S.type==="ended"?a.readyState<2:a.readyState<3),jA()),i=Bm($e(a,"progress"),$e(a,"timeupdate")).pipe(ht(()=>Dm(a.buffered,a.currentTime))),s=zA.isSafari?WA({play:e("play").pipe(YA()),playing:e("playing")}).pipe(_m(void 0)):e("playing"),n=$e(a,"volumechange").pipe(ht(()=>({muted:a.muted,volume:a.volume}))),o=$e(a,"ratechange").pipe(ht(()=>a.playbackRate)),u=$e(a,"error").pipe(Vm(()=>!!(a.error||a.played.length)),ht(()=>{var v;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:QA.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(v=a.error)!=null?v:void 0}})),c=$e(a,"timeupdate").pipe(ht(()=>a.currentTime)),l=new GA,d=.3,p;c.subscribe(S=>{a.loop&&Om(p)&&Om(S)&&p>=a.duration-d&&S<=d&&l.next(p),p=S});let h=e("pause").pipe(Vm(()=>!a.error&&p!==a.duration)),f=$e(a,"enterpictureinpicture"),b=$e(a,"leavepictureinpicture"),g=new Nm(Cm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let y=new Nm(ou(a));return $e(a,"fullscreenchange").pipe(ht(()=>ou(a))).subscribe(y),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:$e(a,"durationchange").pipe(ht(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:y}};import{VideoQuality as ft}from"@vkontakte/videoplayer-shared";var mt=a=>{switch(a){case"mobile":return ft.Q_144P;case"lowest":return ft.Q_240P;case"low":return ft.Q_360P;case"sd":case"medium":return ft.Q_480P;case"hd":case"high":return ft.Q_720P;case"fullhd":case"full":return ft.Q_1080P;case"quadhd":case"quad":return ft.Q_1440P;case"ultrahd":case"ultra":return ft.Q_2160P}};var _t=He(fi(),1);import{isNonNullable as fe,isNullable as cu,now as Zm,isHigher as lu,isHigherOrEqual as zm,isInvariantQuality as Km,isLower as du,isLowerOrEqual as Jm,videoSizeToQuality as aw,assertNotEmptyArray as eb,assertNonNullable as sw}from"@vkontakte/videoplayer-shared";var uu=!1,Xe={},Wm=a=>{uu=a},Ym=()=>{Xe={}},Qm=a=>{a(Xe)},mi=(a,e)=>{var t;uu&&(Xe.meta=(t=Xe.meta)!=null?t:{},Xe.meta[a]=e)},re=class{constructor(e){this.name=e}next(e){var r,i;if(!uu)return;Xe.series=(r=Xe.series)!=null?r:{};let t=(i=Xe.series[this.name])!=null?i:[];t.push([Date.now(),e]),Xe.series[this.name]=t}};var nw=new re("best_bitrate"),tb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var pu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),bi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Zm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},rb='Assertion "ABR Tracks is empty array" failed',ns=(a,e,t,r)=>{var u;let i=[...e].sort(pu(1)),s=[...t].sort(pu(1)),n=s.filter(c=>fe(c.bitrate)&&fe(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,_t.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,_t.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,_t.default)(n,-1):(0,_t.default)(s,0)},Xm=a=>"quality"in a,ib=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&Zm()-r.history[t.id]<=a.trackCooldown&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!i&&r.recordSelection(t),i&&(r!=null&&r.last)){let s=r.last;r==null||r.recordSwitch(s);let n=Xm(s)?"video":"audio",o=Xm(s)?s.quality:s.bitrate;return e({message:`
7
7
  [last ${n} selected] ${o}
8
8
  `}),s}return r==null||r.recordSwitch(t),t},bt=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:l,droppedVideoMaxQualityLimit:d,abrLogger:p})=>{var N,O,w,L,q;eb(a,rb);let h=r.usePixelRatio&&(N=window.devicePixelRatio)!=null?N:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},b=f&&aw(f),g=r.considerPlaybackRate&&fe(o)?o:1,y=a.filter(k=>!Km(k.quality)).sort((k,x)=>lu(k.quality,x.quality)?-1:1),I=(O=(0,_t.default)(y,-1))==null?void 0:O.quality,S=(w=(0,_t.default)(y,0))==null?void 0:w.quality,v=cu(i)||fe(i.min)&&fe(i.max)&&du(i.max,i.min)||fe(i.min)&&S&&lu(i.min,S)||fe(i.max)&&I&&du(i.max,I),T=g*tb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),R={},$=y.filter(k=>{if(!(b?du(k.quality,b):!0))return R[k.quality]="FitsContainer",!1;if(!(fe(t)&&isFinite(t)&&fe(k.bitrate)?t-s>=k.bitrate*T:!0))return R[k.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&fe(r.minBufferToSwitchUp)&&u&&!Km(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&lu(k.quality,u.quality))return R[k.quality]="Buffer",!1;if(!!d&&zm(k.quality,d))return R[k.quality]="DroppedFramesLimit",!1;let z=v||(cu(i.max)||Jm(k.quality,i.max))&&(cu(i.min)||zm(k.quality,i.min)),se=fe(l)&&!l?Jm(k.quality,r.backgroundVideoQualityLimit):!0;return!z||!se?(R[k.quality]="FitsQualityLimits",!1):!0})[0];$&&$.bitrate&&nw.next($.bitrate);let B=(L=$!=null?$:y[Math.ceil((y.length-1)/2)])!=null?L:a[0];return B.quality!==((q=c==null?void 0:c.last)==null?void 0:q.quality)&&p({message:`
9
9
  [VIDEO TRACKS ABR]
@@ -55,7 +55,7 @@ var tv=Object.create;var Cc=Object.defineProperty;var rv=Object.getOwnPropertyDe
55
55
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
56
56
 
57
57
  [selected audio track] ${h==null?void 0:h.id}
58
- `}),h&&ib(i,u,h,o)};var X=a=>new URL(a).hostname;import{assertNever as lb,assertNonNullable as db,combine as Aw,debounce as ww,ErrorCategory as pb,filter as hb,filterChanged as kw,isNonNullable as gu,map as ds,merge as fb,observableFrom as Rw,once as $w,Subscription as Lw,ValueSubject as Su,videoQualityToHeight as Mw,videoSizeToQuality as Cw}from"@vkontakte/videoplayer-shared";var sb=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},me=async a=>{let e=a.muted;try{await a.play()}catch(t){if(!sb(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(r){return sb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as us,isNullable as cw,assertNonNullable as vi}from"@vkontakte/videoplayer-shared";import{isNonNullable as nb,assertNonNullable as os,now as ow}from"@vkontakte/videoplayer-shared";function Z(){return ow()}function hu(a){return Z()-a}function fu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ob(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function yr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;os(l);let w=hu(l),L;if(w<b){L=b-w,setTimeout(g,L);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,R()},y=w=>(s=w,O),I=w=>(d=w,O),S=()=>(h="json",O),v=()=>{if(!u){if(--c>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},T=w=>(p=w,O),R=()=>{l=Z(),n=new i,n.open("get",a);let w=0,L,q=0,k=()=>(os(l),Math.max(l,Math.max(L||0,q||0)));if(s&&n.addEventListener("progress",x=>{let V=Z();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,L=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>v())),n.addEventListener("load",()=>{if(u)return;os(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let V=n.response.byteLength-w;V&&s.updateChunk&&s.updateChunk(k(),V)}n.responseType==="json"&&!Object.values(n.response).length?v():(d&&d(),e(n.response))}else v()}),n.addEventListener("error",()=>{v()}),p){let x=()=>{os(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=Z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),O},O={withBitrateReporting:y,withParallel:T,withJSONResponse:S,withRetryCount:w=>(c=w,O),withRetryInterval:(w,L)=>(nb(w)&&(b=w),nb(L)&&(f=L),O),withTimeout:w=>(o=w,O),withFinally:I,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return O}var gi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Si=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Z(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Z()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=yr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Z()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Z();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var cs=1e4,mu=3;var lw=6e4,dw=10,pw=1,hw=500,yi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new gi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=fu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=fu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||us(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ob(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Si(mu,cs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,c=null,l=!1,d=()=>{let v=s&&(!l||l===this.rep);return v||t("Not running!"),v},p=(v,T,R)=>{u&&u.abort(),u=yr(this.urlResolver.resolve(v,!1),T,R,()=>this._retryCallback()).withTimeout(cs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(mu).withFinally(()=>{u=null}).send()},h=(v,T,R)=>{vi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),T,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=v=>{let T=r.playbackRate;r.playbackRate!==v&&(t(`Playback rate switch: ${T}=>${v}`),r.playbackRate=v)},b=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=Z()-1e4,U=0;for(let B=0;B<this.bufferStates.length;B++){let N=this.bufferStates[B];v=Math.min(v,N.buf),N.ts<R&&U++}this.bufferStates.splice(0,U),t(`update playback rate; minBuffer=${v} drop=${U} jitter=${this.sourceJitter}`);let $=v-pw;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},y=v=>{let T,R=()=>T&&T.start?T.start.length:0,U=x=>T.start[x]/1e3,$=x=>T.dur[x]/1e3,B=x=>T.fragIndex+x,N=(x,V)=>({chunkIdx:B(x),startTS:U(x),dur:$(x),discontinuity:V}),O=()=>{let x=0;if(T&&T.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,G=V;this.sourceJitter>1&&(G+=this.sourceJitter-1);let z=T.dur.length-1;for(;z>=0&&(G-=T.dur[z],!(G<=0));--z);x=Math.min(z,T.dur.length-1-H),x=Math.max(x,0)}return N(x,!0)},w=x=>{let V=R();if(!(V<=0)){if(us(x)){for(let H=0;H<V;H++)if(U(H)>x)return N(H)}return O()}},L=x=>{let V=R(),H=x?x.chunkIdx+1:0,G=H-T.fragIndex;if(!(V<=0)){if(!x||G<0||G-V>dw)return t(`Resync: offset=${G} bChunks=${V} chunk=`+JSON.stringify(x)),O();if(!(G>=V))return N(H-T.fragIndex,!1)}},q=(x,V,H)=>{c&&c.abort(),c=yr(this.urlResolver.resolve(x,!0,this.lowLatency),V,H,()=>this._retryCallback()).withTimeout(cs).withRetryCount(mu).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,V)=>{q(v,H=>{if(!d())return;T=H;let G=!!T.lowLatency;G!==this.lowLatency&&b(G);let z=0;for(let se=0;se<T.dur.length;++se)z+=T.dur[se];z>0&&(vi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(z/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x(w(V))},()=>this._handleNetworkError())},nextChunk:L}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),vi(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:v=>{let{videoElement:T,logger:R}=this.params,U=y(e.jidxUrl),$,B,N,O,w=0,L,q,k,x=()=>{L&&(clearTimeout(L),L=void 0);let A=Math.max(hw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=w+A,Se=Z(),xe=Math.min(1e4,ne-Se);w=Se;let ot=()=>{c||d()&&U.seek(()=>{d()&&(w=Z(),V(),x())})};xe>0?L=window.setTimeout(()=>{this.paused?x():ot()},xe):ot()},V=()=>{let A;for(;A=U.nextChunk(O);)O=A,Et(A);let ne=U.nextChunk(N);if(ne){if(N&&ne.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}se(ne)}else x()},H=(A,ne)=>{if(!d()||!this.sourceBuffer)return;let Se,xe,ot,Kt=ut=>{window.setTimeout(()=>{d()&&H(A,ne)},ut)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),Kt(100);else{let ut=Z(),xt=T.currentTime;!this.paused&&T.buffered.length>1&&q===xt&&ut-k>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),q!==xt&&(q=xt,k=ut);let Jt=this._getBufferSizeSec();if(Jt>30)R(`Buffered ${Jt} seconds; delaying appendBuffer`),Kt(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:ut,buf:Jt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(Or){if(Or.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),ot=this.sourceBuffer.buffered.length,ot!==0&&(Se=this.sourceBuffer.buffered.start(0),xe=xt,xe-Se>4&&this.sourceBuffer.remove(Se,xe-3)),Kt(1e3);else throw Or}}},G=()=>{B&&$&&(R([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(N)]),H(B,function(){B=null,V()}))},z=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),se=A=>{d()&&h(z(A),(ne,Se)=>{if(d()){if(Se/=1e3,B=ne,N=A,n=A.startTS,Se){let xe=Math.min(10,A.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}G()}},()=>this._handleNetworkError())},Et=A=>{d()&&(vi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(z(A),!1)))},nt=A=>{d()&&(e.cachedHeader=A,H(A,()=>{$=!0,G()}))};s=!0,U.seek(A=>{if(d()){if(w=Z(),!A){x();return}O=A,!cw(v)||A.startTS>v?se(A):(N=A,V())}},v),e.cachedHeader?nt(e.cachedHeader):p(e.headerUrl,nt,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),us(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,vi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return us(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=Z();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&hu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=Z();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=yr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(cs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;me(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},lw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as fw,filter as ub,fromEvent as mw,interval as bw,isHigher as gw,isInvariantQuality as Sw,isLower as vw,merge as yw,Subject as cb,Subscription as Tw}from"@vkontakte/videoplayer-shared";var bu=class{constructor(){this.onDroopedVideoFramesLimit$=new cb;this.subscription=new Tw;this.playing=!1;this.tracks=[];this.forceChecker$=new cb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Sw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&gw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(mw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=bw(this.droppedFramesChecker.checkTime).pipe(ub(()=>this.playing),ub(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(fw(this.droppedFramesChecker.checkTime)),r=yw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>vw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ls=bu;import{map as Iw,Observable as Ew}from"@vkontakte/videoplayer-shared";import{fromEvent as xw}from"@vkontakte/videoplayer-shared";var Ti=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Pw=(a,e)=>new Ew(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ti()))},{...r,...e});i.observe(a);let s=xw(document,"visibilitychange").pipe(Iw(n=>!document.hidden||Ti())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Le=Pw;var Dw=["paused","playing","ready"],Bw=["paused","playing","ready"],Ii=class{constructor(e){this.subscription=new Lw;this.videoState=new M("stopped");this.representations$=new Su([]);this.textTracksManager=new Re;this.droppedFramesManager=new ls;this.maxSeekBackTime$=new Su(1/0);this.zeroTime$=new Su(void 0);this.liveOffset=new Je;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:pb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),l=(r=mt(u.name))!=null?r:Cw(u.video),d=u.bitrate/1e3,p={...u.video};if(!l)continue;let h={id:c,quality:l,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),gu(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Bw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Dw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ee(this.params.source.url,u))}return;default:return lb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:pb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};fb(this.videoState.stateChangeStarted$.pipe(ds(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ds(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=he(this.video);this.subscription.add(this.representations$.pipe(ds(i=>i.map(({track:s})=>s)),hb(i=>!!i.length),$w()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(kw(),ds(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Aw({zeroTime:this.zeroTime$.pipe(hb(gu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ge(this.video,this.params.desiredState.isLooped,t)).add(pe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ke(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Le(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Mw(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return lb(i.to)}},t)).add(fb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Rw(["init"])).pipe(ww(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),de(this.video)}createLiveDashPlayer(){let e=new yi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var c,l,d,p,h,f;let e=this.representations$.getValue(),t=(l=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?l:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&gu(t)?t:bt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;db(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;db(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var mb=Ii;var Ze=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as sR,assertNonNullable as nR,debounce as oR,ErrorCategory as Wu,filter as qg,filterChanged as Yu,fromEvent as uR,isNonNullable as cR,map as Ug,merge as Os,observableFrom as lR,observeElementSize as dR,once as Hg,Subscription as pR,ValueSubject as hR}from"@vkontakte/videoplayer-shared";var ps=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Tr=class extends ps{constructor(){super(),this.listeners||ps.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Ei=class{constructor(){Object.defineProperty(this,"signal",{value:new Tr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ei.prototype[Symbol.toStringTag]="AbortController",Tr.prototype[Symbol.toStringTag]="AbortSignal");function hs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function vu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!hs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(c,l){let d;l&&l.signal&&(d=l.signal,delete l.signal);let p=new t(c,l);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let l=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(l){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(l.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{l.addEventListener("abort",()=>f(d),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var xi=hs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),bb=xi?vu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,et=xi?bb.fetch:window.fetch,mB=xi?bb.Request:window.Request,tt=xi?Ei:window.AbortController,bB=xi?Tr:window.AbortSignal;var Rb=He(fi(),1);var rt=()=>window.ManagedMediaSource||window.MediaSource,fs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},gb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Sb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Es,clientChecker as Is}from"@vkontakte/videoplayer-shared";var Me=document.createElement("video"),_w='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Nw='video/mp4; codecs="hev1.1.6.L93.B0"',$b='video/webm; codecs="vp09.00.10.08"',Lb='video/webm; codecs="av01.0.00M.08"',Fw='audio/mp4; codecs="mp4a.40.2"',qw='audio/webm; codecs="opus"',vb,yb,Nt={mms:fs(),mse:gb(),hls:!!((vb=Me.canPlayType)!=null&&vb.call(Me,"application/x-mpegurl")||(yb=Me.canPlayType)!=null&&yb.call(Me,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Tb,Ib,be={mp4:!!((Tb=Me.canPlayType)!=null&&Tb.call(Me,"video/mp4")),webm:!!((Ib=Me.canPlayType)!=null&&Ib.call(Me,"video/webm")),cmaf:!0},bs,Eb,gs,xb,Ss,Pb,vs,Ab,ys,wb,Ts,kb,ge={h264:!!((Eb=(bs=rt())==null?void 0:bs.isTypeSupported)!=null&&Eb.call(bs,_w)),h265:!!((xb=(gs=rt())==null?void 0:gs.isTypeSupported)!=null&&xb.call(gs,Nw)),vp9:!!((Pb=(Ss=rt())==null?void 0:Ss.isTypeSupported)!=null&&Pb.call(Ss,$b)),av1:!!((Ab=(vs=rt())==null?void 0:vs.isTypeSupported)!=null&&Ab.call(vs,Lb)),aac:!!((wb=(ys=rt())==null?void 0:ys.isTypeSupported)!=null&&wb.call(ys,Fw)),opus:!!((kb=(Ts=rt())==null?void 0:Ts.isTypeSupported)!=null&&kb.call(Ts,qw))},Ir=(ge.h264||ge.h265)&&ge.aac,Ft,Uw=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Lb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:$b}})]);Ft={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Uw()}catch(a){console.error(a)}var Er=Nt.hls&&be.mp4,Mb=()=>Object.keys(ge).filter(a=>ge[a]),Cb=(a,e=!1,t=!1)=>{let r=Nt.mse||Nt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&be.mp4&&Ir;case"DASH_WEBM":return r&&be.webm&&ge.vp9&&ge.opus;case"DASH_WEBM_AV1":return r&&be.webm&&ge.av1&&ge.opus;case"DASH_STREAMS":return r&&(be.mp4&&Ir||be.webm&&(ge.vp9||ge.av1)&&(ge.opus||ge.aac));case"DASH_LIVE":return Nt.mse&&be.mp4&&Ir;case"DASH_LIVE_CMAF":return r&&be.mp4&&Ir&&be.cmaf;case"DASH_ONDEMAND":return r&&be.mp4&&Ir;case"HLS":case"HLS_ONDEMAND":return Er||e&&Nt.mse&&be.mp4&&Ir;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Er;case"MPEG":return be.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Nt.webrtc&&Nt.ws&&ge.h264&&(be.mp4||be.webm);default:return Es(i)}})},ms=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Ft?Ft[t].smooth?[t,e]:Ft[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ft?Ft[t].powerEfficient?[t,e]:Ft[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Es(a)}return[e,t]},Db=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ms(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Is.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...ms(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ms(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ms(a),...i,"HLS","HLS_ONDEMAND"];default:Es(e)}return Er?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Bb=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=Is.isMac&&Is.isSafari;if(Is.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Es(a)}else Er&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},yu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ob=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,Rb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Pi}from"@vkontakte/videoplayer-shared";var Vb=a=>{if(!a)return{id:"EmptyResponse",category:Pi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Pi.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Pi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Pi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Pi.PARSER,message:"Response is valid XML, but parser failed"}};var xr=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};import{abortable as Hu,assertNonNullable as Qt,combine as $s,ErrorCategory as St,filter as Ls,filterChanged as Dg,fromEvent as Mr,interval as ju,isNonNullable as Bg,map as Gu,merge as Cr,Subject as Og,Subscription as Vg,tap as Jk,throttle as Xk,clientChecker as Zk,ValueSubject as ie,flattenObject as ea,getTraceSubscriptionMethod as eR}from"@vkontakte/videoplayer-shared";var $r=He(fi(),1);var Hw=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},jw=a=>window.clearTimeout(a),_b=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Tu=_b?Hw:window.requestIdleCallback,$B=_b?jw:window.cancelIdleCallback;var wg=He(is(),1);import{assertNever as Gw,ErrorCategory as Nb,clientChecker as Iu,Subject as Fb}from"@vkontakte/videoplayer-shared";var Ww=16,qb=!1;try{qb=Iu.isSafari&&!!Iu.macVersion&&Iu.macVersion<=Ww}catch(a){console.error(a)}var Eu=class{constructor(e){this.bufferFull$=new Fb;this.error$=new Fb;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Nb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;qb&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Nb.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Gw(t)}}},Ub=Eu;var xu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Rr,assertNonNullable as Fe,ErrorCategory as Gt,fromEvent as Vu,getExponentialDelay as _u,isNonNullable as Nu,isNullable as Ce,once as Hk,Subject as jk,Subscription as Gk,ValueSubject as Qi}from"@vkontakte/videoplayer-shared";var F=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Pr=class extends F{};var Ai=class extends F{};var wi=class extends F{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ki=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var Q=class extends F{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var qt=class extends Q{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};var Li=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ci=class extends Q{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Di=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Bi=class extends Q{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Oi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends Q{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var _i=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ni=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var qi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends Q{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Hi=class extends Q{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ji=class extends Q{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Qw={ftyp:wi,moov:ki,moof:Ri,mdat:$i,sidx:qt,trak:Li,mdia:Oi,mfhd:Fi,tkhd:Vi,traf:qi,tfhd:Ui,tfdt:Hi,trun:ji,minf:_i,sv3d:Mi,st3d:Ci,prhd:Di,proj:Ni,equi:Bi,uuid:Ai,unknown:Pr},Ut=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Qw[e];return r?new r(t,new a):new Pr(t,new a)}};var Ar=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Kw=new TextDecoder("ascii"),Jw=a=>Kw.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Xw=a=>{let e=new qt(a,new Ut),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Zw=(a,e)=>{let r=new Ut().parse(a),i=new Ar(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},ek=(a,e)=>{let r=new Ut().parse(a),s=new Ar(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},tk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Ut().parse(a),i=new Ar(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Hb={validateData:Jw,parseInit:tk,getIndexRange:()=>{},parseSegments:Xw,parseFeedableSegmentChunk:Zw,getSegmentEndTime:ek};import{assertNonNullable as Au,isNonNullable as Yb,isNullable as ik}from"@vkontakte/videoplayer-shared";import{assertNever as rk}from"@vkontakte/videoplayer-shared";var jb={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Gb=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Gi(a,t),i=r in jb,s=i?jb[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,l=Gi(u),d=c*2**((o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Gi=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ne=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Gi(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:rk(e)}},Ht=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Gb(r);if(!e(i))return;i.type==="master"&&Ht(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Wb=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Gb(a);return Ht(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ne(o,n):s===17026?t=Ne(o,n):s===17029&&(r=Ne(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Qb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ak=[231,22612,22743,167,171,163,160,175],sk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return Ht(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ne(f,h);c=Gi(g)}else p!==21420&&(c=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ne(f,h):p===17545?i=Ne(f,h):p===21420&&c===475249515?u=Ne(f,h):p===374648427?Ht(f,({tag:g,type:y,value:I})=>g===30321?(l=Ne(I,y)===1,!1):!0):s&&n&&Qb.includes(p)&&(o=!0),!o}),Au(e,"Failed to parse webm Segment start"),Au(t,"Failed to parse webm Segment end"),Au(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},nk=a=>{if(ik(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ok=(a,e)=>{let t=!1,r=!1,i=o=>Yb(o.time)&&Yb(o.position),s=[],n;return Ht(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ne(c,u));break;case 183:break;case 241:n&&(n.position=Ne(c,u));break;default:t&&Qb.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},uk=a=>{let e=0,t=!1;try{Ht(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):ak.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},zb={validateData:Wb,parseInit:sk,getIndexRange:nk,parseSegments:ok,parseFeedableSegmentChunk:uk};var wr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return zb;case"mp4":return Hb}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Cu=He(gg(),1);var Mu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as vg,isNullable as yg}from"@vkontakte/videoplayer-shared";var Sg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Tg=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},jt=(a,e)=>{let t=a;t=(0,Cu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Cu.default)(t,n,(o,u)=>yg(s)?o:yg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Eg=(a,e)=>{var v,T,R,U,$,B,N,O,w,L,q,k,x,V,H,G,z,se,Et,nt,A,ne,Se,xe,ot,Kt,ut,xt,Jt,Or,cc,lc,dc,pc,hc,fc,mc,bc,gc,Sc,vc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(R=(T=(v=s.querySelector("BaseURL"))==null?void 0:v.textContent)==null?void 0:T.trim())!=null?R:"",u=n.children,c=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],g=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Tg(h);else if(f){let oe=Tg(f);vg(oe)&&(p=oe)}else g&&(p=parseInt(g,10));let y=0,I=($=(U=s.getAttribute("profiles"))==null?void 0:U.split(","))!=null?$:[];for(let oe of u){let DS=(B=oe.getAttribute("id"))!=null?B:"id"+(y++).toString(10),Vr=(N=oe.getAttribute("mimeType"))!=null?N:"",Js=(O=oe.getAttribute("codecs"))!=null?O:"",Xs=(w=oe.getAttribute("contentType"))!=null?w:Vr==null?void 0:Vr.split("/")[0],BS=(q=(L=oe.getAttribute("profiles"))==null?void 0:L.split(","))!=null?q:[],OS=(k=oe.getAttribute("lang"))!=null?k:void 0,VS=(H=(V=(x=oe.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:V.trim())!=null?H:void 0,_S=oe.querySelectorAll("Representation"),NS=oe.querySelector("SegmentTemplate"),FS=(z=(G=oe.querySelector("Role"))==null?void 0:G.getAttribute("value"))!=null?z:void 0,_r=Xs,J={id:DS,language:OS,isDefault:FS==="main",label:VS,codecs:Js,hdr:_r==="video"&&Mu(Js),mime:Vr,representations:[]};for(let K of _S){let qS=(se=K.getAttribute("lang"))!=null?se:void 0,US=(Et=K.getAttribute("label"))!=null?Et:void 0,HS=(ne=(A=(nt=K.querySelector("BaseURL"))==null?void 0:nt.textContent)==null?void 0:A.trim())!=null?ne:"",Zs=new URL(HS||o,e).toString(),Xt=(Se=K.getAttribute("mimeType"))!=null?Se:Vr,ma=(ot=(xe=K.getAttribute("codecs"))!=null?xe:Js)!=null?ot:"",en;if(Xs==="text"){let Pt=K.getAttribute("id")||"",tn=Pt.includes("_auto");en={id:Pt,isAuto:tn,kind:"text",url:Zs}}else{let Pt=(ut=(Kt=K.getAttribute("contentType"))!=null?Kt:Xt==null?void 0:Xt.split("/")[0])!=null?ut:Xs,tn=(Jt=(xt=oe.getAttribute("profiles"))==null?void 0:xt.split(","))!=null?Jt:[],jS=parseInt((Or=K.getAttribute("width"))!=null?Or:"",10),Rc=parseInt((cc=K.getAttribute("height"))!=null?cc:"",10),$c=parseInt((lc=K.getAttribute("bandwidth"))!=null?lc:"",10)/1e3,Lc=(dc=K.getAttribute("frameRate"))!=null?dc:"",GS=(pc=K.getAttribute("quality"))!=null?pc:void 0,WS=Lc?Sg(Lc):void 0,YS=(hc=K.getAttribute("id"))!=null?hc:"id"+(y++).toString(10),QS=Pt==="video"?`${Rc}p`:Pt==="audio"?`${$c}Kbps`:ma,zS=`${YS}@${QS}`,KS=[...I,...BS,...tn],rn,JS=K.querySelector("SegmentBase"),At=(fc=K.querySelector("SegmentTemplate"))!=null?fc:NS;if(JS){let wt=(bc=(mc=K.querySelector("SegmentBase Initialization"))==null?void 0:mc.getAttribute("range"))!=null?bc:"",[kt,sn]=wt.split("-").map(Zt=>parseInt(Zt,10)),ct={from:kt,to:sn},Nr=(gc=K.querySelector("SegmentBase"))==null?void 0:gc.getAttribute("indexRange"),[nn,ba]=Nr?Nr.split("-").map(Zt=>parseInt(Zt,10)):[],Fr=Nr?{from:nn,to:ba}:void 0;rn={type:"byteRange",url:Zs,initRange:ct,indexRange:Fr}}else if(At){let wt={representationId:(Sc=K.getAttribute("id"))!=null?Sc:void 0,bandwidth:(vc=K.getAttribute("bandwidth"))!=null?vc:void 0},kt=parseInt((yc=At.getAttribute("timescale"))!=null?yc:"",10),sn=(Tc=At.getAttribute("initialization"))!=null?Tc:"",ct=At.getAttribute("media"),Nr=(Ec=parseInt((Ic=At.getAttribute("startNumber"))!=null?Ic:"",10))!=null?Ec:1,nn=jt(sn,wt);if(!ct)throw new ReferenceError("No media attribute in SegmentTemplate");let ba=(xc=At.querySelectorAll("SegmentTimeline S"))!=null?xc:[],Fr=[],Zt=0,on="",un=0;if(ba.length){let ga=Nr,De=0;for(let er of ba){let Ue=parseInt((Pc=er.getAttribute("d"))!=null?Pc:"",10),Rt=parseInt((Ac=er.getAttribute("r"))!=null?Ac:"",10)||0,Sa=parseInt((wc=er.getAttribute("t"))!=null?wc:"",10);De=Number.isFinite(Sa)?Sa:De;let cn=Ue/kt*1e3,ln=De/kt*1e3;for(let va=0;va<Rt+1;va++){let ZS=jt(ct,{...wt,segmentNumber:ga.toString(10),segmentTime:(De+va*Ue).toString(10)}),Mc=(ln!=null?ln:0)+va*cn,ev=Mc+cn;ga++,Fr.push({time:{from:Mc,to:ev},url:ZS})}De+=(Rt+1)*Ue,Zt+=(Rt+1)*cn}un=De/kt*1e3,on=jt(ct,{...wt,segmentNumber:ga.toString(10),segmentTime:De.toString(10)})}else if(vg(p)){let De=parseInt((kc=At.getAttribute("duration"))!=null?kc:"",10)/kt*1e3,er=Math.ceil(p/De),Ue=0;for(let Rt=1;Rt<er;Rt++){let Sa=jt(ct,{...wt,segmentNumber:Rt.toString(10),segmentTime:Ue.toString(10)});Fr.push({time:{from:Ue,to:Ue+De},url:Sa}),Ue+=De}un=Ue,on=jt(ct,{...wt,segmentNumber:er.toString(10),segmentTime:Ue.toString(10)})}let XS={time:{from:un,to:1/0},url:on};rn={type:"template",baseUrl:Zs,segmentTemplateUrl:ct,initUrl:nn,totalSegmentsDurationMs:Zt,segments:Fr,nextSegmentBeyondManifest:XS,timescale:kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pt||!Xt)continue;let an={video:"video",audio:"audio",text:"text"}[Pt];if(!an)continue;_r||(_r=an),en={id:zS,kind:an,segmentReference:rn,profiles:KS,duration:p,bitrate:$c,mime:Xt,codecs:ma,width:jS,height:Rc,fps:WS,quality:GS}}J.language||(J.language=qS),J.label||(J.label=US),J.mime||(J.mime=Xt),J.codecs||(J.codecs=ma),J.hdr||(J.hdr=_r==="video"&&Mu(ma)),J.representations.push(en)}_r&&i[_r].push(J)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Wi=He(fi(),1);import{videoSizeToQuality as Uk}from"@vkontakte/videoplayer-shared";var xg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?mt(s):void 0)!=null?o:Uk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Pg=({id:a,bitrate:e})=>({id:a,bitrate:e}),xs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Wi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Wi.default)(t,-1)},Ag=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Bu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Wi.default)(r.split("."),0),isDefault:i}),Ou=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Wi.default)(i.split("."),0)}),Ps=a=>"url"in a,it=a=>a.type==="template",Yi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var zi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Qi(0);this.onLastSegment$=new Qi(!1);this.fullyBuffered$=new Qi(!1);this.playingRepresentation$=new Qi(void 0);this.playingRepresentationInit$=new Qi(void 0);this.error$=new jk;this.gaps=[];this.subscription=new Gk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new tt;this.destroyAbortController=new tt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Rr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Fe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ub(this.sourceBuffer),this.subscription.add(Vu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Vu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Gt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,xu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=Ze(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Fe(r,"No init buffer for starting representation"),Fe(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Rr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Fe(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ce(s)||Ce(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Fe(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Nu(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Rr(this.destroyAbortController.signal,async function*(e){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(f=>f.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!it(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(c=this.switchingToRepresentationId)!=null?c:this.downloadingRepresentationId,i=this.representations.get(r);Fe(i);let s=this.segments.get(r);Fe(s,"No segments for starting representation");let n=this.initData.get(r);if(Fe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if(Ce(e)||Ce(this.downloadingRepresentationId)||Ce(this.playingRepresentationId)||Ce(this.sourceBuffer)||!Ce(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Fe(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((c=i==null?void 0:i.time.to)!=null?c:0)-((l=i==null?void 0:i.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Ze(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&xu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ze(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,$r.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&Ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,$r.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;Nu(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!it(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,$r.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Fe(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!it(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),c=jt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+y||h<=r+y;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!(xr(this.sourceBuffer.buffered,p)&&xr(this.sourceBuffer.buffered,h)))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Rr(o,async function*(){let l=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!l)return;let d=new DataView(l);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=wr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Yi(l)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Rr(n,async function*(){let u=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Vu(window,"online").pipe(Hk()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Yi(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,$r.default)(e,0).byte.from,to:(0,$r.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,l)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=wr(n.mime).parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,g=p?d.byte.to-r:e.byteLength,y=b<i,I=g<=i;if(d.status==="downloading"&&y&&I){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,h),v=this.getCurrentPosition();Nu(v)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-v,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:l}),this.activeSegments.delete(l));let T=({segmentView:R,segmentProgress:U})=>this.sourceBufferTaskQueue.append(R,s).then($=>$&&!s.aborted?this.onSegmentFullyAppended(U,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Ce(v))&&(T({segmentView:S,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&!I&&(l.loadedBytes=Math.min(h,i-b),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===h?S:wr(o.mime).parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",l.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,s).then(T=>{if(s.aborted)n();else if(T)l.fedBytes+=v.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let l=c.byte.from-r,d=c.byte.to-r,p=d-l+1,h=l<i,f=d<=i;if(h){if(c.status==="downloading"&&f){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-l),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:wr(o.mime).parseFeedableSegmentChunk(b);g!=null&&g.byteLength&&(c.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ps(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");Fe(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(s=>this.sourceBuffer&&(Math.round(s.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(s.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Tu(()=>(0,wg.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Rr(this.destroyAbortController.signal,async function*(){let o=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,wr(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&it(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Gt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ce(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return i;i.push({...u.time}),i=n(i);let c=Ps(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return i.length?(await Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ce(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=c=>{var d;s=Math.min(s,c.time.from),n=Math.max(n,c.time.to);let l=Ps(c)?(d=c.size)!=null?d:0:c.byte.to-c.byte.from;i+=l};for(let c of this.segments.values())for(let l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let c of this.segments.values())for(let l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(s)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){let l=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)){s=l,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>e+c&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Tu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Gt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ce(this.sourceBuffer)||Ce(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=10;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?i.status="partially_ejected":this.gaps.some(l=>l.from===i.time.from||l.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Ki=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var kg=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ji,assertNever as Rg,fromEvent as $g,merge as Wk,now as Xi,Subscription as Yk,ValueSubject as Fu,flattenObject as Lr}from"@vkontakte/videoplayer-shared";var As=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new Fu(void 0);this.lastConnectionReused$=new Fu(void 0);this.lastRequestFirstBytes$=new Fu(void 0);this.abortAllController=new tt;this.subscription=new Yk;this.fetchManifest=Ji(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ki(r));let i=yield et(r,{signal:this.abortAllController.signal}).catch(Zi);return i?(t.log("success",Lr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Lr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ji(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,w;let c=e,l=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{l.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:Rg(t)}this.requestQuic&&(c=Ki(c));let p=this.abortAllController.signal,h;if(n){let L=new tt;if(h=Wk($g(this.abortAllController.signal,"abort"),$g(n,"abort")).subscribe(()=>{try{L.abort()}catch(q){Zi(q)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(q){Zi(q)}p=L.signal}let f=Xi();d.log("startRequest",Lr({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield et(c,{priority:s,headers:l,signal:p}).catch(Zi),g=Xi();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let L=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:L}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let L=Xi(),q={requestStartedAt:f,requestEndedAt:L,duration:L-f};return d.log("endRequest",Lr(q)),d.end(),b.arrayBuffer()}let[y,I]=b.body.tee(),S=y.getReader();o&&((w=this.throughputEstimator)==null||w.trackStream(I,u));let v=0,T=new Uint8Array(0),R=!1,U=L=>{h==null||h.unsubscribe(),R=!0,Zi(L)},$=Ji(p,async function*({done:L,value:q}){if(v===0&&this.lastRequestFirstBytes$.next(Xi()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&q){let k=new Uint8Array(T.length+q.length);k.set(T),k.set(q,T.length),T=k,v+=q.byteLength,i==null||i(new DataView(T.buffer),v),yield S==null?void 0:S.read().then($,U)}}.bind(this));yield S==null?void 0:S.read().then($,U),h==null||h.unsubscribe();let B=Xi(),N={failed:R,requestStartedAt:f,requestEndedAt:B,duration:B-f};return R?(d.error("endRequest",Lr(N)),d.end(),null):(d.log("endRequest",Lr(N)),d.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ji(this.abortAllController.signal,async function*(e,t,r){var y;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,i),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(y=e.indexRange)!=null?y:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ji(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=kg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Rg(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Zi=a=>{if(!Yi(a))throw a};var Wt=(a,e,t)=>t*e+(1-t)*a,qu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Lg=(a,e,t,r)=>{let i=0,s=t,n=qu(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as Qk,ValueSubject as Mg}from"@vkontakte/videoplayer-shared";var gt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Mg(e.initial),this.debounced$=new Mg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new re(`raw_${t}`),this.smoothedSeries$=new re(`smoothed_${t}`),this.reportedSeries$=new re(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(Qk(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var ws=class extends gt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Wt(this.slow,e,this.params.emaAlphaSlow),this.fast=Wt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ks=class extends gt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=qu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Wt(this.emaSmoothed,e,this.params.emaAlpha);let r=Lg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Rs=class extends gt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Wt(this.smoothed,t,this.params.emaAlpha):t}};var Yt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ws({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ks({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Rs({initial:e,label:"liveEdgeDelay",...t})}};var Uu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var _g=["timeupdate","progress","play","seeked","stalled","waiting"];var Ms=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Vg;this.representationSubscription=new Vg;this.state$=new M("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new Og;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.isLive$=new ie(!1);this.liveDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ie(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Og;this.gapWatchdogActive=!1;this.destroyController=new tt;this.initManifest=Hu(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:St.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Hu(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:St.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=Eg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Vb(e))!=null?n:{id:"ManifestParsing",category:St.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let r=(u,c,l)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,c)&&((f=(h=rt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${c}; codecs="${l}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let l=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(l.map(({codecs:h})=>h)),p=Ob(d);if(p&&(i[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);Zk.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",ea(s)),s}.bind(this));this.initRepresentations=Hu(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",ea({initialVideo:e,initialAudio:t,sourceHls:r})),Qt(this.manifest),Qt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Mr(p,"error").pipe(Ls(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:St.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Sb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&fs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new zi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Bg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new zi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ju(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=eu(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Cr(..._g.filter(p=>p!=="waiting").map(p=>Mr(this.element,p))).pipe(Gu(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),Dg(),Ls(p=>!!p),Jk(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Dg()).subscribe(h=>Uu(this.element,1))),this.representationSubscription.add($s({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Ls(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add($s({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,S=1;Math.abs(I)>g&&(S=1+Math.sign(I)*y),Uu(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let y=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(S=>{var v,T;return(T=(v=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:v.to)!=null?T:y}))-y}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add($s({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Xk(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(Qt(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=eu(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),U=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&U);let $="none";if(R?$="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&U?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),$="active_low_latency"):g!==0&&T<I?$="live_forward_buffering":T<I+v&&($="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let B=p-(I+S),N=this.normolizeLiveOffset(Math.trunc(g+B/b)),O=Math.abs(N-g),w;!h||O<=this.tuning.dashCmafLive.offsetCalculationError?w=g:N>0&&O>this.tuning.dashCmafLive.offsetCalculationError?w=N:w=0,this.manifestUrlString=ee(this.manifestUrlString,w,2)}$!=="none"&&$!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=Cr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Gu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Cr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Gu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Cr(this.forceEnded$,$s({allBuffersFull:u,someBufferEnded:c}).pipe(Ls(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:St.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Cr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),it(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&Bg(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ju(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:St.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new As({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Yt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s,n;Qt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video)),await((n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio)))}initBuffer(){Qt(this.element),this.state$.setState("running"),this.subscription.add(Cr(..._g.map(e=>Mr(this.element,e)),Mr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:St.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Mr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Mr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&xr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var n,o;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s={...s,liveLastSeekOffset:this.liveLastSeekOffset};else{let u=this.element.currentTime*1e3;(n=this.videoBufferManager)==null||n.maintain(u),(o=this.audioBufferManager)==null||o.maintain(u),s={...s,position:u}}this.tracer.log("stallIntervalCallback",ea(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=ju(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:St.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u,c;Qt(this.element),Qt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),xr(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(c=this.audioBufferManager)==null||c.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",ea({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=eR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ea(t)))}}};var Cs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ds=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Ng=`attribute vec2 a_vertex;
58
+ `}),h&&ib(i,u,h,o)};var X=a=>new URL(a).hostname;import{assertNever as lb,assertNonNullable as db,combine as Aw,debounce as ww,ErrorCategory as pb,filter as hb,filterChanged as kw,isNonNullable as gu,map as ds,merge as fb,observableFrom as Rw,once as $w,Subscription as Lw,ValueSubject as Su,videoQualityToHeight as Mw,videoSizeToQuality as Cw}from"@vkontakte/videoplayer-shared";var sb=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},me=async a=>{let e=a.muted;try{await a.play()}catch(t){if(!sb(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{await a.play()}catch(r){return sb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as us,isNullable as cw,assertNonNullable as vi}from"@vkontakte/videoplayer-shared";import{isNonNullable as nb,assertNonNullable as os,now as ow}from"@vkontakte/videoplayer-shared";function Z(){return ow()}function hu(a){return Z()-a}function fu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ob(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function yr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;os(l);let w=hu(l),L;if(w<b){L=b-w,setTimeout(g,L);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,R()},y=w=>(s=w,O),I=w=>(d=w,O),S=()=>(h="json",O),v=()=>{if(!u){if(--c>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},T=w=>(p=w,O),R=()=>{l=Z(),n=new i,n.open("get",a);let w=0,L,q=0,k=()=>(os(l),Math.max(l,Math.max(L||0,q||0)));if(s&&n.addEventListener("progress",x=>{let V=Z();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,L=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>v())),n.addEventListener("load",()=>{if(u)return;os(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let V=n.response.byteLength-w;V&&s.updateChunk&&s.updateChunk(k(),V)}n.responseType==="json"&&!Object.values(n.response).length?v():(d&&d(),e(n.response))}else v()}),n.addEventListener("error",()=>{v()}),p){let x=()=>{os(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=Z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),O},O={withBitrateReporting:y,withParallel:T,withJSONResponse:S,withRetryCount:w=>(c=w,O),withRetryInterval:(w,L)=>(nb(w)&&(b=w),nb(L)&&(f=L),O),withTimeout:w=>(o=w,O),withFinally:I,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return O}var gi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Si=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=Z(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Z()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=yr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Z()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Z();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var cs=1e4,mu=3;var lw=6e4,dw=10,pw=1,hw=500,yi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new gi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=fu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=fu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||us(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ob(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Si(mu,cs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,c=null,l=!1,d=()=>{let v=s&&(!l||l===this.rep);return v||t("Not running!"),v},p=(v,T,R)=>{u&&u.abort(),u=yr(this.urlResolver.resolve(v,!1),T,R,()=>this._retryCallback()).withTimeout(cs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(mu).withFinally(()=>{u=null}).send()},h=(v,T,R)=>{vi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),T,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=v=>{let T=r.playbackRate;r.playbackRate!==v&&(t(`Playback rate switch: ${T}=>${v}`),r.playbackRate=v)},b=v=>{this.lowLatency=v,t(`lowLatency changed to ${v}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=Z()-1e4,U=0;for(let B=0;B<this.bufferStates.length;B++){let N=this.bufferStates[B];v=Math.min(v,N.buf),N.ts<R&&U++}this.bufferStates.splice(0,U),t(`update playback rate; minBuffer=${v} drop=${U} jitter=${this.sourceJitter}`);let $=v-pw;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},y=v=>{let T,R=()=>T&&T.start?T.start.length:0,U=x=>T.start[x]/1e3,$=x=>T.dur[x]/1e3,B=x=>T.fragIndex+x,N=(x,V)=>({chunkIdx:B(x),startTS:U(x),dur:$(x),discontinuity:V}),O=()=>{let x=0;if(T&&T.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,G=V;this.sourceJitter>1&&(G+=this.sourceJitter-1);let z=T.dur.length-1;for(;z>=0&&(G-=T.dur[z],!(G<=0));--z);x=Math.min(z,T.dur.length-1-H),x=Math.max(x,0)}return N(x,!0)},w=x=>{let V=R();if(!(V<=0)){if(us(x)){for(let H=0;H<V;H++)if(U(H)>x)return N(H)}return O()}},L=x=>{let V=R(),H=x?x.chunkIdx+1:0,G=H-T.fragIndex;if(!(V<=0)){if(!x||G<0||G-V>dw)return t(`Resync: offset=${G} bChunks=${V} chunk=`+JSON.stringify(x)),O();if(!(G>=V))return N(H-T.fragIndex,!1)}},q=(x,V,H)=>{c&&c.abort(),c=yr(this.urlResolver.resolve(x,!0,this.lowLatency),V,H,()=>this._retryCallback()).withTimeout(cs).withRetryCount(mu).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,V)=>{q(v,H=>{if(!d())return;T=H;let G=!!T.lowLatency;G!==this.lowLatency&&b(G);let z=0;for(let se=0;se<T.dur.length;++se)z+=T.dur[se];z>0&&(vi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(z/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,x(w(V))},()=>this._handleNetworkError())},nextChunk:L}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),vi(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:v=>{let{videoElement:T,logger:R}=this.params,U=y(e.jidxUrl),$,B,N,O,w=0,L,q,k,x=()=>{L&&(clearTimeout(L),L=void 0);let A=Math.max(hw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=w+A,Se=Z(),xe=Math.min(1e4,ne-Se);w=Se;let ot=()=>{c||d()&&U.seek(()=>{d()&&(w=Z(),V(),x())})};xe>0?L=window.setTimeout(()=>{this.paused?x():ot()},xe):ot()},V=()=>{let A;for(;A=U.nextChunk(O);)O=A,Et(A);let ne=U.nextChunk(N);if(ne){if(N&&ne.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?x():(I(),this._initPlayerWith(e));return}se(ne)}else x()},H=(A,ne)=>{if(!d()||!this.sourceBuffer)return;let Se,xe,ot,Kt=ut=>{window.setTimeout(()=>{d()&&H(A,ne)},ut)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),Kt(100);else{let ut=Z(),xt=T.currentTime;!this.paused&&T.buffered.length>1&&q===xt&&ut-k>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),q!==xt&&(q=xt,k=ut);let Jt=this._getBufferSizeSec();if(Jt>30)R(`Buffered ${Jt} seconds; delaying appendBuffer`),Kt(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:ut,buf:Jt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(Or){if(Or.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),ot=this.sourceBuffer.buffered.length,ot!==0&&(Se=this.sourceBuffer.buffered.start(0),xe=xt,xe-Se>4&&this.sourceBuffer.remove(Se,xe-3)),Kt(1e3);else throw Or}}},G=()=>{B&&$&&(R([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(N)]),H(B,function(){B=null,V()}))},z=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),se=A=>{d()&&h(z(A),(ne,Se)=>{if(d()){if(Se/=1e3,B=ne,N=A,n=A.startTS,Se){let xe=Math.min(10,A.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}G()}},()=>this._handleNetworkError())},Et=A=>{d()&&(vi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(z(A),!1)))},nt=A=>{d()&&(e.cachedHeader=A,H(A,()=>{$=!0,G()}))};s=!0,U.seek(A=>{if(d()){if(w=Z(),!A){x();return}O=A,!cw(v)||A.startTS>v?se(A):(N=A,V())}},v),e.cachedHeader?nt(e.cachedHeader):p(e.headerUrl,nt,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),us(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,vi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return us(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=Z();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&hu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=Z();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=yr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(cs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;me(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},lw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as fw,filter as ub,fromEvent as mw,interval as bw,isHigher as gw,isInvariantQuality as Sw,isLower as vw,merge as yw,Subject as cb,Subscription as Tw}from"@vkontakte/videoplayer-shared";var bu=class{constructor(){this.onDroopedVideoFramesLimit$=new cb;this.subscription=new Tw;this.playing=!1;this.tracks=[];this.forceChecker$=new cb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Sw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&gw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(mw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=bw(this.droppedFramesChecker.checkTime).pipe(ub(()=>this.playing),ub(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(fw(this.droppedFramesChecker.checkTime)),r=yw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>vw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ls=bu;import{map as Iw,Observable as Ew}from"@vkontakte/videoplayer-shared";import{fromEvent as xw}from"@vkontakte/videoplayer-shared";var Ti=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Pw=(a,e)=>new Ew(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ti()))},{...r,...e});i.observe(a);let s=xw(document,"visibilitychange").pipe(Iw(n=>!document.hidden||Ti())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Le=Pw;var Dw=["paused","playing","ready"],Bw=["paused","playing","ready"],Ii=class{constructor(e){this.subscription=new Lw;this.videoState=new M("stopped");this.representations$=new Su([]);this.textTracksManager=new Re;this.droppedFramesManager=new ls;this.maxSeekBackTime$=new Su(1/0);this.zeroTime$=new Su(void 0);this.liveOffset=new Je;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:pb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),l=(r=mt(u.name))!=null?r:Cw(u.video),d=u.bitrate/1e3,p={...u.video};if(!l)continue;let h={id:c,quality:l,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),gu(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Bw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Dw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ee(this.params.source.url,u))}return;default:return lb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:pb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};fb(this.videoState.stateChangeStarted$.pipe(ds(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ds(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=le(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(X(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=he(this.video);this.subscription.add(this.representations$.pipe(ds(i=>i.map(({track:s})=>s)),hb(i=>!!i.length),$w()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(kw(),ds(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Aw({zeroTime:this.zeroTime$.pipe(hb(gu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ge(this.video,this.params.desiredState.isLooped,t)).add(pe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ke(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Le(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Mw(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return lb(i.to)}},t)).add(fb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Rw(["init"])).pipe(ww(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),de(this.video)}createLiveDashPlayer(){let e=new yi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var c,l,d,p,h,f;let e=this.representations$.getValue(),t=(l=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?l:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&gu(t)?t:bt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;db(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;db(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var mb=Ii;var Ze=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as sR,assertNonNullable as nR,debounce as oR,ErrorCategory as Wu,filter as qg,filterChanged as Yu,fromEvent as uR,isNonNullable as cR,map as Ug,merge as Os,observableFrom as lR,observeElementSize as dR,once as Hg,Subscription as pR,ValueSubject as hR}from"@vkontakte/videoplayer-shared";var ps=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Tr=class extends ps{constructor(){super(),this.listeners||ps.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Ei=class{constructor(){Object.defineProperty(this,"signal",{value:new Tr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ei.prototype[Symbol.toStringTag]="AbortController",Tr.prototype[Symbol.toStringTag]="AbortSignal");function hs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function vu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!hs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(c,l){let d;l&&l.signal&&(d=l.signal,delete l.signal);let p=new t(c,l);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let l=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(l){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(l.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{l.addEventListener("abort",()=>f(d),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var xi=hs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),bb=xi?vu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,et=xi?bb.fetch:window.fetch,mB=xi?bb.Request:window.Request,tt=xi?Ei:window.AbortController,bB=xi?Tr:window.AbortSignal;var Rb=He(fi(),1);var rt=()=>window.ManagedMediaSource||window.MediaSource,fs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},gb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Sb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Es,clientChecker as Is}from"@vkontakte/videoplayer-shared";var Me=document.createElement("video"),_w='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Nw='video/mp4; codecs="hev1.1.6.L93.B0"',$b='video/webm; codecs="vp09.00.10.08"',Lb='video/webm; codecs="av01.0.00M.08"',Fw='audio/mp4; codecs="mp4a.40.2"',qw='audio/webm; codecs="opus"',vb,yb,Nt={mms:fs(),mse:gb(),hls:!!((vb=Me.canPlayType)!=null&&vb.call(Me,"application/x-mpegurl")||(yb=Me.canPlayType)!=null&&yb.call(Me,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Tb,Ib,be={mp4:!!((Tb=Me.canPlayType)!=null&&Tb.call(Me,"video/mp4")),webm:!!((Ib=Me.canPlayType)!=null&&Ib.call(Me,"video/webm")),cmaf:!0},bs,Eb,gs,xb,Ss,Pb,vs,Ab,ys,wb,Ts,kb,ge={h264:!!((Eb=(bs=rt())==null?void 0:bs.isTypeSupported)!=null&&Eb.call(bs,_w)),h265:!!((xb=(gs=rt())==null?void 0:gs.isTypeSupported)!=null&&xb.call(gs,Nw)),vp9:!!((Pb=(Ss=rt())==null?void 0:Ss.isTypeSupported)!=null&&Pb.call(Ss,$b)),av1:!!((Ab=(vs=rt())==null?void 0:vs.isTypeSupported)!=null&&Ab.call(vs,Lb)),aac:!!((wb=(ys=rt())==null?void 0:ys.isTypeSupported)!=null&&wb.call(ys,Fw)),opus:!!((kb=(Ts=rt())==null?void 0:Ts.isTypeSupported)!=null&&kb.call(Ts,qw))},Ir=(ge.h264||ge.h265)&&ge.aac,Ft,Uw=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Lb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:$b}})]);Ft={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Uw()}catch(a){console.error(a)}var Er=Nt.hls&&be.mp4,Mb=()=>Object.keys(ge).filter(a=>ge[a]),Cb=(a,e=!1,t=!1)=>{let r=Nt.mse||Nt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&be.mp4&&Ir;case"DASH_WEBM":return r&&be.webm&&ge.vp9&&ge.opus;case"DASH_WEBM_AV1":return r&&be.webm&&ge.av1&&ge.opus;case"DASH_STREAMS":return r&&(be.mp4&&Ir||be.webm&&(ge.vp9||ge.av1)&&(ge.opus||ge.aac));case"DASH_LIVE":return Nt.mse&&be.mp4&&Ir;case"DASH_LIVE_CMAF":return r&&be.mp4&&Ir&&be.cmaf;case"DASH_ONDEMAND":return r&&be.mp4&&Ir;case"HLS":case"HLS_ONDEMAND":return Er||e&&Nt.mse&&be.mp4&&Ir;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Er;case"MPEG":return be.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Nt.webrtc&&Nt.ws&&ge.h264&&(be.mp4||be.webm);default:return Es(i)}})},ms=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Ft?Ft[t].smooth?[t,e]:Ft[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ft?Ft[t].powerEfficient?[t,e]:Ft[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Es(a)}return[e,t]},Db=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ms(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Is.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...ms(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ms(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ms(a),...i,"HLS","HLS_ONDEMAND"];default:Es(e)}return Er?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Bb=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=Is.isMac&&Is.isSafari;if(Is.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Es(a)}else Er&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},yu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ob=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,Rb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as Pi}from"@vkontakte/videoplayer-shared";var Vb=a=>{if(!a)return{id:"EmptyResponse",category:Pi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Pi.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Pi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Pi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Pi.PARSER,message:"Response is valid XML, but parser failed"}};var xr=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};import{abortable as Hu,assertNonNullable as Qt,combine as $s,ErrorCategory as St,filter as Ls,filterChanged as Dg,fromEvent as Mr,interval as ju,isNonNullable as Bg,map as Gu,merge as Cr,Subject as Og,Subscription as Vg,tap as Jk,throttle as Xk,clientChecker as Zk,ValueSubject as ie,flattenObject as ea,getTraceSubscriptionMethod as eR}from"@vkontakte/videoplayer-shared";var $r=He(fi(),1);var Hw=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},jw=a=>window.clearTimeout(a),_b=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Tu=_b?Hw:window.requestIdleCallback,$B=_b?jw:window.cancelIdleCallback;var wg=He(is(),1);import{assertNever as Gw,ErrorCategory as Nb,clientChecker as Iu,Subject as Fb}from"@vkontakte/videoplayer-shared";var Ww=16,qb=!1;try{qb=Iu.isSafari&&!!Iu.macVersion&&Iu.macVersion<=Ww}catch(a){console.error(a)}var Eu=class{constructor(e){this.bufferFull$=new Fb;this.error$=new Fb;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Nb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;qb&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Nb.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Gw(t)}}},Ub=Eu;var xu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Rr,assertNonNullable as Ce,ErrorCategory as Gt,fromEvent as Vu,getExponentialDelay as _u,isNonNullable as Nu,isNullable as De,once as Hk,Subject as jk,Subscription as Gk,ValueSubject as Qi}from"@vkontakte/videoplayer-shared";var F=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Pr=class extends F{};var Ai=class extends F{};var wi=class extends F{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ki=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var Q=class extends F{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var qt=class extends Q{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};var Li=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ci=class extends Q{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Di=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Bi=class extends Q{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Oi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends Q{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var _i=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ni=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fi=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var qi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends Q{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Hi=class extends Q{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ji=class extends Q{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Qw={ftyp:wi,moov:ki,moof:Ri,mdat:$i,sidx:qt,trak:Li,mdia:Oi,mfhd:Fi,tkhd:Vi,traf:qi,tfhd:Ui,tfdt:Hi,trun:ji,minf:_i,sv3d:Mi,st3d:Ci,prhd:Di,proj:Ni,equi:Bi,uuid:Ai,unknown:Pr},Ut=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Qw[e];return r?new r(t,new a):new Pr(t,new a)}};var Ar=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Kw=new TextDecoder("ascii"),Jw=a=>Kw.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Xw=a=>{let e=new qt(a,new Ut),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Zw=(a,e)=>{let r=new Ut().parse(a),i=new Ar(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},ek=(a,e)=>{let r=new Ut().parse(a),s=new Ar(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},tk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Ut().parse(a),i=new Ar(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Hb={validateData:Jw,parseInit:tk,getIndexRange:()=>{},parseSegments:Xw,parseFeedableSegmentChunk:Zw,getSegmentEndTime:ek};import{assertNonNullable as Au,isNonNullable as Yb,isNullable as ik}from"@vkontakte/videoplayer-shared";import{assertNever as rk}from"@vkontakte/videoplayer-shared";var jb={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Gb=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Gi(a,t),i=r in jb,s=i?jb[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,l=Gi(u),d=c*2**((o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Gi=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Gi(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:rk(e)}},Ht=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Gb(r);if(!e(i))return;i.type==="master"&&Ht(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Wb=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Gb(a);return Ht(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Fe(o,n):s===17026?t=Fe(o,n):s===17029&&(r=Fe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Qb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ak=[231,22612,22743,167,171,163,160,175],sk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return Ht(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Fe(f,h);c=Gi(g)}else p!==21420&&(c=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Fe(f,h):p===17545?i=Fe(f,h):p===21420&&c===475249515?u=Fe(f,h):p===374648427?Ht(f,({tag:g,type:y,value:I})=>g===30321?(l=Fe(I,y)===1,!1):!0):s&&n&&Qb.includes(p)&&(o=!0),!o}),Au(e,"Failed to parse webm Segment start"),Au(t,"Failed to parse webm Segment end"),Au(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},nk=a=>{if(ik(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ok=(a,e)=>{let t=!1,r=!1,i=o=>Yb(o.time)&&Yb(o.position),s=[],n;return Ht(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Fe(c,u));break;case 183:break;case 241:n&&(n.position=Fe(c,u));break;default:t&&Qb.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},uk=a=>{let e=0,t=!1;try{Ht(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):ak.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},zb={validateData:Wb,parseInit:sk,getIndexRange:nk,parseSegments:ok,parseFeedableSegmentChunk:uk};var wr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return zb;case"mp4":return Hb}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Cu=He(gg(),1);var Mu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as vg,isNullable as yg}from"@vkontakte/videoplayer-shared";var Sg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Tg=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},jt=(a,e)=>{let t=a;t=(0,Cu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Cu.default)(t,n,(o,u)=>yg(s)?o:yg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Eg=(a,e)=>{var v,T,R,U,$,B,N,O,w,L,q,k,x,V,H,G,z,se,Et,nt,A,ne,Se,xe,ot,Kt,ut,xt,Jt,Or,cc,lc,dc,pc,hc,fc,mc,bc,gc,Sc,vc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(R=(T=(v=s.querySelector("BaseURL"))==null?void 0:v.textContent)==null?void 0:T.trim())!=null?R:"",u=n.children,c=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],g=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Tg(h);else if(f){let oe=Tg(f);vg(oe)&&(p=oe)}else g&&(p=parseInt(g,10));let y=0,I=($=(U=s.getAttribute("profiles"))==null?void 0:U.split(","))!=null?$:[];for(let oe of u){let DS=(B=oe.getAttribute("id"))!=null?B:"id"+(y++).toString(10),Vr=(N=oe.getAttribute("mimeType"))!=null?N:"",Js=(O=oe.getAttribute("codecs"))!=null?O:"",Xs=(w=oe.getAttribute("contentType"))!=null?w:Vr==null?void 0:Vr.split("/")[0],BS=(q=(L=oe.getAttribute("profiles"))==null?void 0:L.split(","))!=null?q:[],OS=(k=oe.getAttribute("lang"))!=null?k:void 0,VS=(H=(V=(x=oe.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:V.trim())!=null?H:void 0,_S=oe.querySelectorAll("Representation"),NS=oe.querySelector("SegmentTemplate"),FS=(z=(G=oe.querySelector("Role"))==null?void 0:G.getAttribute("value"))!=null?z:void 0,_r=Xs,J={id:DS,language:OS,isDefault:FS==="main",label:VS,codecs:Js,hdr:_r==="video"&&Mu(Js),mime:Vr,representations:[]};for(let K of _S){let qS=(se=K.getAttribute("lang"))!=null?se:void 0,US=(Et=K.getAttribute("label"))!=null?Et:void 0,HS=(ne=(A=(nt=K.querySelector("BaseURL"))==null?void 0:nt.textContent)==null?void 0:A.trim())!=null?ne:"",Zs=new URL(HS||o,e).toString(),Xt=(Se=K.getAttribute("mimeType"))!=null?Se:Vr,ma=(ot=(xe=K.getAttribute("codecs"))!=null?xe:Js)!=null?ot:"",en;if(Xs==="text"){let Pt=K.getAttribute("id")||"",tn=Pt.includes("_auto");en={id:Pt,isAuto:tn,kind:"text",url:Zs}}else{let Pt=(ut=(Kt=K.getAttribute("contentType"))!=null?Kt:Xt==null?void 0:Xt.split("/")[0])!=null?ut:Xs,tn=(Jt=(xt=oe.getAttribute("profiles"))==null?void 0:xt.split(","))!=null?Jt:[],jS=parseInt((Or=K.getAttribute("width"))!=null?Or:"",10),Rc=parseInt((cc=K.getAttribute("height"))!=null?cc:"",10),$c=parseInt((lc=K.getAttribute("bandwidth"))!=null?lc:"",10)/1e3,Lc=(dc=K.getAttribute("frameRate"))!=null?dc:"",GS=(pc=K.getAttribute("quality"))!=null?pc:void 0,WS=Lc?Sg(Lc):void 0,YS=(hc=K.getAttribute("id"))!=null?hc:"id"+(y++).toString(10),QS=Pt==="video"?`${Rc}p`:Pt==="audio"?`${$c}Kbps`:ma,zS=`${YS}@${QS}`,KS=[...I,...BS,...tn],rn,JS=K.querySelector("SegmentBase"),At=(fc=K.querySelector("SegmentTemplate"))!=null?fc:NS;if(JS){let wt=(bc=(mc=K.querySelector("SegmentBase Initialization"))==null?void 0:mc.getAttribute("range"))!=null?bc:"",[kt,sn]=wt.split("-").map(Zt=>parseInt(Zt,10)),ct={from:kt,to:sn},Nr=(gc=K.querySelector("SegmentBase"))==null?void 0:gc.getAttribute("indexRange"),[nn,ba]=Nr?Nr.split("-").map(Zt=>parseInt(Zt,10)):[],Fr=Nr?{from:nn,to:ba}:void 0;rn={type:"byteRange",url:Zs,initRange:ct,indexRange:Fr}}else if(At){let wt={representationId:(Sc=K.getAttribute("id"))!=null?Sc:void 0,bandwidth:(vc=K.getAttribute("bandwidth"))!=null?vc:void 0},kt=parseInt((yc=At.getAttribute("timescale"))!=null?yc:"",10),sn=(Tc=At.getAttribute("initialization"))!=null?Tc:"",ct=At.getAttribute("media"),Nr=(Ec=parseInt((Ic=At.getAttribute("startNumber"))!=null?Ic:"",10))!=null?Ec:1,nn=jt(sn,wt);if(!ct)throw new ReferenceError("No media attribute in SegmentTemplate");let ba=(xc=At.querySelectorAll("SegmentTimeline S"))!=null?xc:[],Fr=[],Zt=0,on="",un=0;if(ba.length){let ga=Nr,Be=0;for(let er of ba){let Ue=parseInt((Pc=er.getAttribute("d"))!=null?Pc:"",10),Rt=parseInt((Ac=er.getAttribute("r"))!=null?Ac:"",10)||0,Sa=parseInt((wc=er.getAttribute("t"))!=null?wc:"",10);Be=Number.isFinite(Sa)?Sa:Be;let cn=Ue/kt*1e3,ln=Be/kt*1e3;for(let va=0;va<Rt+1;va++){let ZS=jt(ct,{...wt,segmentNumber:ga.toString(10),segmentTime:(Be+va*Ue).toString(10)}),Mc=(ln!=null?ln:0)+va*cn,ev=Mc+cn;ga++,Fr.push({time:{from:Mc,to:ev},url:ZS})}Be+=(Rt+1)*Ue,Zt+=(Rt+1)*cn}un=Be/kt*1e3,on=jt(ct,{...wt,segmentNumber:ga.toString(10),segmentTime:Be.toString(10)})}else if(vg(p)){let Be=parseInt((kc=At.getAttribute("duration"))!=null?kc:"",10)/kt*1e3,er=Math.ceil(p/Be),Ue=0;for(let Rt=1;Rt<er;Rt++){let Sa=jt(ct,{...wt,segmentNumber:Rt.toString(10),segmentTime:Ue.toString(10)});Fr.push({time:{from:Ue,to:Ue+Be},url:Sa}),Ue+=Be}un=Ue,on=jt(ct,{...wt,segmentNumber:er.toString(10),segmentTime:Ue.toString(10)})}let XS={time:{from:un,to:1/0},url:on};rn={type:"template",baseUrl:Zs,segmentTemplateUrl:ct,initUrl:nn,totalSegmentsDurationMs:Zt,segments:Fr,nextSegmentBeyondManifest:XS,timescale:kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pt||!Xt)continue;let an={video:"video",audio:"audio",text:"text"}[Pt];if(!an)continue;_r||(_r=an),en={id:zS,kind:an,segmentReference:rn,profiles:KS,duration:p,bitrate:$c,mime:Xt,codecs:ma,width:jS,height:Rc,fps:WS,quality:GS}}J.language||(J.language=qS),J.label||(J.label=US),J.mime||(J.mime=Xt),J.codecs||(J.codecs=ma),J.hdr||(J.hdr=_r==="video"&&Mu(ma)),J.representations.push(en)}_r&&i[_r].push(J)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Wi=He(fi(),1);import{videoSizeToQuality as Uk}from"@vkontakte/videoplayer-shared";var xg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?mt(s):void 0)!=null?o:Uk({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Pg=({id:a,bitrate:e})=>({id:a,bitrate:e}),xs=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Wi.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Wi.default)(t,-1)},Ag=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Bu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Wi.default)(r.split("."),0),isDefault:i}),Ou=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Wi.default)(i.split("."),0)}),Ps=a=>"url"in a,it=a=>a.type==="template",Yi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var zi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Qi(0);this.onLastSegment$=new Qi(!1);this.fullyBuffered$=new Qi(!1);this.playingRepresentation$=new Qi(void 0);this.playingRepresentationInit$=new Qi(void 0);this.error$=new jk;this.gaps=[];this.subscription=new Gk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new tt;this.destroyAbortController=new tt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Rr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ce(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Ub(this.sourceBuffer),this.subscription.add(Vu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Vu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Gt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,xu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=Ze(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ce(r,"No init buffer for starting representation"),Ce(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Rr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ce(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(De(s)||De(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ce(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Nu(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Rr(this.destroyAbortController.signal,async function*(e){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(f=>f.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!it(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(c=this.switchingToRepresentationId)!=null?c:this.downloadingRepresentationId,i=this.representations.get(r);Ce(i);let s=this.segments.get(r);Ce(s,"No segments for starting representation");let n=this.initData.get(r);if(Ce(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if(De(e)||De(this.downloadingRepresentationId)||De(this.playingRepresentationId)||De(this.sourceBuffer)||!De(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ce(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((c=i==null?void 0:i.time.to)!=null?c:0)-((l=i==null?void 0:i.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=Ze(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&xu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Ze(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,$r.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&Ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,$r.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;Nu(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!it(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,$r.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ce(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!it(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),c=jt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&p<=r+y||h<=r+y;return(d==="none"||d==="partially_ejected"&&g&&I&&this.sourceBuffer&&!(xr(this.sourceBuffer.buffered,p)&&xr(this.sourceBuffer.buffered,h)))&&g&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Rr(o,async function*(){let l=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!l)return;let d=new DataView(l);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=wr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Yi(l)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Rr(n,async function*(){let u=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Vu(window,"online").pipe(Hk()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Yi(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,$r.default)(e,0).byte.from,to:(0,$r.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,l)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=wr(n.mime).parseFeedableSegmentChunk(c,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,g=p?d.byte.to-r:e.byteLength,y=b<i,I=g<=i;if(d.status==="downloading"&&y&&I){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+b,h),v=this.getCurrentPosition();Nu(v)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-v,this.bufferAccumulation.accumulated.push({segmentView:S,segmentProgress:l}),this.activeSegments.delete(l));let T=({segmentView:R,segmentProgress:U})=>this.sourceBufferTaskQueue.append(R,s).then($=>$&&!s.aborted?this.onSegmentFullyAppended(U,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||De(v))&&(T({segmentView:S,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&!I&&(l.loadedBytes=Math.min(h,i-b),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===h?S:wr(o.mime).parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",l.feedingBytes+=v.byteLength,this.sourceBufferTaskQueue.append(v,s).then(T=>{if(s.aborted)n();else if(T)l.fedBytes+=v.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let l=c.byte.from-r,d=c.byte.to-r,p=d-l+1,h=l<i,f=d<=i;if(h){if(c.status==="downloading"&&f){c.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-l),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?b:wr(o.mime).parseFeedableSegmentChunk(b);g!=null&&g.byteLength&&(c.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ps(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");Ce(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Tu(()=>(0,wg.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Rr(this.destroyAbortController.signal,async function*(){let o=_u(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,wr(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&it(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Gt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)}async pruneBufferNew(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||De(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return i;i.push({...u.time}),i=n(i);let c=Ps(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return i.length?(await Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1}async pruneBufferOld(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||De(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=c=>{var d;s=Math.min(s,c.time.from),n=Math.max(n,c.time.to);let l=Ps(c)?(d=c.size)!=null?d:0:c.byte.to-c.byte.from;i+=l};for(let c of this.segments.values())for(let l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let c of this.segments.values())for(let l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(s)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){let l=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)){s=l,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>e+c&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){Ce(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Tu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Gt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(De(this.sourceBuffer)||De(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=10;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?i.status="partially_ejected":this.gaps.some(l=>l.from===i.time.from||l.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Ki=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var kg=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ji,assertNever as Rg,fromEvent as $g,merge as Wk,now as Xi,Subscription as Yk,ValueSubject as Fu,flattenObject as Lr}from"@vkontakte/videoplayer-shared";var As=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new Fu(void 0);this.lastConnectionReused$=new Fu(void 0);this.lastRequestFirstBytes$=new Fu(void 0);this.abortAllController=new tt;this.subscription=new Yk;this.fetchManifest=Ji(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ki(r));let i=yield et(r,{signal:this.abortAllController.signal}).catch(Zi);return i?(t.log("success",Lr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Lr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ji(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,w;let c=e,l=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{l.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:Rg(t)}this.requestQuic&&(c=Ki(c));let p=this.abortAllController.signal,h;if(n){let L=new tt;if(h=Wk($g(this.abortAllController.signal,"abort"),$g(n,"abort")).subscribe(()=>{try{L.abort()}catch(q){Zi(q)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(q){Zi(q)}p=L.signal}let f=Xi();d.log("startRequest",Lr({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield et(c,{priority:s,headers:l,signal:p}).catch(Zi),g=Xi();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let L=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:L}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let L=Xi(),q={requestStartedAt:f,requestEndedAt:L,duration:L-f};return d.log("endRequest",Lr(q)),d.end(),b.arrayBuffer()}let[y,I]=b.body.tee(),S=y.getReader();o&&((w=this.throughputEstimator)==null||w.trackStream(I,u));let v=0,T=new Uint8Array(0),R=!1,U=L=>{h==null||h.unsubscribe(),R=!0,Zi(L)},$=Ji(p,async function*({done:L,value:q}){if(v===0&&this.lastRequestFirstBytes$.next(Xi()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&q){let k=new Uint8Array(T.length+q.length);k.set(T),k.set(q,T.length),T=k,v+=q.byteLength,i==null||i(new DataView(T.buffer),v),yield S==null?void 0:S.read().then($,U)}}.bind(this));yield S==null?void 0:S.read().then($,U),h==null||h.unsubscribe();let B=Xi(),N={failed:R,requestStartedAt:f,requestEndedAt:B,duration:B-f};return R?(d.error("endRequest",Lr(N)),d.end(),null):(d.log("endRequest",Lr(N)),d.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ji(this.abortAllController.signal,async function*(e,t,r){var y;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,i),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(y=e.indexRange)!=null?y:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;b=new DataView(I)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ji(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:r}=kg(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Rg(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Zi=a=>{if(!Yi(a))throw a};var Wt=(a,e,t)=>t*e+(1-t)*a,qu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Lg=(a,e,t,r)=>{let i=0,s=t,n=qu(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as Qk,ValueSubject as Mg}from"@vkontakte/videoplayer-shared";var gt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Mg(e.initial),this.debounced$=new Mg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new re(`raw_${t}`),this.smoothedSeries$=new re(`smoothed_${t}`),this.reportedSeries$=new re(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(Qk(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var ws=class extends gt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Wt(this.slow,e,this.params.emaAlphaSlow),this.fast=Wt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ks=class extends gt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=qu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Wt(this.emaSmoothed,e,this.params.emaAlpha);let r=Lg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Rs=class extends gt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Wt(this.smoothed,t,this.params.emaAlpha):t}};var Yt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ws({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ks({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Rs({initial:e,label:"liveEdgeDelay",...t})}};var Uu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var _g=["timeupdate","progress","play","seeked","stalled","waiting"];var Ms=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Vg;this.representationSubscription=new Vg;this.state$=new M("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new Og;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.isLive$=new ie(!1);this.liveDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ie(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Og;this.gapWatchdogActive=!1;this.destroyController=new tt;this.initManifest=Hu(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:St.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Hu(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:St.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=Eg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Vb(e))!=null?n:{id:"ManifestParsing",category:St.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let r=(u,c,l)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,c)&&((f=(h=rt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${c}; codecs="${l}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let l=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(l.map(({codecs:h})=>h)),p=Ob(d);if(p&&(i[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);Zk.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",ea(s)),s}.bind(this));this.initRepresentations=Hu(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",ea({initialVideo:e,initialAudio:t,sourceHls:r})),Qt(this.manifest),Qt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Mr(p,"error").pipe(Ls(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:St.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Sb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&fs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new zi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Bg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new zi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ju(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=eu(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(Cr(..._g.filter(p=>p!=="waiting").map(p=>Mr(this.element,p))).pipe(Gu(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),Dg(),Ls(p=>!!p),Jk(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Dg()).subscribe(h=>Uu(this.element,1))),this.representationSubscription.add($s({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Ls(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add($s({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-b,S=1;Math.abs(I)>g&&(S=1+Math.sign(I)*y),Uu(this.element,S)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let y=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(S=>{var v,T;return(T=(v=S.getLiveSegmentsToLoadState(this.manifest))==null?void 0:v.to)!=null?T:y}))-y}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add($s({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Xk(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(Qt(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=eu(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,T=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),U=y<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&U);let $="none";if(R?$="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&U?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),$="active_low_latency"):g!==0&&T<I?$="live_forward_buffering":T<I+v&&($="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let B=p-(I+S),N=this.normolizeLiveOffset(Math.trunc(g+B/b)),O=Math.abs(N-g),w;!h||O<=this.tuning.dashCmafLive.offsetCalculationError?w=g:N>0&&O>this.tuning.dashCmafLive.offsetCalculationError?w=N:w=0,this.manifestUrlString=ee(this.manifestUrlString,w,2)}$!=="none"&&$!=="active_low_latency"&&(p=0,this.updateLive())}))}let u=Cr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Gu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Cr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Gu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Cr(this.forceEnded$,$s({allBuffersFull:u,someBufferEnded:c}).pipe(Ls(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:St.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Cr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),it(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&Bg(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ju(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:St.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new As({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Yt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s,n;Qt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video)),await((n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio)))}initBuffer(){Qt(this.element),this.state$.setState("running"),this.subscription.add(Cr(..._g.map(e=>Mr(this.element,e)),Mr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:St.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Mr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Mr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&xr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var n,o;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s={...s,liveLastSeekOffset:this.liveLastSeekOffset};else{let u=this.element.currentTime*1e3;(n=this.videoBufferManager)==null||n.maintain(u),(o=this.audioBufferManager)==null||o.maintain(u),s={...s,position:u}}this.tracer.log("stallIntervalCallback",ea(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=ju(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:St.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u,c;Qt(this.element),Qt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),xr(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(c=this.audioBufferManager)==null||c.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",ea({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=eR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ea(t)))}}};var Cs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ds=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Ng=`attribute vec2 a_vertex;
59
59
  attribute vec2 a_texel;
60
60
 
61
61
  varying vec2 v_texel;