@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/es2015.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 pv=Object.create;var gn=Object.defineProperty,hv=Object.defineProperties,fv=Object.getOwnPropertyDescriptor,mv=Object.getOwnPropertyDescriptors,bv=Object.getOwnPropertyNames,Pa=Object.getOwnPropertySymbols,gv=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty,Hc=Object.prototype.propertyIsEnumerable;var Sv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Ye=Math.pow,Uc=(a,e,t)=>e in a?gn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,k=(a,e)=>{for(var t in e||(e={}))Sn.call(e,t)&&Uc(a,t,e[t]);if(Pa)for(var t of Pa(e))Hc.call(e,t)&&Uc(a,t,e[t]);return a},V=(a,e)=>hv(a,mv(e));var jc=(a,e)=>{var t={};for(var r in a)Sn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Pa)for(var r of Pa(a))e.indexOf(r)<0&&Hc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var vv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of bv(e))!Sn.call(a,i)&&i!==t&&gn(a,i,{get:()=>e[i],enumerable:!(r=fv(e,i))||r.enumerable});return a};var Qe=(a,e,t)=>(t=a!=null?pv(gv(a)):{},vv(e||!a||!a.__esModule?gn(t,"default",{value:a,enumerable:!0}):t,a));var R=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(c){i(c)}},n=u=>{try{o(t.throw(u))}catch(c){i(c)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),vn=function(a,e){this[0]=a,this[1]=e},te=(a,e,t)=>{var r=(n,o,u,c)=>{try{var l=t[n](o),d=(o=l.value)instanceof vn,p=l.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,c):u({value:h,done:p})).catch(h=>r("throw",h,u,c))}catch(h){c(h)}},i=n=>s[n]=o=>new Promise((u,c)=>r(n,o,u,c)),s={};return t=t.apply(a,e),s[Sv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Ee=m((hL,Xc)=>{"use strict";Xc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Wr=m((fL,Zc)=>{"use strict";var wv=Ee();Zc.exports=!wv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var he=m((mL,rl)=>{"use strict";var el=Wr(),tl=Function.prototype,xn=tl.call,kv=el&&tl.bind.bind(xn,xn);rl.exports=el?kv:function(a){return function(){return xn.apply(a,arguments)}}});var nr=m((bL,al)=>{"use strict";var il=he(),Rv=il({}.toString),$v=il("".slice);al.exports=function(a){return $v(Rv(a),8,-1)}});var nl=m((gL,sl)=>{"use strict";var Lv=he(),Mv=Ee(),Cv=nr(),Pn=Object,Dv=Lv("".split);sl.exports=Mv(function(){return!Pn("z").propertyIsEnumerable(0)})?function(a){return Cv(a)==="String"?Dv(a,""):Pn(a)}:Pn});var or=m((SL,ol)=>{"use strict";ol.exports=function(a){return a==null}});var Yr=m((vL,ul)=>{"use strict";var Bv=or(),Ov=TypeError;ul.exports=function(a){if(Bv(a))throw new Ov("Can't call method on "+a);return a}});var ur=m((yL,cl)=>{"use strict";var Vv=nl(),_v=Yr();cl.exports=function(a){return Vv(_v(a))}});var An=m((TL,ll)=>{"use strict";ll.exports=function(){}});var Bt=m((IL,dl)=>{"use strict";dl.exports={}});var K=m((wn,pl)=>{"use strict";var Qr=function(a){return a&&a.Math===Math&&a};pl.exports=Qr(typeof globalThis=="object"&&globalThis)||Qr(typeof window=="object"&&window)||Qr(typeof self=="object"&&self)||Qr(typeof global=="object"&&global)||Qr(typeof wn=="object"&&wn)||function(){return this}()||Function("return this")()});var z=m((EL,hl)=>{"use strict";var kn=typeof document=="object"&&document.all;hl.exports=typeof kn=="undefined"&&kn!==void 0?function(a){return typeof a=="function"||a===kn}:function(a){return typeof a=="function"}});var bl=m((xL,ml)=>{"use strict";var Nv=K(),Fv=z(),fl=Nv.WeakMap;ml.exports=Fv(fl)&&/native code/.test(String(fl))});var Re=m((PL,gl)=>{"use strict";var qv=z();gl.exports=function(a){return typeof a=="object"?a!==null:qv(a)}});var $e=m((AL,Sl)=>{"use strict";var Uv=Ee();Sl.exports=!Uv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ra=m((wL,yl)=>{"use strict";var Hv=K(),vl=Re(),Rn=Hv.document,jv=vl(Rn)&&vl(Rn.createElement);yl.exports=function(a){return jv?Rn.createElement(a):{}}});var $n=m((kL,Tl)=>{"use strict";var Gv=$e(),Wv=Ee(),Yv=Ra();Tl.exports=!Gv&&!Wv(function(){return Object.defineProperty(Yv("div"),"a",{get:function(){return 7}}).a!==7})});var Ln=m((RL,Il)=>{"use strict";var Qv=$e(),zv=Ee();Il.exports=Qv&&zv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=m(($L,El)=>{"use strict";var Kv=Re(),Jv=String,Xv=TypeError;El.exports=function(a){if(Kv(a))return a;throw new Xv(Jv(a)+" is not an object")}});var xe=m((LL,xl)=>{"use strict";var Zv=Wr(),$a=Function.prototype.call;xl.exports=Zv?$a.bind($a):function(){return $a.apply($a,arguments)}});var La=m((ML,Pl)=>{"use strict";Pl.exports={}});var Xe=m((CL,wl)=>{"use strict";var Mn=La(),Cn=K(),ey=z(),Al=function(a){return ey(a)?a:void 0};wl.exports=function(a,e){return arguments.length<2?Al(Mn[a])||Al(Cn[a]):Mn[a]&&Mn[a][e]||Cn[a]&&Cn[a][e]}});var zr=m((DL,kl)=>{"use strict";var ty=he();kl.exports=ty({}.isPrototypeOf)});var cr=m((BL,Ll)=>{"use strict";var ry=K(),Rl=ry.navigator,$l=Rl&&Rl.userAgent;Ll.exports=$l?String($l):""});var Bn=m((OL,Vl)=>{"use strict";var Ol=K(),Dn=cr(),Ml=Ol.process,Cl=Ol.Deno,Dl=Ml&&Ml.versions||Cl&&Cl.version,Bl=Dl&&Dl.v8,Ne,Ma;Bl&&(Ne=Bl.split("."),Ma=Ne[0]>0&&Ne[0]<4?1:+(Ne[0]+Ne[1]));!Ma&&Dn&&(Ne=Dn.match(/Edge\/(\d+)/),(!Ne||Ne[1]>=74)&&(Ne=Dn.match(/Chrome\/(\d+)/),Ne&&(Ma=+Ne[1])));Vl.exports=Ma});var On=m((VL,Nl)=>{"use strict";var _l=Bn(),iy=Ee(),ay=K(),sy=ay.String;Nl.exports=!!Object.getOwnPropertySymbols&&!iy(function(){var a=Symbol("symbol detection");return!sy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&_l&&_l<41})});var Vn=m((_L,Fl)=>{"use strict";var ny=On();Fl.exports=ny&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var _n=m((NL,ql)=>{"use strict";var oy=Xe(),uy=z(),cy=zr(),ly=Vn(),dy=Object;ql.exports=ly?function(a){return typeof a=="symbol"}:function(a){var e=oy("Symbol");return uy(e)&&cy(e.prototype,dy(a))}});var Kr=m((FL,Ul)=>{"use strict";var py=String;Ul.exports=function(a){try{return py(a)}catch(e){return"Object"}}});var Ze=m((qL,Hl)=>{"use strict";var hy=z(),fy=Kr(),my=TypeError;Hl.exports=function(a){if(hy(a))return a;throw new my(fy(a)+" is not a function")}});var Jr=m((UL,jl)=>{"use strict";var by=Ze(),gy=or();jl.exports=function(a,e){var t=a[e];return gy(t)?void 0:by(t)}});var Wl=m((HL,Gl)=>{"use strict";var Nn=xe(),Fn=z(),qn=Re(),Sy=TypeError;Gl.exports=function(a,e){var t,r;if(e==="string"&&Fn(t=a.toString)&&!qn(r=Nn(t,a))||Fn(t=a.valueOf)&&!qn(r=Nn(t,a))||e!=="string"&&Fn(t=a.toString)&&!qn(r=Nn(t,a)))return r;throw new Sy("Can't convert object to primitive value")}});var Fe=m((jL,Yl)=>{"use strict";Yl.exports=!0});var Kl=m((GL,zl)=>{"use strict";var Ql=K(),vy=Object.defineProperty;zl.exports=function(a,e){try{vy(Ql,a,{value:e,configurable:!0,writable:!0})}catch(t){Ql[a]=e}return e}});var Xr=m((WL,Zl)=>{"use strict";var yy=Fe(),Ty=K(),Iy=Kl(),Jl="__core-js_shared__",Xl=Zl.exports=Ty[Jl]||Iy(Jl,{});(Xl.versions||(Xl.versions=[])).push({version:"3.38.0",mode:yy?"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 Un=m((YL,td)=>{"use strict";var ed=Xr();td.exports=function(a,e){return ed[a]||(ed[a]=e||{})}});var Zr=m((QL,rd)=>{"use strict";var Ey=Yr(),xy=Object;rd.exports=function(a){return xy(Ey(a))}});var qe=m((zL,id)=>{"use strict";var Py=he(),Ay=Zr(),wy=Py({}.hasOwnProperty);id.exports=Object.hasOwn||function(e,t){return wy(Ay(e),t)}});var Hn=m((KL,ad)=>{"use strict";var ky=he(),Ry=0,$y=Math.random(),Ly=ky(1 .toString);ad.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Ly(++Ry+$y,36)}});var se=m((JL,nd)=>{"use strict";var My=K(),Cy=Un(),sd=qe(),Dy=Hn(),By=On(),Oy=Vn(),lr=My.Symbol,jn=Cy("wks"),Vy=Oy?lr.for||lr:lr&&lr.withoutSetter||Dy;nd.exports=function(a){return sd(jn,a)||(jn[a]=By&&sd(lr,a)?lr[a]:Vy("Symbol."+a)),jn[a]}});var ld=m((XL,cd)=>{"use strict";var _y=xe(),od=Re(),ud=_n(),Ny=Jr(),Fy=Wl(),qy=se(),Uy=TypeError,Hy=qy("toPrimitive");cd.exports=function(a,e){if(!od(a)||ud(a))return a;var t=Ny(a,Hy),r;if(t){if(e===void 0&&(e="default"),r=_y(t,a,e),!od(r)||ud(r))return r;throw new Uy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Fy(a,e)}});var Gn=m((ZL,dd)=>{"use strict";var jy=ld(),Gy=_n();dd.exports=function(a){var e=jy(a,"string");return Gy(e)?e:e+""}});var Ot=m(hd=>{"use strict";var Wy=$e(),Yy=$n(),Qy=Ln(),Ca=ze(),pd=Gn(),zy=TypeError,Wn=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,Yn="enumerable",Qn="configurable",zn="writable";hd.f=Wy?Qy?function(e,t,r){if(Ca(e),t=pd(t),Ca(r),typeof e=="function"&&t==="prototype"&&"value"in r&&zn in r&&!r[zn]){var i=Ky(e,t);i&&i[zn]&&(e[t]=r.value,r={configurable:Qn in r?r[Qn]:i[Qn],enumerable:Yn in r?r[Yn]:i[Yn],writable:!1})}return Wn(e,t,r)}:Wn:function(e,t,r){if(Ca(e),t=pd(t),Ca(r),Yy)try{return Wn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new zy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var ei=m((tM,fd)=>{"use strict";fd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var dr=m((rM,md)=>{"use strict";var Jy=$e(),Xy=Ot(),Zy=ei();md.exports=Jy?function(a,e,t){return Xy.f(a,e,Zy(1,t))}:function(a,e,t){return a[e]=t,a}});var Da=m((iM,gd)=>{"use strict";var eT=Un(),tT=Hn(),bd=eT("keys");gd.exports=function(a){return bd[a]||(bd[a]=tT(a))}});var Ba=m((aM,Sd)=>{"use strict";Sd.exports={}});var Zn=m((sM,Td)=>{"use strict";var rT=bl(),yd=K(),iT=Re(),aT=dr(),Kn=qe(),Jn=Xr(),sT=Da(),nT=Ba(),vd="Object already initialized",Xn=yd.TypeError,oT=yd.WeakMap,Oa,ti,Va,uT=function(a){return Va(a)?ti(a):Oa(a,{})},cT=function(a){return function(e){var t;if(!iT(e)||(t=ti(e)).type!==a)throw new Xn("Incompatible receiver, "+a+" required");return t}};rT||Jn.state?(Ue=Jn.state||(Jn.state=new oT),Ue.get=Ue.get,Ue.has=Ue.has,Ue.set=Ue.set,Oa=function(a,e){if(Ue.has(a))throw new Xn(vd);return e.facade=a,Ue.set(a,e),e},ti=function(a){return Ue.get(a)||{}},Va=function(a){return Ue.has(a)}):(Vt=sT("state"),nT[Vt]=!0,Oa=function(a,e){if(Kn(a,Vt))throw new Xn(vd);return e.facade=a,aT(a,Vt,e),e},ti=function(a){return Kn(a,Vt)?a[Vt]:{}},Va=function(a){return Kn(a,Vt)});var Ue,Vt;Td.exports={set:Oa,get:ti,has:Va,enforce:uT,getterFor:cT}});var eo=m((nM,Pd)=>{"use strict";var lT=Wr(),xd=Function.prototype,Id=xd.apply,Ed=xd.call;Pd.exports=typeof Reflect=="object"&&Reflect.apply||(lT?Ed.bind(Id):function(){return Ed.apply(Id,arguments)})});var to=m((oM,Ad)=>{"use strict";var dT=nr(),pT=he();Ad.exports=function(a){if(dT(a)==="Function")return pT(a)}});var $d=m(Rd=>{"use strict";var wd={}.propertyIsEnumerable,kd=Object.getOwnPropertyDescriptor,hT=kd&&!wd.call({1:2},1);Rd.f=hT?function(e){var t=kd(this,e);return!!t&&t.enumerable}:wd});var Cd=m(Md=>{"use strict";var fT=$e(),mT=xe(),bT=$d(),gT=ei(),ST=ur(),vT=Gn(),yT=qe(),TT=$n(),Ld=Object.getOwnPropertyDescriptor;Md.f=fT?Ld:function(e,t){if(e=ST(e),t=vT(t),TT)try{return Ld(e,t)}catch(r){}if(yT(e,t))return gT(!mT(bT.f,e,t),e[t])}});var ro=m((lM,Dd)=>{"use strict";var IT=Ee(),ET=z(),xT=/#|\.prototype\./,ri=function(a,e){var t=AT[PT(a)];return t===kT?!0:t===wT?!1:ET(e)?IT(e):!!e},PT=ri.normalize=function(a){return String(a).replace(xT,".").toLowerCase()},AT=ri.data={},wT=ri.NATIVE="N",kT=ri.POLYFILL="P";Dd.exports=ri});var ii=m((dM,Od)=>{"use strict";var Bd=to(),RT=Ze(),$T=Wr(),LT=Bd(Bd.bind);Od.exports=function(a,e){return RT(a),e===void 0?a:$T?LT(a,e):function(){return a.apply(e,arguments)}}});var Le=m((pM,_d)=>{"use strict";var ai=K(),MT=eo(),CT=to(),DT=z(),BT=Cd().f,OT=ro(),pr=La(),VT=ii(),hr=dr(),Vd=qe();Xr();var _T=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 MT(a,this,arguments)};return e.prototype=a.prototype,e};_d.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ai:i?ai[t]:ai[t]&&ai[t].prototype,o=r?pr:pr[t]||hr(pr,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,S;for(p in e)c=OT(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Vd(n,p),f=o[p],l&&(a.dontCallGetSet?(S=BT(n,p),b=S&&S.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&l?g=VT(h,ai):a.wrap&&l?g=_T(h):s&&DT(h)?g=CT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&hr(g,"sham",!0),hr(o,p,g),s&&(d=t+"Prototype",Vd(pr,d)||hr(pr,d,{}),hr(pr[d],p,h),a.real&&u&&(c||!u[p])&&hr(u,p,h)))}});var qd=m((hM,Fd)=>{"use strict";var io=$e(),NT=qe(),Nd=Function.prototype,FT=io&&Object.getOwnPropertyDescriptor,ao=NT(Nd,"name"),qT=ao&&function(){}.name==="something",UT=ao&&(!io||io&&FT(Nd,"name").configurable);Fd.exports={EXISTS:ao,PROPER:qT,CONFIGURABLE:UT}});var Hd=m((fM,Ud)=>{"use strict";var HT=Math.ceil,jT=Math.floor;Ud.exports=Math.trunc||function(e){var t=+e;return(t>0?jT:HT)(t)}});var _a=m((mM,jd)=>{"use strict";var GT=Hd();jd.exports=function(a){var e=+a;return e!==e||e===0?0:GT(e)}});var Wd=m((bM,Gd)=>{"use strict";var WT=_a(),YT=Math.max,QT=Math.min;Gd.exports=function(a,e){var t=WT(a);return t<0?YT(t+e,0):QT(t,e)}});var Qd=m((gM,Yd)=>{"use strict";var zT=_a(),KT=Math.min;Yd.exports=function(a){var e=zT(a);return e>0?KT(e,9007199254740991):0}});var Na=m((SM,zd)=>{"use strict";var JT=Qd();zd.exports=function(a){return JT(a.length)}});var Xd=m((vM,Jd)=>{"use strict";var XT=ur(),ZT=Wd(),eI=Na(),Kd=function(a){return function(e,t,r){var i=XT(e),s=eI(i);if(s===0)return!a&&-1;var n=ZT(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}};Jd.exports={includes:Kd(!0),indexOf:Kd(!1)}});var tp=m((yM,ep)=>{"use strict";var tI=he(),so=qe(),rI=ur(),iI=Xd().indexOf,aI=Ba(),Zd=tI([].push);ep.exports=function(a,e){var t=rI(a),r=0,i=[],s;for(s in t)!so(aI,s)&&so(t,s)&&Zd(i,s);for(;e.length>r;)so(t,s=e[r++])&&(~iI(i,s)||Zd(i,s));return i}});var no=m((TM,rp)=>{"use strict";rp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ap=m((IM,ip)=>{"use strict";var sI=tp(),nI=no();ip.exports=Object.keys||function(e){return sI(e,nI)}});var np=m(sp=>{"use strict";var oI=$e(),uI=Ln(),cI=Ot(),lI=ze(),dI=ur(),pI=ap();sp.f=oI&&!uI?Object.defineProperties:function(e,t){lI(e);for(var r=dI(t),i=pI(t),s=i.length,n=0,o;s>n;)cI.f(e,o=i[n++],r[o]);return e}});var oo=m((xM,op)=>{"use strict";var hI=Xe();op.exports=hI("document","documentElement")});var po=m((PM,fp)=>{"use strict";var fI=ze(),mI=np(),up=no(),bI=Ba(),gI=oo(),SI=Ra(),vI=Da(),cp=">",lp="<",co="prototype",lo="script",pp=vI("IE_PROTO"),uo=function(){},hp=function(a){return lp+lo+cp+a+lp+"/"+lo+cp},dp=function(a){a.write(hp("")),a.close();var e=a.parentWindow.Object;return a=null,e},yI=function(){var a=SI("iframe"),e="java"+lo+":",t;return a.style.display="none",gI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(hp("document.F=Object")),t.close(),t.F},Fa,qa=function(){try{Fa=new ActiveXObject("htmlfile")}catch(e){}qa=typeof document!="undefined"?document.domain&&Fa?dp(Fa):yI():dp(Fa);for(var a=up.length;a--;)delete qa[co][up[a]];return qa()};bI[pp]=!0;fp.exports=Object.create||function(e,t){var r;return e!==null?(uo[co]=fI(e),r=new uo,uo[co]=null,r[pp]=e):r=qa(),t===void 0?r:mI.f(r,t)}});var bp=m((AM,mp)=>{"use strict";var TI=Ee();mp.exports=!TI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var fo=m((wM,Sp)=>{"use strict";var II=qe(),EI=z(),xI=Zr(),PI=Da(),AI=bp(),gp=PI("IE_PROTO"),ho=Object,wI=ho.prototype;Sp.exports=AI?ho.getPrototypeOf:function(a){var e=xI(a);if(II(e,gp))return e[gp];var t=e.constructor;return EI(t)&&e instanceof t?t.prototype:e instanceof ho?wI:null}});var fr=m((kM,vp)=>{"use strict";var kI=dr();vp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:kI(a,e,t),a}});var So=m((RM,Ip)=>{"use strict";var RI=Ee(),$I=z(),LI=Re(),MI=po(),yp=fo(),CI=fr(),DI=se(),BI=Fe(),go=DI("iterator"),Tp=!1,et,mo,bo;[].keys&&(bo=[].keys(),"next"in bo?(mo=yp(yp(bo)),mo!==Object.prototype&&(et=mo)):Tp=!0);var OI=!LI(et)||RI(function(){var a={};return et[go].call(a)!==a});OI?et={}:BI&&(et=MI(et));$I(et[go])||CI(et,go,function(){return this});Ip.exports={IteratorPrototype:et,BUGGY_SAFARI_ITERATORS:Tp}});var Ua=m(($M,xp)=>{"use strict";var VI=se(),_I=VI("toStringTag"),Ep={};Ep[_I]="z";xp.exports=String(Ep)==="[object z]"});var si=m((LM,Pp)=>{"use strict";var NI=Ua(),FI=z(),Ha=nr(),qI=se(),UI=qI("toStringTag"),HI=Object,jI=Ha(function(){return arguments}())==="Arguments",GI=function(a,e){try{return a[e]}catch(t){}};Pp.exports=NI?Ha:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=GI(e=HI(a),UI))=="string"?t:jI?Ha(e):(r=Ha(e))==="Object"&&FI(e.callee)?"Arguments":r}});var wp=m((MM,Ap)=>{"use strict";var WI=Ua(),YI=si();Ap.exports=WI?{}.toString:function(){return"[object "+YI(this)+"]"}});var ni=m((CM,Rp)=>{"use strict";var QI=Ua(),zI=Ot().f,KI=dr(),JI=qe(),XI=wp(),ZI=se(),kp=ZI("toStringTag");Rp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(JI(i,kp)||zI(i,kp,{configurable:!0,value:e}),r&&!QI&&KI(i,"toString",XI))}});var Lp=m((DM,$p)=>{"use strict";var eE=So().IteratorPrototype,tE=po(),rE=ei(),iE=ni(),aE=Bt(),sE=function(){return this};$p.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=tE(eE,{next:rE(+!r,t)}),iE(a,i,!1,!0),aE[i]=sE,a}});var Cp=m((BM,Mp)=>{"use strict";var nE=he(),oE=Ze();Mp.exports=function(a,e,t){try{return nE(oE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Bp=m((OM,Dp)=>{"use strict";var uE=Re();Dp.exports=function(a){return uE(a)||a===null}});var Vp=m((VM,Op)=>{"use strict";var cE=Bp(),lE=String,dE=TypeError;Op.exports=function(a){if(cE(a))return a;throw new dE("Can't set "+lE(a)+" as a prototype")}});var vo=m((_M,_p)=>{"use strict";var pE=Cp(),hE=Re(),fE=Yr(),mE=Vp();_p.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=pE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return fE(i),mE(s),hE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var zp=m((NM,Qp)=>{"use strict";var bE=Le(),gE=xe(),ja=Fe(),Wp=qd(),SE=z(),vE=Lp(),Np=fo(),Fp=vo(),yE=ni(),TE=dr(),yo=fr(),IE=se(),qp=Bt(),Yp=So(),EE=Wp.PROPER,xE=Wp.CONFIGURABLE,Up=Yp.IteratorPrototype,Ga=Yp.BUGGY_SAFARI_ITERATORS,oi=IE("iterator"),Hp="keys",ui="values",jp="entries",Gp=function(){return this};Qp.exports=function(a,e,t,r,i,s,n){vE(t,e,r);var o=function(S){if(S===i&&p)return p;if(!Ga&&S&&S in l)return l[S];switch(S){case Hp:return function(){return new t(this,S)};case ui:return function(){return new t(this,S)};case jp:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[oi]||l["@@iterator"]||i&&l[i],p=!Ga&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=Np(h.call(new a)),f!==Object.prototype&&f.next&&(!ja&&Np(f)!==Up&&(Fp?Fp(f,Up):SE(f[oi])||yo(f,oi,Gp)),yE(f,u,!0,!0),ja&&(qp[u]=Gp))),EE&&i===ui&&d&&d.name!==ui&&(!ja&&xE?TE(l,"name",ui):(c=!0,p=function(){return gE(d,this)})),i)if(b={values:o(ui),keys:s?p:o(Hp),entries:o(jp)},n)for(g in b)(Ga||c||!(g in l))&&yo(l,g,b[g]);else bE({target:e,proto:!0,forced:Ga||c},b);return(!ja||n)&&l[oi]!==p&&yo(l,oi,p,{name:i}),qp[e]=p,b}});var Jp=m((FM,Kp)=>{"use strict";Kp.exports=function(a,e){return{value:a,done:e}}});var Io=m((qM,rh)=>{"use strict";var PE=ur(),To=An(),Xp=Bt(),eh=Zn(),AE=Ot().f,wE=zp(),Wa=Jp(),kE=Fe(),RE=$e(),th="Array Iterator",$E=eh.set,LE=eh.getterFor(th);rh.exports=wE(Array,"Array",function(a,e){$E(this,{type:th,target:PE(a),index:0,kind:e})},function(){var a=LE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Wa(void 0,!0);switch(a.kind){case"keys":return Wa(t,!1);case"values":return Wa(e[t],!1)}return Wa([t,e[t]],!1)},"values");var Zp=Xp.Arguments=Xp.Array;To("keys");To("values");To("entries");if(!kE&&RE&&Zp.name!=="values")try{AE(Zp,"name",{value:"values"})}catch(a){}});var ah=m((UM,ih)=>{"use strict";var ME=se(),CE=Bt(),DE=ME("iterator"),BE=Array.prototype;ih.exports=function(a){return a!==void 0&&(CE.Array===a||BE[DE]===a)}});var Eo=m((HM,nh)=>{"use strict";var OE=si(),sh=Jr(),VE=or(),_E=Bt(),NE=se(),FE=NE("iterator");nh.exports=function(a){if(!VE(a))return sh(a,FE)||sh(a,"@@iterator")||_E[OE(a)]}});var uh=m((jM,oh)=>{"use strict";var qE=xe(),UE=Ze(),HE=ze(),jE=Kr(),GE=Eo(),WE=TypeError;oh.exports=function(a,e){var t=arguments.length<2?GE(a):e;if(UE(t))return HE(qE(t,a));throw new WE(jE(a)+" is not iterable")}});var dh=m((GM,lh)=>{"use strict";var YE=xe(),ch=ze(),QE=Jr();lh.exports=function(a,e,t){var r,i;ch(a);try{if(r=QE(a,"return"),!r){if(e==="throw")throw t;return t}r=YE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return ch(r),t}});var Qa=m((WM,mh)=>{"use strict";var zE=ii(),KE=xe(),JE=ze(),XE=Kr(),ZE=ah(),ex=Na(),ph=zr(),tx=uh(),rx=Eo(),hh=dh(),ix=TypeError,Ya=function(a,e){this.stopped=a,this.result=e},fh=Ya.prototype;mh.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=zE(e,r),c,l,d,p,h,f,b,g=function(T){return c&&hh(c,"normal",T),new Ya(!0,T)},S=function(T){return i?(JE(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)c=a.iterator;else if(n)c=a;else{if(l=rx(a),!l)throw new ix(XE(a)+" is not iterable");if(ZE(l)){for(d=0,p=ex(a);p>d;d++)if(h=S(a[d]),h&&ph(fh,h))return h;return new Ya(!1)}c=tx(a,l)}for(f=s?a.next:c.next;!(b=KE(f,c)).done;){try{h=S(b.value)}catch(T){hh(c,"throw",T)}if(typeof h=="object"&&h&&ph(fh,h))return h}return new Ya(!1)}});var gh=m((YM,bh)=>{"use strict";var ax=$e(),sx=Ot(),nx=ei();bh.exports=function(a,e,t){ax?sx.f(a,e,nx(0,t)):a[e]=t}});var Sh=m(()=>{"use strict";var ox=Le(),ux=Qa(),cx=gh();ox({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ux(e,function(r,i){cx(t,r,i)},{AS_ENTRIES:!0}),t}})});var yh=m((KM,vh)=>{"use strict";Io();Sh();var lx=La();vh.exports=lx.Object.fromEntries});var Ih=m((JM,Th)=>{"use strict";Th.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 xh=m(()=>{"use strict";Io();var dx=Ih(),px=K(),hx=ni(),Eh=Bt();for(za in dx)hx(px[za],za),Eh[za]=Eh.Array;var za});var Ah=m((eC,Ph)=>{"use strict";var fx=yh();xh();Ph.exports=fx});var xo=m((tC,wh)=>{"use strict";var mx=Ah();wh.exports=mx});var kh=m(()=>{"use strict"});var Po=m((aC,Rh)=>{"use strict";var ci=K(),bx=cr(),gx=nr(),Ka=function(a){return bx.slice(0,a.length)===a};Rh.exports=function(){return Ka("Bun/")?"BUN":Ka("Cloudflare-Workers")?"CLOUDFLARE":Ka("Deno/")?"DENO":Ka("Node.js/")?"NODE":ci.Bun&&typeof Bun.version=="string"?"BUN":ci.Deno&&typeof Deno.version=="object"?"DENO":gx(ci.process)==="process"?"NODE":ci.window&&ci.document?"BROWSER":"REST"}()});var Ja=m((sC,$h)=>{"use strict";var Sx=Po();$h.exports=Sx==="NODE"});var Mh=m((nC,Lh)=>{"use strict";var vx=Ot();Lh.exports=function(a,e,t){return vx.f(a,e,t)}});var Bh=m((oC,Dh)=>{"use strict";var yx=Xe(),Tx=Mh(),Ix=se(),Ex=$e(),Ch=Ix("species");Dh.exports=function(a){var e=yx(a);Ex&&e&&!e[Ch]&&Tx(e,Ch,{configurable:!0,get:function(){return this}})}});var Vh=m((uC,Oh)=>{"use strict";var xx=zr(),Px=TypeError;Oh.exports=function(a,e){if(xx(e,a))return a;throw new Px("Incorrect invocation")}});var wo=m((cC,_h)=>{"use strict";var Ax=he(),wx=z(),Ao=Xr(),kx=Ax(Function.toString);wx(Ao.inspectSource)||(Ao.inspectSource=function(a){return kx(a)});_h.exports=Ao.inspectSource});var jh=m((lC,Hh)=>{"use strict";var Rx=he(),$x=Ee(),Nh=z(),Lx=si(),Mx=Xe(),Cx=wo(),Fh=function(){},qh=Mx("Reflect","construct"),ko=/^\s*(?:class|function)\b/,Dx=Rx(ko.exec),Bx=!ko.test(Fh),li=function(e){if(!Nh(e))return!1;try{return qh(Fh,[],e),!0}catch(t){return!1}},Uh=function(e){if(!Nh(e))return!1;switch(Lx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Bx||!!Dx(ko,Cx(e))}catch(t){return!0}};Uh.sham=!0;Hh.exports=!qh||$x(function(){var a;return li(li.call)||!li(Object)||!li(function(){a=!0})||a})?Uh:li});var Wh=m((dC,Gh)=>{"use strict";var Ox=jh(),Vx=Kr(),_x=TypeError;Gh.exports=function(a){if(Ox(a))return a;throw new _x(Vx(a)+" is not a constructor")}});var Ro=m((pC,Qh)=>{"use strict";var Yh=ze(),Nx=Wh(),Fx=or(),qx=se(),Ux=qx("species");Qh.exports=function(a,e){var t=Yh(a).constructor,r;return t===void 0||Fx(r=Yh(t)[Ux])?e:Nx(r)}});var Kh=m((hC,zh)=>{"use strict";var Hx=he();zh.exports=Hx([].slice)});var Xh=m((fC,Jh)=>{"use strict";var jx=TypeError;Jh.exports=function(a,e){if(a<e)throw new jx("Not enough arguments");return a}});var $o=m((mC,Zh)=>{"use strict";var Gx=cr();Zh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Gx)});var No=m((bC,cf)=>{"use strict";var Pe=K(),Wx=eo(),Yx=ii(),ef=z(),Qx=qe(),uf=Ee(),tf=oo(),zx=Kh(),rf=Ra(),Kx=Xh(),Jx=$o(),Xx=Ja(),Oo=Pe.setImmediate,Vo=Pe.clearImmediate,Zx=Pe.process,Lo=Pe.Dispatch,eP=Pe.Function,af=Pe.MessageChannel,tP=Pe.String,Mo=0,di={},sf="onreadystatechange",pi,_t,Co,Do;uf(function(){pi=Pe.location});var _o=function(a){if(Qx(di,a)){var e=di[a];delete di[a],e()}},Bo=function(a){return function(){_o(a)}},nf=function(a){_o(a.data)},of=function(a){Pe.postMessage(tP(a),pi.protocol+"//"+pi.host)};(!Oo||!Vo)&&(Oo=function(e){Kx(arguments.length,1);var t=ef(e)?e:eP(e),r=zx(arguments,1);return di[++Mo]=function(){Wx(t,void 0,r)},_t(Mo),Mo},Vo=function(e){delete di[e]},Xx?_t=function(a){Zx.nextTick(Bo(a))}:Lo&&Lo.now?_t=function(a){Lo.now(Bo(a))}:af&&!Jx?(Co=new af,Do=Co.port2,Co.port1.onmessage=nf,_t=Yx(Do.postMessage,Do)):Pe.addEventListener&&ef(Pe.postMessage)&&!Pe.importScripts&&pi&&pi.protocol!=="file:"&&!uf(of)?(_t=of,Pe.addEventListener("message",nf,!1)):sf in rf("script")?_t=function(a){tf.appendChild(rf("script"))[sf]=function(){tf.removeChild(this),_o(a)}}:_t=function(a){setTimeout(Bo(a),0)});cf.exports={set:Oo,clear:Vo}});var pf=m((gC,df)=>{"use strict";var lf=K(),rP=$e(),iP=Object.getOwnPropertyDescriptor;df.exports=function(a){if(!rP)return lf[a];var e=iP(lf,a);return e&&e.value}});var Fo=m((SC,ff)=>{"use strict";var hf=function(){this.head=null,this.tail=null};hf.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}}};ff.exports=hf});var bf=m((vC,mf)=>{"use strict";var aP=cr();mf.exports=/ipad|iphone|ipod/i.test(aP)&&typeof Pebble!="undefined"});var Sf=m((yC,gf)=>{"use strict";var sP=cr();gf.exports=/web0s(?!.*chrome)/i.test(sP)});var Pf=m((TC,xf)=>{"use strict";var br=K(),nP=pf(),vf=ii(),qo=No().set,oP=Fo(),uP=$o(),cP=bf(),lP=Sf(),Uo=Ja(),yf=br.MutationObserver||br.WebKitMutationObserver,Tf=br.document,If=br.process,Xa=br.Promise,Go=nP("queueMicrotask"),mr,Ho,jo,Za,Ef;Go||(hi=new oP,fi=function(){var a,e;for(Uo&&(a=If.domain)&&a.exit();e=hi.get();)try{e()}catch(t){throw hi.head&&mr(),t}a&&a.enter()},!uP&&!Uo&&!lP&&yf&&Tf?(Ho=!0,jo=Tf.createTextNode(""),new yf(fi).observe(jo,{characterData:!0}),mr=function(){jo.data=Ho=!Ho}):!cP&&Xa&&Xa.resolve?(Za=Xa.resolve(void 0),Za.constructor=Xa,Ef=vf(Za.then,Za),mr=function(){Ef(fi)}):Uo?mr=function(){If.nextTick(fi)}:(qo=vf(qo,br),mr=function(){qo(fi)}),Go=function(a){hi.head||mr(),hi.add(a)});var hi,fi;xf.exports=Go});var wf=m((IC,Af)=>{"use strict";Af.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var es=m((EC,kf)=>{"use strict";kf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Nt=m((xC,Rf)=>{"use strict";var dP=K();Rf.exports=dP.Promise});var gr=m((PC,Cf)=>{"use strict";var pP=K(),mi=Nt(),hP=z(),fP=ro(),mP=wo(),bP=se(),$f=Po(),gP=Fe(),Wo=Bn(),Lf=mi&&mi.prototype,SP=bP("species"),Yo=!1,Mf=hP(pP.PromiseRejectionEvent),vP=fP("Promise",function(){var a=mP(mi),e=a!==String(mi);if(!e&&Wo===66||gP&&!(Lf.catch&&Lf.finally))return!0;if(!Wo||Wo<51||!/native code/.test(a)){var t=new mi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[SP]=r,Yo=t.then(function(){})instanceof r,!Yo)return!0}return!e&&($f==="BROWSER"||$f==="DENO")&&!Mf});Cf.exports={CONSTRUCTOR:vP,REJECTION_EVENT:Mf,SUBCLASSING:Yo}});var Sr=m((AC,Bf)=>{"use strict";var Df=Ze(),yP=TypeError,TP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new yP("Bad Promise constructor");e=r,t=i}),this.resolve=Df(e),this.reject=Df(t)};Bf.exports.f=function(a){return new TP(a)}});var em=m(()=>{"use strict";var IP=Le(),EP=Fe(),as=Ja(),bt=K(),Ir=xe(),Of=fr(),Vf=vo(),xP=ni(),PP=Bh(),AP=Ze(),is=z(),wP=Re(),kP=Vh(),RP=Ro(),Uf=No().set,Xo=Pf(),$P=wf(),LP=es(),MP=Fo(),Hf=Zn(),ss=Nt(),Zo=gr(),jf=Sr(),ns="Promise",Gf=Zo.CONSTRUCTOR,CP=Zo.REJECTION_EVENT,DP=Zo.SUBCLASSING,Qo=Hf.getterFor(ns),BP=Hf.set,vr=ss&&ss.prototype,Ft=ss,ts=vr,Wf=bt.TypeError,zo=bt.document,eu=bt.process,Ko=jf.f,OP=Ko,VP=!!(zo&&zo.createEvent&&bt.dispatchEvent),Yf="unhandledrejection",_P="rejectionhandled",_f=0,Qf=1,NP=2,tu=1,zf=2,rs,Nf,FP,Ff,Kf=function(a){var e;return wP(a)&&is(e=a.then)?e:!1},Jf=function(a,e){var t=e.value,r=e.state===Qf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===zf&&UP(e),e.rejection=tu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Wf("Promise-chain cycle")):(c=Kf(u))?Ir(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},Xf=function(a,e){a.notified||(a.notified=!0,Xo(function(){for(var t=a.reactions,r;r=t.get();)Jf(r,a);a.notified=!1,e&&!a.rejection&&qP(a)}))},Zf=function(a,e,t){var r,i;VP?(r=zo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),bt.dispatchEvent(r)):r={promise:e,reason:t},!CP&&(i=bt["on"+a])?i(r):a===Yf&&$P("Unhandled promise rejection",t)},qP=function(a){Ir(Uf,bt,function(){var e=a.facade,t=a.value,r=qf(a),i;if(r&&(i=LP(function(){as?eu.emit("unhandledRejection",t,e):Zf(Yf,e,t)}),a.rejection=as||qf(a)?zf:tu,i.error))throw i.value})},qf=function(a){return a.rejection!==tu&&!a.parent},UP=function(a){Ir(Uf,bt,function(){var e=a.facade;as?eu.emit("rejectionHandled",e):Zf(_P,e,a.value)})},yr=function(a,e,t){return function(r){a(e,r,t)}},Tr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=NP,Xf(a,!0))},Jo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Wf("Promise can't be resolved itself");var r=Kf(e);r?Xo(function(){var i={done:!1};try{Ir(r,e,yr(Jo,i,a),yr(Tr,i,a))}catch(s){Tr(i,s,a)}}):(a.value=e,a.state=Qf,Xf(a,!1))}catch(i){Tr({done:!1},i,a)}}};if(Gf&&(Ft=function(e){kP(this,ts),AP(e),Ir(rs,this);var t=Qo(this);try{e(yr(Jo,t),yr(Tr,t))}catch(r){Tr(t,r)}},ts=Ft.prototype,rs=function(e){BP(this,{type:ns,done:!1,notified:!1,parent:!1,reactions:new MP,rejection:!1,state:_f,value:void 0})},rs.prototype=Of(ts,"then",function(e,t){var r=Qo(this),i=Ko(RP(this,Ft));return r.parent=!0,i.ok=is(e)?e:!0,i.fail=is(t)&&t,i.domain=as?eu.domain:void 0,r.state===_f?r.reactions.add(i):Xo(function(){Jf(i,r)}),i.promise}),Nf=function(){var a=new rs,e=Qo(a);this.promise=a,this.resolve=yr(Jo,e),this.reject=yr(Tr,e)},jf.f=Ko=function(a){return a===Ft||a===FP?new Nf(a):OP(a)},!EP&&is(ss)&&vr!==Object.prototype)){Ff=vr.then,DP||Of(vr,"then",function(e,t){var r=this;return new Ft(function(i,s){Ir(Ff,r,i,s)}).then(e,t)},{unsafe:!0});try{delete vr.constructor}catch(a){}Vf&&Vf(vr,ts)}IP({global:!0,constructor:!0,wrap:!0,forced:Gf},{Promise:Ft});xP(Ft,ns,!1,!0);PP(ns)});var sm=m((RC,am)=>{"use strict";var HP=se(),rm=HP("iterator"),im=!1;try{tm=0,ru={next:function(){return{done:!!tm++}},return:function(){im=!0}},ru[rm]=function(){return this},Array.from(ru,function(){throw 2})}catch(a){}var tm,ru;am.exports=function(a,e){try{if(!e&&!im)return!1}catch(i){return!1}var t=!1;try{var r={};r[rm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var iu=m(($C,nm)=>{"use strict";var jP=Nt(),GP=sm(),WP=gr().CONSTRUCTOR;nm.exports=WP||!GP(function(a){jP.all(a).then(void 0,function(){})})});var om=m(()=>{"use strict";var YP=Le(),QP=xe(),zP=Ze(),KP=Sr(),JP=es(),XP=Qa(),ZP=iu();YP({target:"Promise",stat:!0,forced:ZP},{all:function(e){var t=this,r=KP.f(t),i=r.resolve,s=r.reject,n=JP(function(){var o=zP(t.resolve),u=[],c=0,l=1;XP(e,function(d){var p=c++,h=!1;l++,QP(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 cm=m(()=>{"use strict";var eA=Le(),tA=Fe(),rA=gr().CONSTRUCTOR,su=Nt(),iA=Xe(),aA=z(),sA=fr(),um=su&&su.prototype;eA({target:"Promise",proto:!0,forced:rA,real:!0},{catch:function(a){return this.then(void 0,a)}});!tA&&aA(su)&&(au=iA("Promise").prototype.catch,um.catch!==au&&sA(um,"catch",au,{unsafe:!0}));var au});var lm=m(()=>{"use strict";var nA=Le(),oA=xe(),uA=Ze(),cA=Sr(),lA=es(),dA=Qa(),pA=iu();nA({target:"Promise",stat:!0,forced:pA},{race:function(e){var t=this,r=cA.f(t),i=r.reject,s=lA(function(){var n=uA(t.resolve);dA(e,function(o){oA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var dm=m(()=>{"use strict";var hA=Le(),fA=Sr(),mA=gr().CONSTRUCTOR;hA({target:"Promise",stat:!0,forced:mA},{reject:function(e){var t=fA.f(this),r=t.reject;return r(e),t.promise}})});var nu=m((NC,pm)=>{"use strict";var bA=ze(),gA=Re(),SA=Sr();pm.exports=function(a,e){if(bA(a),gA(e)&&e.constructor===a)return e;var t=SA.f(a),r=t.resolve;return r(e),t.promise}});var mm=m(()=>{"use strict";var vA=Le(),yA=Xe(),hm=Fe(),TA=Nt(),fm=gr().CONSTRUCTOR,IA=nu(),EA=yA("Promise"),xA=hm&&!fm;vA({target:"Promise",stat:!0,forced:hm||fm},{resolve:function(e){return IA(xA&&this===EA?TA:this,e)}})});var bm=m(()=>{"use strict";em();om();cm();lm();dm();mm()});var ym=m(()=>{"use strict";var PA=Le(),AA=Fe(),os=Nt(),wA=Ee(),Sm=Xe(),vm=z(),kA=Ro(),gm=nu(),RA=fr(),uu=os&&os.prototype,$A=!!os&&wA(function(){uu.finally.call({then:function(){}},function(){})});PA({target:"Promise",proto:!0,real:!0,forced:$A},{finally:function(a){var e=kA(this,Sm("Promise")),t=vm(a);return this.then(t?function(r){return gm(e,a()).then(function(){return r})}:a,t?function(r){return gm(e,a()).then(function(){throw r})}:a)}});!AA&&vm(os)&&(ou=Sm("Promise").prototype.finally,uu.finally!==ou&&RA(uu,"finally",ou,{unsafe:!0}));var ou});var us=m((WC,Tm)=>{"use strict";var LA=Xe();Tm.exports=LA});var Em=m((YC,Im)=>{"use strict";kh();bm();ym();var MA=us();Im.exports=MA("Promise","finally")});var Pm=m((QC,xm)=>{"use strict";var CA=Em();xm.exports=CA});var cs=m((zC,Am)=>{"use strict";var DA=Pm();Am.exports=DA});var Jm=m(()=>{"use strict";var cw=Le(),lw=Zr(),dw=Na(),pw=_a(),hw=An();cw({target:"Array",proto:!0},{at:function(e){var t=lw(this),r=dw(t),i=pw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});hw("at")});var Zm=m((a0,Xm)=>{"use strict";Jm();var fw=us();Xm.exports=fw("Array","at")});var tb=m((s0,eb)=>{"use strict";var mw=Zm();eb.exports=mw});var vi=m((n0,rb)=>{"use strict";var bw=tb();rb.exports=bw});var og=m(()=>{"use strict"});var ug=m(()=>{"use strict"});var lg=m((h_,cg)=>{"use strict";var Ik=Re(),Ek=nr(),xk=se(),Pk=xk("match");cg.exports=function(a){var e;return Ik(a)&&((e=a[Pk])!==void 0?!!e:Ek(a)==="RegExp")}});var pg=m((f_,dg)=>{"use strict";var Ak=si(),wk=String;dg.exports=function(a){if(Ak(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return wk(a)}});var fg=m((m_,hg)=>{"use strict";var kk=ze();hg.exports=function(){var a=kk(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 gg=m((b_,bg)=>{"use strict";var Rk=xe(),$k=qe(),Lk=zr(),Mk=fg(),mg=RegExp.prototype;bg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in mg)&&!$k(a,"flags")&&Lk(mg,a)?Rk(Mk,a):e}});var vg=m((g_,Sg)=>{"use strict";var _u=he(),Ck=Zr(),Dk=Math.floor,Ou=_u("".charAt),Bk=_u("".replace),Vu=_u("".slice),Ok=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Vk=/\$([$&'`]|\d{1,2})/g;Sg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Vk;return i!==void 0&&(i=Ck(i),u=Ok),Bk(s,u,function(c,l){var d;switch(Ou(l,0)){case"$":return"$";case"&":return a;case"`":return Vu(e,0,t);case"'":return Vu(e,n);case"<":d=i[Vu(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Dk(p/10);return h===0?c:h<=o?r[h-1]===void 0?Ou(l,1):r[h-1]+Ou(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var Ig=m(()=>{"use strict";var _k=Le(),Nk=xe(),Fu=he(),yg=Yr(),Fk=z(),qk=or(),Uk=lg(),Cr=pg(),Hk=Jr(),jk=gg(),Gk=vg(),Wk=se(),Yk=Fe(),Qk=Wk("replace"),zk=TypeError,Nu=Fu("".indexOf),Kk=Fu("".replace),Tg=Fu("".slice),Jk=Math.max;_k({target:"String",proto:!0},{replaceAll:function(e,t){var r=yg(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!qk(e)){if(i=Uk(e),i&&(s=Cr(yg(jk(e))),!~Nu(s,"g")))throw new zk("`.replaceAll` does not allow non-global regexes");if(n=Hk(e,Qk),n)return Nk(n,e,r,t);if(Yk&&i)return Kk(Cr(r),e,t)}for(o=Cr(r),u=Cr(e),c=Fk(t),c||(t=Cr(t)),l=u.length,d=Jk(1,l),p=Nu(o,u);p!==-1;)h=c?Cr(t(u,p,o)):Gk(u,o,p,[],void 0,t),b+=Tg(o,f,p)+h,f=p+l,p=p+d>o.length?-1:Nu(o,u,p+d);return f<o.length&&(b+=Tg(o,f)),b}})});var xg=m((y_,Eg)=>{"use strict";og();ug();Ig();var Xk=us();Eg.exports=Xk("String","replaceAll")});var Ag=m((T_,Pg)=>{"use strict";var Zk=xg();Pg.exports=Zk});var kg=m((I_,wg)=>{"use strict";var eR=Ag();wg.exports=eR});var Gc="2.0.111-dev.2c18acf4.0";var pe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(pe||{}),mt=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(mt||{});var Aa=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Aa||{}),yn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(yn||{});var Tn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Tn||{});import{assertNever as Jc,assertNonNullable as yv,isNonNullable as wa,ValueSubject as In,Subject as Tv,Subscription as Iv,merge as Ev,observableFrom as xv,fromEvent as Yc,map as Qc,tap as zc,filterChanged as Pv,isNullable as En,ErrorCategory as Kc}from"@vkontakte/videoplayer-shared";var Wc=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 ka=class{constructor(e){this.connection$=new In(void 0);this.castState$=new In("NOT_AVAILABLE");this.errorEvent$=new Tv;this.realCastState$=new In("NOT_AVAILABLE");this.subscription=new Iv;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=wa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Wc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Kc.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(){wa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();En(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();En(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(Yc(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 Jc(i.sessionState)}})).add(Ev(Yc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(zc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Qc(i=>i.castState)),xv([r.getCastState()])).pipe(Pv(),Qc(Av),zc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=wa(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();yv(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(En(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"?wa(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:Kc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Av=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 Jc(a)}};var AS=Qe(xo(),1);var Om=Qe(cs(),1);import{assertNever as wm}from"@vkontakte/videoplayer-shared";var ae=(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:wm(t)}return a},cu=(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:wm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as BA,Subject as ls,merge as km}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new ls;this.transitionEnded$=new ls;this.transitionUpdated$=new ls;this.forceChanged$=new ls;this.stateChangeStarted$=km(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=km(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||BA(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 OA}from"@vkontakte/videoplayer-shared";var Rm=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 OA(a)}};import{assertNever as Er,assertNonNullable as qt,debounce as $m,ErrorCategory as Lm,fromEvent as Ut,isNonNullable as Mm,map as Cm,merge as Dm,observableFrom as VA,Subject as _A,Subscription as lu,timeout as NA,getHighestQuality as FA}from"@vkontakte/videoplayer-shared";var qA=5,UA=5,HA=500,Bm=7e3,bi=class{constructor(e){this.subscription=new lu;this.loadMediaTimeoutSubscription=new lu;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:Er(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:Er(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:Er(e)}break}default:Er(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Rm(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 lu;this.subscription.add(e),this.subscription.add(Dm(this.videoState.stateChangeStarted$.pipe(Cm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Cm(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 _A;e.add(i.pipe($m(HA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ut(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)>qA)&&i.next(o),s=o})),e.add(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ut(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<UA&&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:Er(n)}}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Dm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,VA(["init"])).pipe($m(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];qt(l);let d=FA(Object.keys(l));qt(d);let p=l[d];qt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];qt(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];qt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];qt(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];qt(l),r=ae(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:Lm.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Er(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 Mm(o)&&(n.metadata.title=o),Mm(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(NA(Bm).subscribe(()=>s(`timeout(${Bm})`)))});(0,Om.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:Lm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as _m}from"@vkontakte/videoplayer-shared";import{clearVideoElement as jA}from"@vkontakte/videoplayer-shared";var Vm=a=>{try{a.pause(),a.playbackRate=0,jA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as GA,Subscription as WA}from"@vkontakte/videoplayer-shared";var du=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)}},pu=window.WeakMap?new WeakMap:new du,hu=window.WeakMap?new WeakMap:new Map,YA=(a,e=20)=>{let t=0;return GA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},fe=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?_m(t):(t=document.createElement("video"),a.appendChild(t)),pu.set(t,r);let i=new WA;return i.add(YA(t,e)),hu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},me=a=>{let e=hu.get(a);e==null||e.unsubscribe(),hu.delete(a);let t=pu.get(a);pu.delete(a),t?_m(a):Vm(a)};import{assertNonNullable as gi,isNonNullable as Je,isNullable as KA,fromEvent as xr,merge as Nm,observableFrom as Fm,filterChanged as qm,map as Si,Subject as Um,Subscription as JA,ValueSubject as XA,ErrorCategory as ZA}from"@vkontakte/videoplayer-shared";import{isNonNullable as fu,isNullable as QA,Subscription as zA}from"@vkontakte/videoplayer-shared";var ds=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=QA(i),c=new zA;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},Ke=(a,e,t)=>ds(e,()=>a.loop,r=>{fu(r)&&(a.loop=r)},{onError:t}),be=(a,e,t,r)=>ds(e,()=>({muted:a.muted,volume:a.volume}),i=>{fu(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}),Me=(a,e,t,r)=>ds(e,()=>a.playbackRate,i=>{fu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),gt=ds;var ew=a=>["__",a.language,a.label].join("|"),tw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},mu=class a{constructor(){this.available$=new Um;this.current$=new XA(void 0);this.error$=new Um;this.subscription=new JA;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:ZA.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(gt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Je(s)&&this.setInternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Si(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(gt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Je(s)&&this.setExternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Si(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(gt(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(gt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){gi(this.video);let{textTracks:e}=this.video;this.subscription.add(xr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Nm(xr(e,"addtrack"),xr(e,"removetrack"),Fm(["init"])).pipe(Si(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),qm((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Nm(xr(e,"change"),Fm(["init"])).pipe(Si(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Si(r=>r&&this.htmlTextTrackToITextTrack(r).id),qm()).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(xr(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(xr(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;Je(t.align)&&(i.align=t.align),Je(t.position)&&(i.position=t.position),Je(t.size)&&(i.size=t.size),Je(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){gi(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:ew(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){gi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(KA(e)||!tw(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){gi(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){gi(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)}},Ce=mu;var rt=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 Hm=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},bu=a=>{let e=Hm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},jm=a=>{let e=Hm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as De,map as St,merge as Wm,filterChanged as iw,isNonNullable as Ym,Subject as aw,filter as Qm,mapTo as zm,combine as sw,once as nw,ErrorCategory as ow,ValueSubject as Km,clientChecker as uw}from"@vkontakte/videoplayer-shared";var rw=3,Gm=(a,e,t=rw)=>{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 ge=a=>{let e=v=>De(a,v).pipe(zm(void 0)),r=Wm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>De(a,v))).pipe(St(v=>v.type==="ended"?a.readyState<2:a.readyState<3),iw()),i=Wm(De(a,"progress"),De(a,"timeupdate")).pipe(St(()=>Gm(a.buffered,a.currentTime))),s=uw.isSafari?sw({play:e("play").pipe(nw()),playing:e("playing")}).pipe(zm(void 0)):e("playing"),n=De(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume}))),o=De(a,"ratechange").pipe(St(()=>a.playbackRate)),u=De(a,"error").pipe(Qm(()=>!!(a.error||a.played.length)),St(()=>{var y;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:ow.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),c=De(a,"timeupdate").pipe(St(()=>a.currentTime)),l=new aw,d=.3,p;c.subscribe(v=>{a.loop&&Ym(p)&&Ym(v)&&p>=a.duration-d&&v<=d&&l.next(p),p=v});let h=e("pause").pipe(Qm(()=>!a.error&&p!==a.duration)),f=De(a,"enterpictureinpicture"),b=De(a,"leavepictureinpicture"),g=new Km(jm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Km(bu(a));return De(a,"fullscreenchange").pipe(St(()=>bu(a))).subscribe(S),{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$:De(a,"durationchange").pipe(St(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as vt}from"@vkontakte/videoplayer-shared";var yt=a=>{switch(a){case"mobile":return vt.Q_144P;case"lowest":return vt.Q_240P;case"low":return vt.Q_360P;case"sd":case"medium":return vt.Q_480P;case"hd":case"high":return vt.Q_720P;case"fullhd":case"full":return vt.Q_1080P;case"quadhd":case"quad":return vt.Q_1440P;case"ultrahd":case"ultra":return vt.Q_2160P}};var Ht=Qe(vi(),1);import{isNonNullable as Se,isNullable as Su,now as lb,isHigher as vu,isHigherOrEqual as nb,isInvariantQuality as ob,isLower as yu,isLowerOrEqual as ub,videoSizeToQuality as gw,assertNotEmptyArray as db,assertNonNullable as Sw}from"@vkontakte/videoplayer-shared";var gu=!1,it={},ib=a=>{gu=a},ab=()=>{it={}},sb=a=>{a(it)},yi=(a,e)=>{var t;gu&&(it.meta=(t=it.meta)!=null?t:{},it.meta[a]=e)},ne=class{constructor(e){this.name=e}next(e){var r,i;if(!gu)return;it.series=(r=it.series)!=null?r:{};let t=(i=it.series[this.name])!=null?i:[];t.push([Date.now(),e]),it.series[this.name]=t}};var vw=new ne("best_bitrate"),pb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Tu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ti=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=lb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},hb='Assertion "ABR Tracks is empty array" failed',ps=(a,e,t,r)=>{var u;let i=[...e].sort(Tu(1)),s=[...t].sort(Tu(1)),n=s.filter(c=>Se(c.bitrate)&&Se(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,Ht.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Ht.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ht.default)(n,-1):(0,Ht.default)(s,0)},cb=a=>"quality"in a,fb=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&lb()-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=cb(s)?"video":"audio",o=cb(s)?s.quality:s.bitrate;return e({message:`
6
+ var pv=Object.create;var gn=Object.defineProperty,hv=Object.defineProperties,fv=Object.getOwnPropertyDescriptor,mv=Object.getOwnPropertyDescriptors,bv=Object.getOwnPropertyNames,Pa=Object.getOwnPropertySymbols,gv=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty,Hc=Object.prototype.propertyIsEnumerable;var Sv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Ye=Math.pow,Uc=(a,e,t)=>e in a?gn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,k=(a,e)=>{for(var t in e||(e={}))Sn.call(e,t)&&Uc(a,t,e[t]);if(Pa)for(var t of Pa(e))Hc.call(e,t)&&Uc(a,t,e[t]);return a},V=(a,e)=>hv(a,mv(e));var jc=(a,e)=>{var t={};for(var r in a)Sn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Pa)for(var r of Pa(a))e.indexOf(r)<0&&Hc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var vv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of bv(e))!Sn.call(a,i)&&i!==t&&gn(a,i,{get:()=>e[i],enumerable:!(r=fv(e,i))||r.enumerable});return a};var Qe=(a,e,t)=>(t=a!=null?pv(gv(a)):{},vv(e||!a||!a.__esModule?gn(t,"default",{value:a,enumerable:!0}):t,a));var R=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(c){i(c)}},n=u=>{try{o(t.throw(u))}catch(c){i(c)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),vn=function(a,e){this[0]=a,this[1]=e},te=(a,e,t)=>{var r=(n,o,u,c)=>{try{var l=t[n](o),d=(o=l.value)instanceof vn,p=l.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,c):u({value:h,done:p})).catch(h=>r("throw",h,u,c))}catch(h){c(h)}},i=n=>s[n]=o=>new Promise((u,c)=>r(n,o,u,c)),s={};return t=t.apply(a,e),s[Sv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Ee=m((hL,Xc)=>{"use strict";Xc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Wr=m((fL,Zc)=>{"use strict";var wv=Ee();Zc.exports=!wv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var he=m((mL,rl)=>{"use strict";var el=Wr(),tl=Function.prototype,xn=tl.call,kv=el&&tl.bind.bind(xn,xn);rl.exports=el?kv:function(a){return function(){return xn.apply(a,arguments)}}});var nr=m((bL,al)=>{"use strict";var il=he(),Rv=il({}.toString),$v=il("".slice);al.exports=function(a){return $v(Rv(a),8,-1)}});var nl=m((gL,sl)=>{"use strict";var Lv=he(),Mv=Ee(),Cv=nr(),Pn=Object,Dv=Lv("".split);sl.exports=Mv(function(){return!Pn("z").propertyIsEnumerable(0)})?function(a){return Cv(a)==="String"?Dv(a,""):Pn(a)}:Pn});var or=m((SL,ol)=>{"use strict";ol.exports=function(a){return a==null}});var Yr=m((vL,ul)=>{"use strict";var Bv=or(),Ov=TypeError;ul.exports=function(a){if(Bv(a))throw new Ov("Can't call method on "+a);return a}});var ur=m((yL,cl)=>{"use strict";var Vv=nl(),_v=Yr();cl.exports=function(a){return Vv(_v(a))}});var An=m((TL,ll)=>{"use strict";ll.exports=function(){}});var Bt=m((IL,dl)=>{"use strict";dl.exports={}});var K=m((wn,pl)=>{"use strict";var Qr=function(a){return a&&a.Math===Math&&a};pl.exports=Qr(typeof globalThis=="object"&&globalThis)||Qr(typeof window=="object"&&window)||Qr(typeof self=="object"&&self)||Qr(typeof global=="object"&&global)||Qr(typeof wn=="object"&&wn)||function(){return this}()||Function("return this")()});var z=m((EL,hl)=>{"use strict";var kn=typeof document=="object"&&document.all;hl.exports=typeof kn=="undefined"&&kn!==void 0?function(a){return typeof a=="function"||a===kn}:function(a){return typeof a=="function"}});var bl=m((xL,ml)=>{"use strict";var Nv=K(),Fv=z(),fl=Nv.WeakMap;ml.exports=Fv(fl)&&/native code/.test(String(fl))});var Re=m((PL,gl)=>{"use strict";var qv=z();gl.exports=function(a){return typeof a=="object"?a!==null:qv(a)}});var $e=m((AL,Sl)=>{"use strict";var Uv=Ee();Sl.exports=!Uv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ra=m((wL,yl)=>{"use strict";var Hv=K(),vl=Re(),Rn=Hv.document,jv=vl(Rn)&&vl(Rn.createElement);yl.exports=function(a){return jv?Rn.createElement(a):{}}});var $n=m((kL,Tl)=>{"use strict";var Gv=$e(),Wv=Ee(),Yv=Ra();Tl.exports=!Gv&&!Wv(function(){return Object.defineProperty(Yv("div"),"a",{get:function(){return 7}}).a!==7})});var Ln=m((RL,Il)=>{"use strict";var Qv=$e(),zv=Ee();Il.exports=Qv&&zv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=m(($L,El)=>{"use strict";var Kv=Re(),Jv=String,Xv=TypeError;El.exports=function(a){if(Kv(a))return a;throw new Xv(Jv(a)+" is not an object")}});var xe=m((LL,xl)=>{"use strict";var Zv=Wr(),$a=Function.prototype.call;xl.exports=Zv?$a.bind($a):function(){return $a.apply($a,arguments)}});var La=m((ML,Pl)=>{"use strict";Pl.exports={}});var Xe=m((CL,wl)=>{"use strict";var Mn=La(),Cn=K(),ey=z(),Al=function(a){return ey(a)?a:void 0};wl.exports=function(a,e){return arguments.length<2?Al(Mn[a])||Al(Cn[a]):Mn[a]&&Mn[a][e]||Cn[a]&&Cn[a][e]}});var zr=m((DL,kl)=>{"use strict";var ty=he();kl.exports=ty({}.isPrototypeOf)});var cr=m((BL,Ll)=>{"use strict";var ry=K(),Rl=ry.navigator,$l=Rl&&Rl.userAgent;Ll.exports=$l?String($l):""});var Bn=m((OL,Vl)=>{"use strict";var Ol=K(),Dn=cr(),Ml=Ol.process,Cl=Ol.Deno,Dl=Ml&&Ml.versions||Cl&&Cl.version,Bl=Dl&&Dl.v8,Fe,Ma;Bl&&(Fe=Bl.split("."),Ma=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!Ma&&Dn&&(Fe=Dn.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=Dn.match(/Chrome\/(\d+)/),Fe&&(Ma=+Fe[1])));Vl.exports=Ma});var On=m((VL,Nl)=>{"use strict";var _l=Bn(),iy=Ee(),ay=K(),sy=ay.String;Nl.exports=!!Object.getOwnPropertySymbols&&!iy(function(){var a=Symbol("symbol detection");return!sy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&_l&&_l<41})});var Vn=m((_L,Fl)=>{"use strict";var ny=On();Fl.exports=ny&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var _n=m((NL,ql)=>{"use strict";var oy=Xe(),uy=z(),cy=zr(),ly=Vn(),dy=Object;ql.exports=ly?function(a){return typeof a=="symbol"}:function(a){var e=oy("Symbol");return uy(e)&&cy(e.prototype,dy(a))}});var Kr=m((FL,Ul)=>{"use strict";var py=String;Ul.exports=function(a){try{return py(a)}catch(e){return"Object"}}});var Ze=m((qL,Hl)=>{"use strict";var hy=z(),fy=Kr(),my=TypeError;Hl.exports=function(a){if(hy(a))return a;throw new my(fy(a)+" is not a function")}});var Jr=m((UL,jl)=>{"use strict";var by=Ze(),gy=or();jl.exports=function(a,e){var t=a[e];return gy(t)?void 0:by(t)}});var Wl=m((HL,Gl)=>{"use strict";var Nn=xe(),Fn=z(),qn=Re(),Sy=TypeError;Gl.exports=function(a,e){var t,r;if(e==="string"&&Fn(t=a.toString)&&!qn(r=Nn(t,a))||Fn(t=a.valueOf)&&!qn(r=Nn(t,a))||e!=="string"&&Fn(t=a.toString)&&!qn(r=Nn(t,a)))return r;throw new Sy("Can't convert object to primitive value")}});var qe=m((jL,Yl)=>{"use strict";Yl.exports=!0});var Kl=m((GL,zl)=>{"use strict";var Ql=K(),vy=Object.defineProperty;zl.exports=function(a,e){try{vy(Ql,a,{value:e,configurable:!0,writable:!0})}catch(t){Ql[a]=e}return e}});var Xr=m((WL,Zl)=>{"use strict";var yy=qe(),Ty=K(),Iy=Kl(),Jl="__core-js_shared__",Xl=Zl.exports=Ty[Jl]||Iy(Jl,{});(Xl.versions||(Xl.versions=[])).push({version:"3.38.0",mode:yy?"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 Un=m((YL,td)=>{"use strict";var ed=Xr();td.exports=function(a,e){return ed[a]||(ed[a]=e||{})}});var Zr=m((QL,rd)=>{"use strict";var Ey=Yr(),xy=Object;rd.exports=function(a){return xy(Ey(a))}});var Ue=m((zL,id)=>{"use strict";var Py=he(),Ay=Zr(),wy=Py({}.hasOwnProperty);id.exports=Object.hasOwn||function(e,t){return wy(Ay(e),t)}});var Hn=m((KL,ad)=>{"use strict";var ky=he(),Ry=0,$y=Math.random(),Ly=ky(1 .toString);ad.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Ly(++Ry+$y,36)}});var se=m((JL,nd)=>{"use strict";var My=K(),Cy=Un(),sd=Ue(),Dy=Hn(),By=On(),Oy=Vn(),lr=My.Symbol,jn=Cy("wks"),Vy=Oy?lr.for||lr:lr&&lr.withoutSetter||Dy;nd.exports=function(a){return sd(jn,a)||(jn[a]=By&&sd(lr,a)?lr[a]:Vy("Symbol."+a)),jn[a]}});var ld=m((XL,cd)=>{"use strict";var _y=xe(),od=Re(),ud=_n(),Ny=Jr(),Fy=Wl(),qy=se(),Uy=TypeError,Hy=qy("toPrimitive");cd.exports=function(a,e){if(!od(a)||ud(a))return a;var t=Ny(a,Hy),r;if(t){if(e===void 0&&(e="default"),r=_y(t,a,e),!od(r)||ud(r))return r;throw new Uy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Fy(a,e)}});var Gn=m((ZL,dd)=>{"use strict";var jy=ld(),Gy=_n();dd.exports=function(a){var e=jy(a,"string");return Gy(e)?e:e+""}});var Ot=m(hd=>{"use strict";var Wy=$e(),Yy=$n(),Qy=Ln(),Ca=ze(),pd=Gn(),zy=TypeError,Wn=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,Yn="enumerable",Qn="configurable",zn="writable";hd.f=Wy?Qy?function(e,t,r){if(Ca(e),t=pd(t),Ca(r),typeof e=="function"&&t==="prototype"&&"value"in r&&zn in r&&!r[zn]){var i=Ky(e,t);i&&i[zn]&&(e[t]=r.value,r={configurable:Qn in r?r[Qn]:i[Qn],enumerable:Yn in r?r[Yn]:i[Yn],writable:!1})}return Wn(e,t,r)}:Wn:function(e,t,r){if(Ca(e),t=pd(t),Ca(r),Yy)try{return Wn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new zy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var ei=m((tM,fd)=>{"use strict";fd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var dr=m((rM,md)=>{"use strict";var Jy=$e(),Xy=Ot(),Zy=ei();md.exports=Jy?function(a,e,t){return Xy.f(a,e,Zy(1,t))}:function(a,e,t){return a[e]=t,a}});var Da=m((iM,gd)=>{"use strict";var eT=Un(),tT=Hn(),bd=eT("keys");gd.exports=function(a){return bd[a]||(bd[a]=tT(a))}});var Ba=m((aM,Sd)=>{"use strict";Sd.exports={}});var Zn=m((sM,Td)=>{"use strict";var rT=bl(),yd=K(),iT=Re(),aT=dr(),Kn=Ue(),Jn=Xr(),sT=Da(),nT=Ba(),vd="Object already initialized",Xn=yd.TypeError,oT=yd.WeakMap,Oa,ti,Va,uT=function(a){return Va(a)?ti(a):Oa(a,{})},cT=function(a){return function(e){var t;if(!iT(e)||(t=ti(e)).type!==a)throw new Xn("Incompatible receiver, "+a+" required");return t}};rT||Jn.state?(He=Jn.state||(Jn.state=new oT),He.get=He.get,He.has=He.has,He.set=He.set,Oa=function(a,e){if(He.has(a))throw new Xn(vd);return e.facade=a,He.set(a,e),e},ti=function(a){return He.get(a)||{}},Va=function(a){return He.has(a)}):(Vt=sT("state"),nT[Vt]=!0,Oa=function(a,e){if(Kn(a,Vt))throw new Xn(vd);return e.facade=a,aT(a,Vt,e),e},ti=function(a){return Kn(a,Vt)?a[Vt]:{}},Va=function(a){return Kn(a,Vt)});var He,Vt;Td.exports={set:Oa,get:ti,has:Va,enforce:uT,getterFor:cT}});var eo=m((nM,Pd)=>{"use strict";var lT=Wr(),xd=Function.prototype,Id=xd.apply,Ed=xd.call;Pd.exports=typeof Reflect=="object"&&Reflect.apply||(lT?Ed.bind(Id):function(){return Ed.apply(Id,arguments)})});var to=m((oM,Ad)=>{"use strict";var dT=nr(),pT=he();Ad.exports=function(a){if(dT(a)==="Function")return pT(a)}});var $d=m(Rd=>{"use strict";var wd={}.propertyIsEnumerable,kd=Object.getOwnPropertyDescriptor,hT=kd&&!wd.call({1:2},1);Rd.f=hT?function(e){var t=kd(this,e);return!!t&&t.enumerable}:wd});var Cd=m(Md=>{"use strict";var fT=$e(),mT=xe(),bT=$d(),gT=ei(),ST=ur(),vT=Gn(),yT=Ue(),TT=$n(),Ld=Object.getOwnPropertyDescriptor;Md.f=fT?Ld:function(e,t){if(e=ST(e),t=vT(t),TT)try{return Ld(e,t)}catch(r){}if(yT(e,t))return gT(!mT(bT.f,e,t),e[t])}});var ro=m((lM,Dd)=>{"use strict";var IT=Ee(),ET=z(),xT=/#|\.prototype\./,ri=function(a,e){var t=AT[PT(a)];return t===kT?!0:t===wT?!1:ET(e)?IT(e):!!e},PT=ri.normalize=function(a){return String(a).replace(xT,".").toLowerCase()},AT=ri.data={},wT=ri.NATIVE="N",kT=ri.POLYFILL="P";Dd.exports=ri});var ii=m((dM,Od)=>{"use strict";var Bd=to(),RT=Ze(),$T=Wr(),LT=Bd(Bd.bind);Od.exports=function(a,e){return RT(a),e===void 0?a:$T?LT(a,e):function(){return a.apply(e,arguments)}}});var Le=m((pM,_d)=>{"use strict";var ai=K(),MT=eo(),CT=to(),DT=z(),BT=Cd().f,OT=ro(),pr=La(),VT=ii(),hr=dr(),Vd=Ue();Xr();var _T=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 MT(a,this,arguments)};return e.prototype=a.prototype,e};_d.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ai:i?ai[t]:ai[t]&&ai[t].prototype,o=r?pr:pr[t]||hr(pr,t,{})[t],u=o.prototype,c,l,d,p,h,f,b,g,S;for(p in e)c=OT(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Vd(n,p),f=o[p],l&&(a.dontCallGetSet?(S=BT(n,p),b=S&&S.value):b=n[p]),h=l&&b?b:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&l?g=VT(h,ai):a.wrap&&l?g=_T(h):s&&DT(h)?g=CT(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&hr(g,"sham",!0),hr(o,p,g),s&&(d=t+"Prototype",Vd(pr,d)||hr(pr,d,{}),hr(pr[d],p,h),a.real&&u&&(c||!u[p])&&hr(u,p,h)))}});var qd=m((hM,Fd)=>{"use strict";var io=$e(),NT=Ue(),Nd=Function.prototype,FT=io&&Object.getOwnPropertyDescriptor,ao=NT(Nd,"name"),qT=ao&&function(){}.name==="something",UT=ao&&(!io||io&&FT(Nd,"name").configurable);Fd.exports={EXISTS:ao,PROPER:qT,CONFIGURABLE:UT}});var Hd=m((fM,Ud)=>{"use strict";var HT=Math.ceil,jT=Math.floor;Ud.exports=Math.trunc||function(e){var t=+e;return(t>0?jT:HT)(t)}});var _a=m((mM,jd)=>{"use strict";var GT=Hd();jd.exports=function(a){var e=+a;return e!==e||e===0?0:GT(e)}});var Wd=m((bM,Gd)=>{"use strict";var WT=_a(),YT=Math.max,QT=Math.min;Gd.exports=function(a,e){var t=WT(a);return t<0?YT(t+e,0):QT(t,e)}});var Qd=m((gM,Yd)=>{"use strict";var zT=_a(),KT=Math.min;Yd.exports=function(a){var e=zT(a);return e>0?KT(e,9007199254740991):0}});var Na=m((SM,zd)=>{"use strict";var JT=Qd();zd.exports=function(a){return JT(a.length)}});var Xd=m((vM,Jd)=>{"use strict";var XT=ur(),ZT=Wd(),eI=Na(),Kd=function(a){return function(e,t,r){var i=XT(e),s=eI(i);if(s===0)return!a&&-1;var n=ZT(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}};Jd.exports={includes:Kd(!0),indexOf:Kd(!1)}});var tp=m((yM,ep)=>{"use strict";var tI=he(),so=Ue(),rI=ur(),iI=Xd().indexOf,aI=Ba(),Zd=tI([].push);ep.exports=function(a,e){var t=rI(a),r=0,i=[],s;for(s in t)!so(aI,s)&&so(t,s)&&Zd(i,s);for(;e.length>r;)so(t,s=e[r++])&&(~iI(i,s)||Zd(i,s));return i}});var no=m((TM,rp)=>{"use strict";rp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var ap=m((IM,ip)=>{"use strict";var sI=tp(),nI=no();ip.exports=Object.keys||function(e){return sI(e,nI)}});var np=m(sp=>{"use strict";var oI=$e(),uI=Ln(),cI=Ot(),lI=ze(),dI=ur(),pI=ap();sp.f=oI&&!uI?Object.defineProperties:function(e,t){lI(e);for(var r=dI(t),i=pI(t),s=i.length,n=0,o;s>n;)cI.f(e,o=i[n++],r[o]);return e}});var oo=m((xM,op)=>{"use strict";var hI=Xe();op.exports=hI("document","documentElement")});var po=m((PM,fp)=>{"use strict";var fI=ze(),mI=np(),up=no(),bI=Ba(),gI=oo(),SI=Ra(),vI=Da(),cp=">",lp="<",co="prototype",lo="script",pp=vI("IE_PROTO"),uo=function(){},hp=function(a){return lp+lo+cp+a+lp+"/"+lo+cp},dp=function(a){a.write(hp("")),a.close();var e=a.parentWindow.Object;return a=null,e},yI=function(){var a=SI("iframe"),e="java"+lo+":",t;return a.style.display="none",gI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(hp("document.F=Object")),t.close(),t.F},Fa,qa=function(){try{Fa=new ActiveXObject("htmlfile")}catch(e){}qa=typeof document!="undefined"?document.domain&&Fa?dp(Fa):yI():dp(Fa);for(var a=up.length;a--;)delete qa[co][up[a]];return qa()};bI[pp]=!0;fp.exports=Object.create||function(e,t){var r;return e!==null?(uo[co]=fI(e),r=new uo,uo[co]=null,r[pp]=e):r=qa(),t===void 0?r:mI.f(r,t)}});var bp=m((AM,mp)=>{"use strict";var TI=Ee();mp.exports=!TI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var fo=m((wM,Sp)=>{"use strict";var II=Ue(),EI=z(),xI=Zr(),PI=Da(),AI=bp(),gp=PI("IE_PROTO"),ho=Object,wI=ho.prototype;Sp.exports=AI?ho.getPrototypeOf:function(a){var e=xI(a);if(II(e,gp))return e[gp];var t=e.constructor;return EI(t)&&e instanceof t?t.prototype:e instanceof ho?wI:null}});var fr=m((kM,vp)=>{"use strict";var kI=dr();vp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:kI(a,e,t),a}});var So=m((RM,Ip)=>{"use strict";var RI=Ee(),$I=z(),LI=Re(),MI=po(),yp=fo(),CI=fr(),DI=se(),BI=qe(),go=DI("iterator"),Tp=!1,et,mo,bo;[].keys&&(bo=[].keys(),"next"in bo?(mo=yp(yp(bo)),mo!==Object.prototype&&(et=mo)):Tp=!0);var OI=!LI(et)||RI(function(){var a={};return et[go].call(a)!==a});OI?et={}:BI&&(et=MI(et));$I(et[go])||CI(et,go,function(){return this});Ip.exports={IteratorPrototype:et,BUGGY_SAFARI_ITERATORS:Tp}});var Ua=m(($M,xp)=>{"use strict";var VI=se(),_I=VI("toStringTag"),Ep={};Ep[_I]="z";xp.exports=String(Ep)==="[object z]"});var si=m((LM,Pp)=>{"use strict";var NI=Ua(),FI=z(),Ha=nr(),qI=se(),UI=qI("toStringTag"),HI=Object,jI=Ha(function(){return arguments}())==="Arguments",GI=function(a,e){try{return a[e]}catch(t){}};Pp.exports=NI?Ha:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=GI(e=HI(a),UI))=="string"?t:jI?Ha(e):(r=Ha(e))==="Object"&&FI(e.callee)?"Arguments":r}});var wp=m((MM,Ap)=>{"use strict";var WI=Ua(),YI=si();Ap.exports=WI?{}.toString:function(){return"[object "+YI(this)+"]"}});var ni=m((CM,Rp)=>{"use strict";var QI=Ua(),zI=Ot().f,KI=dr(),JI=Ue(),XI=wp(),ZI=se(),kp=ZI("toStringTag");Rp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(JI(i,kp)||zI(i,kp,{configurable:!0,value:e}),r&&!QI&&KI(i,"toString",XI))}});var Lp=m((DM,$p)=>{"use strict";var eE=So().IteratorPrototype,tE=po(),rE=ei(),iE=ni(),aE=Bt(),sE=function(){return this};$p.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=tE(eE,{next:rE(+!r,t)}),iE(a,i,!1,!0),aE[i]=sE,a}});var Cp=m((BM,Mp)=>{"use strict";var nE=he(),oE=Ze();Mp.exports=function(a,e,t){try{return nE(oE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Bp=m((OM,Dp)=>{"use strict";var uE=Re();Dp.exports=function(a){return uE(a)||a===null}});var Vp=m((VM,Op)=>{"use strict";var cE=Bp(),lE=String,dE=TypeError;Op.exports=function(a){if(cE(a))return a;throw new dE("Can't set "+lE(a)+" as a prototype")}});var vo=m((_M,_p)=>{"use strict";var pE=Cp(),hE=Re(),fE=Yr(),mE=Vp();_p.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=pE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return fE(i),mE(s),hE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var zp=m((NM,Qp)=>{"use strict";var bE=Le(),gE=xe(),ja=qe(),Wp=qd(),SE=z(),vE=Lp(),Np=fo(),Fp=vo(),yE=ni(),TE=dr(),yo=fr(),IE=se(),qp=Bt(),Yp=So(),EE=Wp.PROPER,xE=Wp.CONFIGURABLE,Up=Yp.IteratorPrototype,Ga=Yp.BUGGY_SAFARI_ITERATORS,oi=IE("iterator"),Hp="keys",ui="values",jp="entries",Gp=function(){return this};Qp.exports=function(a,e,t,r,i,s,n){vE(t,e,r);var o=function(S){if(S===i&&p)return p;if(!Ga&&S&&S in l)return l[S];switch(S){case Hp:return function(){return new t(this,S)};case ui:return function(){return new t(this,S)};case jp:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[oi]||l["@@iterator"]||i&&l[i],p=!Ga&&d||o(i),h=e==="Array"&&l.entries||d,f,b,g;if(h&&(f=Np(h.call(new a)),f!==Object.prototype&&f.next&&(!ja&&Np(f)!==Up&&(Fp?Fp(f,Up):SE(f[oi])||yo(f,oi,Gp)),yE(f,u,!0,!0),ja&&(qp[u]=Gp))),EE&&i===ui&&d&&d.name!==ui&&(!ja&&xE?TE(l,"name",ui):(c=!0,p=function(){return gE(d,this)})),i)if(b={values:o(ui),keys:s?p:o(Hp),entries:o(jp)},n)for(g in b)(Ga||c||!(g in l))&&yo(l,g,b[g]);else bE({target:e,proto:!0,forced:Ga||c},b);return(!ja||n)&&l[oi]!==p&&yo(l,oi,p,{name:i}),qp[e]=p,b}});var Jp=m((FM,Kp)=>{"use strict";Kp.exports=function(a,e){return{value:a,done:e}}});var Io=m((qM,rh)=>{"use strict";var PE=ur(),To=An(),Xp=Bt(),eh=Zn(),AE=Ot().f,wE=zp(),Wa=Jp(),kE=qe(),RE=$e(),th="Array Iterator",$E=eh.set,LE=eh.getterFor(th);rh.exports=wE(Array,"Array",function(a,e){$E(this,{type:th,target:PE(a),index:0,kind:e})},function(){var a=LE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Wa(void 0,!0);switch(a.kind){case"keys":return Wa(t,!1);case"values":return Wa(e[t],!1)}return Wa([t,e[t]],!1)},"values");var Zp=Xp.Arguments=Xp.Array;To("keys");To("values");To("entries");if(!kE&&RE&&Zp.name!=="values")try{AE(Zp,"name",{value:"values"})}catch(a){}});var ah=m((UM,ih)=>{"use strict";var ME=se(),CE=Bt(),DE=ME("iterator"),BE=Array.prototype;ih.exports=function(a){return a!==void 0&&(CE.Array===a||BE[DE]===a)}});var Eo=m((HM,nh)=>{"use strict";var OE=si(),sh=Jr(),VE=or(),_E=Bt(),NE=se(),FE=NE("iterator");nh.exports=function(a){if(!VE(a))return sh(a,FE)||sh(a,"@@iterator")||_E[OE(a)]}});var uh=m((jM,oh)=>{"use strict";var qE=xe(),UE=Ze(),HE=ze(),jE=Kr(),GE=Eo(),WE=TypeError;oh.exports=function(a,e){var t=arguments.length<2?GE(a):e;if(UE(t))return HE(qE(t,a));throw new WE(jE(a)+" is not iterable")}});var dh=m((GM,lh)=>{"use strict";var YE=xe(),ch=ze(),QE=Jr();lh.exports=function(a,e,t){var r,i;ch(a);try{if(r=QE(a,"return"),!r){if(e==="throw")throw t;return t}r=YE(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return ch(r),t}});var Qa=m((WM,mh)=>{"use strict";var zE=ii(),KE=xe(),JE=ze(),XE=Kr(),ZE=ah(),ex=Na(),ph=zr(),tx=uh(),rx=Eo(),hh=dh(),ix=TypeError,Ya=function(a,e){this.stopped=a,this.result=e},fh=Ya.prototype;mh.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=zE(e,r),c,l,d,p,h,f,b,g=function(T){return c&&hh(c,"normal",T),new Ya(!0,T)},S=function(T){return i?(JE(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)c=a.iterator;else if(n)c=a;else{if(l=rx(a),!l)throw new ix(XE(a)+" is not iterable");if(ZE(l)){for(d=0,p=ex(a);p>d;d++)if(h=S(a[d]),h&&ph(fh,h))return h;return new Ya(!1)}c=tx(a,l)}for(f=s?a.next:c.next;!(b=KE(f,c)).done;){try{h=S(b.value)}catch(T){hh(c,"throw",T)}if(typeof h=="object"&&h&&ph(fh,h))return h}return new Ya(!1)}});var gh=m((YM,bh)=>{"use strict";var ax=$e(),sx=Ot(),nx=ei();bh.exports=function(a,e,t){ax?sx.f(a,e,nx(0,t)):a[e]=t}});var Sh=m(()=>{"use strict";var ox=Le(),ux=Qa(),cx=gh();ox({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ux(e,function(r,i){cx(t,r,i)},{AS_ENTRIES:!0}),t}})});var yh=m((KM,vh)=>{"use strict";Io();Sh();var lx=La();vh.exports=lx.Object.fromEntries});var Ih=m((JM,Th)=>{"use strict";Th.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 xh=m(()=>{"use strict";Io();var dx=Ih(),px=K(),hx=ni(),Eh=Bt();for(za in dx)hx(px[za],za),Eh[za]=Eh.Array;var za});var Ah=m((eC,Ph)=>{"use strict";var fx=yh();xh();Ph.exports=fx});var xo=m((tC,wh)=>{"use strict";var mx=Ah();wh.exports=mx});var kh=m(()=>{"use strict"});var Po=m((aC,Rh)=>{"use strict";var ci=K(),bx=cr(),gx=nr(),Ka=function(a){return bx.slice(0,a.length)===a};Rh.exports=function(){return Ka("Bun/")?"BUN":Ka("Cloudflare-Workers")?"CLOUDFLARE":Ka("Deno/")?"DENO":Ka("Node.js/")?"NODE":ci.Bun&&typeof Bun.version=="string"?"BUN":ci.Deno&&typeof Deno.version=="object"?"DENO":gx(ci.process)==="process"?"NODE":ci.window&&ci.document?"BROWSER":"REST"}()});var Ja=m((sC,$h)=>{"use strict";var Sx=Po();$h.exports=Sx==="NODE"});var Mh=m((nC,Lh)=>{"use strict";var vx=Ot();Lh.exports=function(a,e,t){return vx.f(a,e,t)}});var Bh=m((oC,Dh)=>{"use strict";var yx=Xe(),Tx=Mh(),Ix=se(),Ex=$e(),Ch=Ix("species");Dh.exports=function(a){var e=yx(a);Ex&&e&&!e[Ch]&&Tx(e,Ch,{configurable:!0,get:function(){return this}})}});var Vh=m((uC,Oh)=>{"use strict";var xx=zr(),Px=TypeError;Oh.exports=function(a,e){if(xx(e,a))return a;throw new Px("Incorrect invocation")}});var wo=m((cC,_h)=>{"use strict";var Ax=he(),wx=z(),Ao=Xr(),kx=Ax(Function.toString);wx(Ao.inspectSource)||(Ao.inspectSource=function(a){return kx(a)});_h.exports=Ao.inspectSource});var jh=m((lC,Hh)=>{"use strict";var Rx=he(),$x=Ee(),Nh=z(),Lx=si(),Mx=Xe(),Cx=wo(),Fh=function(){},qh=Mx("Reflect","construct"),ko=/^\s*(?:class|function)\b/,Dx=Rx(ko.exec),Bx=!ko.test(Fh),li=function(e){if(!Nh(e))return!1;try{return qh(Fh,[],e),!0}catch(t){return!1}},Uh=function(e){if(!Nh(e))return!1;switch(Lx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Bx||!!Dx(ko,Cx(e))}catch(t){return!0}};Uh.sham=!0;Hh.exports=!qh||$x(function(){var a;return li(li.call)||!li(Object)||!li(function(){a=!0})||a})?Uh:li});var Wh=m((dC,Gh)=>{"use strict";var Ox=jh(),Vx=Kr(),_x=TypeError;Gh.exports=function(a){if(Ox(a))return a;throw new _x(Vx(a)+" is not a constructor")}});var Ro=m((pC,Qh)=>{"use strict";var Yh=ze(),Nx=Wh(),Fx=or(),qx=se(),Ux=qx("species");Qh.exports=function(a,e){var t=Yh(a).constructor,r;return t===void 0||Fx(r=Yh(t)[Ux])?e:Nx(r)}});var Kh=m((hC,zh)=>{"use strict";var Hx=he();zh.exports=Hx([].slice)});var Xh=m((fC,Jh)=>{"use strict";var jx=TypeError;Jh.exports=function(a,e){if(a<e)throw new jx("Not enough arguments");return a}});var $o=m((mC,Zh)=>{"use strict";var Gx=cr();Zh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Gx)});var No=m((bC,cf)=>{"use strict";var Pe=K(),Wx=eo(),Yx=ii(),ef=z(),Qx=Ue(),uf=Ee(),tf=oo(),zx=Kh(),rf=Ra(),Kx=Xh(),Jx=$o(),Xx=Ja(),Oo=Pe.setImmediate,Vo=Pe.clearImmediate,Zx=Pe.process,Lo=Pe.Dispatch,eP=Pe.Function,af=Pe.MessageChannel,tP=Pe.String,Mo=0,di={},sf="onreadystatechange",pi,_t,Co,Do;uf(function(){pi=Pe.location});var _o=function(a){if(Qx(di,a)){var e=di[a];delete di[a],e()}},Bo=function(a){return function(){_o(a)}},nf=function(a){_o(a.data)},of=function(a){Pe.postMessage(tP(a),pi.protocol+"//"+pi.host)};(!Oo||!Vo)&&(Oo=function(e){Kx(arguments.length,1);var t=ef(e)?e:eP(e),r=zx(arguments,1);return di[++Mo]=function(){Wx(t,void 0,r)},_t(Mo),Mo},Vo=function(e){delete di[e]},Xx?_t=function(a){Zx.nextTick(Bo(a))}:Lo&&Lo.now?_t=function(a){Lo.now(Bo(a))}:af&&!Jx?(Co=new af,Do=Co.port2,Co.port1.onmessage=nf,_t=Yx(Do.postMessage,Do)):Pe.addEventListener&&ef(Pe.postMessage)&&!Pe.importScripts&&pi&&pi.protocol!=="file:"&&!uf(of)?(_t=of,Pe.addEventListener("message",nf,!1)):sf in rf("script")?_t=function(a){tf.appendChild(rf("script"))[sf]=function(){tf.removeChild(this),_o(a)}}:_t=function(a){setTimeout(Bo(a),0)});cf.exports={set:Oo,clear:Vo}});var pf=m((gC,df)=>{"use strict";var lf=K(),rP=$e(),iP=Object.getOwnPropertyDescriptor;df.exports=function(a){if(!rP)return lf[a];var e=iP(lf,a);return e&&e.value}});var Fo=m((SC,ff)=>{"use strict";var hf=function(){this.head=null,this.tail=null};hf.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}}};ff.exports=hf});var bf=m((vC,mf)=>{"use strict";var aP=cr();mf.exports=/ipad|iphone|ipod/i.test(aP)&&typeof Pebble!="undefined"});var Sf=m((yC,gf)=>{"use strict";var sP=cr();gf.exports=/web0s(?!.*chrome)/i.test(sP)});var Pf=m((TC,xf)=>{"use strict";var br=K(),nP=pf(),vf=ii(),qo=No().set,oP=Fo(),uP=$o(),cP=bf(),lP=Sf(),Uo=Ja(),yf=br.MutationObserver||br.WebKitMutationObserver,Tf=br.document,If=br.process,Xa=br.Promise,Go=nP("queueMicrotask"),mr,Ho,jo,Za,Ef;Go||(hi=new oP,fi=function(){var a,e;for(Uo&&(a=If.domain)&&a.exit();e=hi.get();)try{e()}catch(t){throw hi.head&&mr(),t}a&&a.enter()},!uP&&!Uo&&!lP&&yf&&Tf?(Ho=!0,jo=Tf.createTextNode(""),new yf(fi).observe(jo,{characterData:!0}),mr=function(){jo.data=Ho=!Ho}):!cP&&Xa&&Xa.resolve?(Za=Xa.resolve(void 0),Za.constructor=Xa,Ef=vf(Za.then,Za),mr=function(){Ef(fi)}):Uo?mr=function(){If.nextTick(fi)}:(qo=vf(qo,br),mr=function(){qo(fi)}),Go=function(a){hi.head||mr(),hi.add(a)});var hi,fi;xf.exports=Go});var wf=m((IC,Af)=>{"use strict";Af.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var es=m((EC,kf)=>{"use strict";kf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Nt=m((xC,Rf)=>{"use strict";var dP=K();Rf.exports=dP.Promise});var gr=m((PC,Cf)=>{"use strict";var pP=K(),mi=Nt(),hP=z(),fP=ro(),mP=wo(),bP=se(),$f=Po(),gP=qe(),Wo=Bn(),Lf=mi&&mi.prototype,SP=bP("species"),Yo=!1,Mf=hP(pP.PromiseRejectionEvent),vP=fP("Promise",function(){var a=mP(mi),e=a!==String(mi);if(!e&&Wo===66||gP&&!(Lf.catch&&Lf.finally))return!0;if(!Wo||Wo<51||!/native code/.test(a)){var t=new mi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[SP]=r,Yo=t.then(function(){})instanceof r,!Yo)return!0}return!e&&($f==="BROWSER"||$f==="DENO")&&!Mf});Cf.exports={CONSTRUCTOR:vP,REJECTION_EVENT:Mf,SUBCLASSING:Yo}});var Sr=m((AC,Bf)=>{"use strict";var Df=Ze(),yP=TypeError,TP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new yP("Bad Promise constructor");e=r,t=i}),this.resolve=Df(e),this.reject=Df(t)};Bf.exports.f=function(a){return new TP(a)}});var em=m(()=>{"use strict";var IP=Le(),EP=qe(),as=Ja(),bt=K(),Ir=xe(),Of=fr(),Vf=vo(),xP=ni(),PP=Bh(),AP=Ze(),is=z(),wP=Re(),kP=Vh(),RP=Ro(),Uf=No().set,Xo=Pf(),$P=wf(),LP=es(),MP=Fo(),Hf=Zn(),ss=Nt(),Zo=gr(),jf=Sr(),ns="Promise",Gf=Zo.CONSTRUCTOR,CP=Zo.REJECTION_EVENT,DP=Zo.SUBCLASSING,Qo=Hf.getterFor(ns),BP=Hf.set,vr=ss&&ss.prototype,Ft=ss,ts=vr,Wf=bt.TypeError,zo=bt.document,eu=bt.process,Ko=jf.f,OP=Ko,VP=!!(zo&&zo.createEvent&&bt.dispatchEvent),Yf="unhandledrejection",_P="rejectionhandled",_f=0,Qf=1,NP=2,tu=1,zf=2,rs,Nf,FP,Ff,Kf=function(a){var e;return wP(a)&&is(e=a.then)?e:!1},Jf=function(a,e){var t=e.value,r=e.state===Qf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===zf&&UP(e),e.rejection=tu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Wf("Promise-chain cycle")):(c=Kf(u))?Ir(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},Xf=function(a,e){a.notified||(a.notified=!0,Xo(function(){for(var t=a.reactions,r;r=t.get();)Jf(r,a);a.notified=!1,e&&!a.rejection&&qP(a)}))},Zf=function(a,e,t){var r,i;VP?(r=zo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),bt.dispatchEvent(r)):r={promise:e,reason:t},!CP&&(i=bt["on"+a])?i(r):a===Yf&&$P("Unhandled promise rejection",t)},qP=function(a){Ir(Uf,bt,function(){var e=a.facade,t=a.value,r=qf(a),i;if(r&&(i=LP(function(){as?eu.emit("unhandledRejection",t,e):Zf(Yf,e,t)}),a.rejection=as||qf(a)?zf:tu,i.error))throw i.value})},qf=function(a){return a.rejection!==tu&&!a.parent},UP=function(a){Ir(Uf,bt,function(){var e=a.facade;as?eu.emit("rejectionHandled",e):Zf(_P,e,a.value)})},yr=function(a,e,t){return function(r){a(e,r,t)}},Tr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=NP,Xf(a,!0))},Jo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Wf("Promise can't be resolved itself");var r=Kf(e);r?Xo(function(){var i={done:!1};try{Ir(r,e,yr(Jo,i,a),yr(Tr,i,a))}catch(s){Tr(i,s,a)}}):(a.value=e,a.state=Qf,Xf(a,!1))}catch(i){Tr({done:!1},i,a)}}};if(Gf&&(Ft=function(e){kP(this,ts),AP(e),Ir(rs,this);var t=Qo(this);try{e(yr(Jo,t),yr(Tr,t))}catch(r){Tr(t,r)}},ts=Ft.prototype,rs=function(e){BP(this,{type:ns,done:!1,notified:!1,parent:!1,reactions:new MP,rejection:!1,state:_f,value:void 0})},rs.prototype=Of(ts,"then",function(e,t){var r=Qo(this),i=Ko(RP(this,Ft));return r.parent=!0,i.ok=is(e)?e:!0,i.fail=is(t)&&t,i.domain=as?eu.domain:void 0,r.state===_f?r.reactions.add(i):Xo(function(){Jf(i,r)}),i.promise}),Nf=function(){var a=new rs,e=Qo(a);this.promise=a,this.resolve=yr(Jo,e),this.reject=yr(Tr,e)},jf.f=Ko=function(a){return a===Ft||a===FP?new Nf(a):OP(a)},!EP&&is(ss)&&vr!==Object.prototype)){Ff=vr.then,DP||Of(vr,"then",function(e,t){var r=this;return new Ft(function(i,s){Ir(Ff,r,i,s)}).then(e,t)},{unsafe:!0});try{delete vr.constructor}catch(a){}Vf&&Vf(vr,ts)}IP({global:!0,constructor:!0,wrap:!0,forced:Gf},{Promise:Ft});xP(Ft,ns,!1,!0);PP(ns)});var sm=m((RC,am)=>{"use strict";var HP=se(),rm=HP("iterator"),im=!1;try{tm=0,ru={next:function(){return{done:!!tm++}},return:function(){im=!0}},ru[rm]=function(){return this},Array.from(ru,function(){throw 2})}catch(a){}var tm,ru;am.exports=function(a,e){try{if(!e&&!im)return!1}catch(i){return!1}var t=!1;try{var r={};r[rm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var iu=m(($C,nm)=>{"use strict";var jP=Nt(),GP=sm(),WP=gr().CONSTRUCTOR;nm.exports=WP||!GP(function(a){jP.all(a).then(void 0,function(){})})});var om=m(()=>{"use strict";var YP=Le(),QP=xe(),zP=Ze(),KP=Sr(),JP=es(),XP=Qa(),ZP=iu();YP({target:"Promise",stat:!0,forced:ZP},{all:function(e){var t=this,r=KP.f(t),i=r.resolve,s=r.reject,n=JP(function(){var o=zP(t.resolve),u=[],c=0,l=1;XP(e,function(d){var p=c++,h=!1;l++,QP(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 cm=m(()=>{"use strict";var eA=Le(),tA=qe(),rA=gr().CONSTRUCTOR,su=Nt(),iA=Xe(),aA=z(),sA=fr(),um=su&&su.prototype;eA({target:"Promise",proto:!0,forced:rA,real:!0},{catch:function(a){return this.then(void 0,a)}});!tA&&aA(su)&&(au=iA("Promise").prototype.catch,um.catch!==au&&sA(um,"catch",au,{unsafe:!0}));var au});var lm=m(()=>{"use strict";var nA=Le(),oA=xe(),uA=Ze(),cA=Sr(),lA=es(),dA=Qa(),pA=iu();nA({target:"Promise",stat:!0,forced:pA},{race:function(e){var t=this,r=cA.f(t),i=r.reject,s=lA(function(){var n=uA(t.resolve);dA(e,function(o){oA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var dm=m(()=>{"use strict";var hA=Le(),fA=Sr(),mA=gr().CONSTRUCTOR;hA({target:"Promise",stat:!0,forced:mA},{reject:function(e){var t=fA.f(this),r=t.reject;return r(e),t.promise}})});var nu=m((NC,pm)=>{"use strict";var bA=ze(),gA=Re(),SA=Sr();pm.exports=function(a,e){if(bA(a),gA(e)&&e.constructor===a)return e;var t=SA.f(a),r=t.resolve;return r(e),t.promise}});var mm=m(()=>{"use strict";var vA=Le(),yA=Xe(),hm=qe(),TA=Nt(),fm=gr().CONSTRUCTOR,IA=nu(),EA=yA("Promise"),xA=hm&&!fm;vA({target:"Promise",stat:!0,forced:hm||fm},{resolve:function(e){return IA(xA&&this===EA?TA:this,e)}})});var bm=m(()=>{"use strict";em();om();cm();lm();dm();mm()});var ym=m(()=>{"use strict";var PA=Le(),AA=qe(),os=Nt(),wA=Ee(),Sm=Xe(),vm=z(),kA=Ro(),gm=nu(),RA=fr(),uu=os&&os.prototype,$A=!!os&&wA(function(){uu.finally.call({then:function(){}},function(){})});PA({target:"Promise",proto:!0,real:!0,forced:$A},{finally:function(a){var e=kA(this,Sm("Promise")),t=vm(a);return this.then(t?function(r){return gm(e,a()).then(function(){return r})}:a,t?function(r){return gm(e,a()).then(function(){throw r})}:a)}});!AA&&vm(os)&&(ou=Sm("Promise").prototype.finally,uu.finally!==ou&&RA(uu,"finally",ou,{unsafe:!0}));var ou});var us=m((WC,Tm)=>{"use strict";var LA=Xe();Tm.exports=LA});var Em=m((YC,Im)=>{"use strict";kh();bm();ym();var MA=us();Im.exports=MA("Promise","finally")});var Pm=m((QC,xm)=>{"use strict";var CA=Em();xm.exports=CA});var cs=m((zC,Am)=>{"use strict";var DA=Pm();Am.exports=DA});var Jm=m(()=>{"use strict";var cw=Le(),lw=Zr(),dw=Na(),pw=_a(),hw=An();cw({target:"Array",proto:!0},{at:function(e){var t=lw(this),r=dw(t),i=pw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});hw("at")});var Zm=m((a0,Xm)=>{"use strict";Jm();var fw=us();Xm.exports=fw("Array","at")});var tb=m((s0,eb)=>{"use strict";var mw=Zm();eb.exports=mw});var vi=m((n0,rb)=>{"use strict";var bw=tb();rb.exports=bw});var og=m(()=>{"use strict"});var ug=m(()=>{"use strict"});var lg=m((h_,cg)=>{"use strict";var Ik=Re(),Ek=nr(),xk=se(),Pk=xk("match");cg.exports=function(a){var e;return Ik(a)&&((e=a[Pk])!==void 0?!!e:Ek(a)==="RegExp")}});var pg=m((f_,dg)=>{"use strict";var Ak=si(),wk=String;dg.exports=function(a){if(Ak(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return wk(a)}});var fg=m((m_,hg)=>{"use strict";var kk=ze();hg.exports=function(){var a=kk(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 gg=m((b_,bg)=>{"use strict";var Rk=xe(),$k=Ue(),Lk=zr(),Mk=fg(),mg=RegExp.prototype;bg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in mg)&&!$k(a,"flags")&&Lk(mg,a)?Rk(Mk,a):e}});var vg=m((g_,Sg)=>{"use strict";var _u=he(),Ck=Zr(),Dk=Math.floor,Ou=_u("".charAt),Bk=_u("".replace),Vu=_u("".slice),Ok=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Vk=/\$([$&'`]|\d{1,2})/g;Sg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Vk;return i!==void 0&&(i=Ck(i),u=Ok),Bk(s,u,function(c,l){var d;switch(Ou(l,0)){case"$":return"$";case"&":return a;case"`":return Vu(e,0,t);case"'":return Vu(e,n);case"<":d=i[Vu(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=Dk(p/10);return h===0?c:h<=o?r[h-1]===void 0?Ou(l,1):r[h-1]+Ou(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var Ig=m(()=>{"use strict";var _k=Le(),Nk=xe(),Fu=he(),yg=Yr(),Fk=z(),qk=or(),Uk=lg(),Cr=pg(),Hk=Jr(),jk=gg(),Gk=vg(),Wk=se(),Yk=qe(),Qk=Wk("replace"),zk=TypeError,Nu=Fu("".indexOf),Kk=Fu("".replace),Tg=Fu("".slice),Jk=Math.max;_k({target:"String",proto:!0},{replaceAll:function(e,t){var r=yg(this),i,s,n,o,u,c,l,d,p,h,f=0,b="";if(!qk(e)){if(i=Uk(e),i&&(s=Cr(yg(jk(e))),!~Nu(s,"g")))throw new zk("`.replaceAll` does not allow non-global regexes");if(n=Hk(e,Qk),n)return Nk(n,e,r,t);if(Yk&&i)return Kk(Cr(r),e,t)}for(o=Cr(r),u=Cr(e),c=Fk(t),c||(t=Cr(t)),l=u.length,d=Jk(1,l),p=Nu(o,u);p!==-1;)h=c?Cr(t(u,p,o)):Gk(u,o,p,[],void 0,t),b+=Tg(o,f,p)+h,f=p+l,p=p+d>o.length?-1:Nu(o,u,p+d);return f<o.length&&(b+=Tg(o,f)),b}})});var xg=m((y_,Eg)=>{"use strict";og();ug();Ig();var Xk=us();Eg.exports=Xk("String","replaceAll")});var Ag=m((T_,Pg)=>{"use strict";var Zk=xg();Pg.exports=Zk});var kg=m((I_,wg)=>{"use strict";var eR=Ag();wg.exports=eR});var Gc="2.0.111-dev.974e99b3.0";var pe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(pe||{}),mt=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(mt||{});var Aa=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Aa||{}),yn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(yn||{});var Tn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Tn||{});import{assertNever as Jc,assertNonNullable as yv,isNonNullable as wa,ValueSubject as In,Subject as Tv,Subscription as Iv,merge as Ev,observableFrom as xv,fromEvent as Yc,map as Qc,tap as zc,filterChanged as Pv,isNullable as En,ErrorCategory as Kc}from"@vkontakte/videoplayer-shared";var Wc=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 ka=class{constructor(e){this.connection$=new In(void 0);this.castState$=new In("NOT_AVAILABLE");this.errorEvent$=new Tv;this.realCastState$=new In("NOT_AVAILABLE");this.subscription=new Iv;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=wa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Wc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Kc.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(){wa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();En(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();En(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(Yc(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 Jc(i.sessionState)}})).add(Ev(Yc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(zc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Qc(i=>i.castState)),xv([r.getCastState()])).pipe(Pv(),Qc(Av),zc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=wa(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();yv(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(En(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"?wa(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:Kc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Av=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 Jc(a)}};var AS=Qe(xo(),1);var Om=Qe(cs(),1);import{assertNever as wm}from"@vkontakte/videoplayer-shared";var ae=(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:wm(t)}return a},cu=(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:wm(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as BA,Subject as ls,merge as km}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new ls;this.transitionEnded$=new ls;this.transitionUpdated$=new ls;this.forceChanged$=new ls;this.stateChangeStarted$=km(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=km(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||BA(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 OA}from"@vkontakte/videoplayer-shared";var Rm=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 OA(a)}};import{assertNever as Er,assertNonNullable as qt,debounce as $m,ErrorCategory as Lm,fromEvent as Ut,isNonNullable as Mm,map as Cm,merge as Dm,observableFrom as VA,Subject as _A,Subscription as lu,timeout as NA,getHighestQuality as FA}from"@vkontakte/videoplayer-shared";var qA=5,UA=5,HA=500,Bm=7e3,bi=class{constructor(e){this.subscription=new lu;this.loadMediaTimeoutSubscription=new lu;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:Er(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:Er(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:Er(e)}break}default:Er(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Rm(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 lu;this.subscription.add(e),this.subscription.add(Dm(this.videoState.stateChangeStarted$.pipe(Cm(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Cm(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 _A;e.add(i.pipe($m(HA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ut(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)>qA)&&i.next(o),s=o})),e.add(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ut(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<UA&&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:Er(n)}}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Dm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,VA(["init"])).pipe($m(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];qt(l);let d=FA(Object.keys(l));qt(d);let p=l[d];qt(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];qt(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];qt(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];qt(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];qt(l),r=ae(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:Lm.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Er(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 Mm(o)&&(n.metadata.title=o),Mm(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(NA(Bm).subscribe(()=>s(`timeout(${Bm})`)))});(0,Om.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:Lm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as _m}from"@vkontakte/videoplayer-shared";import{clearVideoElement as jA}from"@vkontakte/videoplayer-shared";var Vm=a=>{try{a.pause(),a.playbackRate=0,jA(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as GA,Subscription as WA}from"@vkontakte/videoplayer-shared";var du=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)}},pu=window.WeakMap?new WeakMap:new du,hu=window.WeakMap?new WeakMap:new Map,YA=(a,e=20)=>{let t=0;return GA(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},fe=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?_m(t):(t=document.createElement("video"),a.appendChild(t)),pu.set(t,r);let i=new WA;return i.add(YA(t,e)),hu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},me=a=>{let e=hu.get(a);e==null||e.unsubscribe(),hu.delete(a);let t=pu.get(a);pu.delete(a),t?_m(a):Vm(a)};import{assertNonNullable as gi,isNonNullable as Je,isNullable as KA,fromEvent as xr,merge as Nm,observableFrom as Fm,filterChanged as qm,map as Si,Subject as Um,Subscription as JA,ValueSubject as XA,ErrorCategory as ZA}from"@vkontakte/videoplayer-shared";import{isNonNullable as fu,isNullable as QA,Subscription as zA}from"@vkontakte/videoplayer-shared";var ds=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=QA(i),c=new zA;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},Ke=(a,e,t)=>ds(e,()=>a.loop,r=>{fu(r)&&(a.loop=r)},{onError:t}),be=(a,e,t,r)=>ds(e,()=>({muted:a.muted,volume:a.volume}),i=>{fu(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}),Me=(a,e,t,r)=>ds(e,()=>a.playbackRate,i=>{fu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),gt=ds;var ew=a=>["__",a.language,a.label].join("|"),tw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},mu=class a{constructor(){this.available$=new Um;this.current$=new XA(void 0);this.error$=new Um;this.subscription=new JA;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:ZA.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(gt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Je(s)&&this.setInternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Si(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(gt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Je(s)&&this.setExternal(s)},{equal:(s,n)=>Je(s)&&Je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Si(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(gt(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(gt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){gi(this.video);let{textTracks:e}=this.video;this.subscription.add(xr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Nm(xr(e,"addtrack"),xr(e,"removetrack"),Fm(["init"])).pipe(Si(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),qm((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Nm(xr(e,"change"),Fm(["init"])).pipe(Si(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Si(r=>r&&this.htmlTextTrackToITextTrack(r).id),qm()).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(xr(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(xr(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;Je(t.align)&&(i.align=t.align),Je(t.position)&&(i.position=t.position),Je(t.size)&&(i.size=t.size),Je(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){gi(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:ew(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){gi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(KA(e)||!tw(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){gi(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){gi(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)}},Ce=mu;var rt=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 Hm=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},bu=a=>{let e=Hm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},jm=a=>{let e=Hm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as De,map as St,merge as Wm,filterChanged as iw,isNonNullable as Ym,Subject as aw,filter as Qm,mapTo as zm,combine as sw,once as nw,ErrorCategory as ow,ValueSubject as Km,clientChecker as uw}from"@vkontakte/videoplayer-shared";var rw=3,Gm=(a,e,t=rw)=>{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 ge=a=>{let e=v=>De(a,v).pipe(zm(void 0)),r=Wm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>De(a,v))).pipe(St(v=>v.type==="ended"?a.readyState<2:a.readyState<3),iw()),i=Wm(De(a,"progress"),De(a,"timeupdate")).pipe(St(()=>Gm(a.buffered,a.currentTime))),s=uw.isSafari?sw({play:e("play").pipe(nw()),playing:e("playing")}).pipe(zm(void 0)):e("playing"),n=De(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume}))),o=De(a,"ratechange").pipe(St(()=>a.playbackRate)),u=De(a,"error").pipe(Qm(()=>!!(a.error||a.played.length)),St(()=>{var y;let v=a.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:ow.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(y=a.error)!=null?y:void 0}})),c=De(a,"timeupdate").pipe(St(()=>a.currentTime)),l=new aw,d=.3,p;c.subscribe(v=>{a.loop&&Ym(p)&&Ym(v)&&p>=a.duration-d&&v<=d&&l.next(p),p=v});let h=e("pause").pipe(Qm(()=>!a.error&&p!==a.duration)),f=De(a,"enterpictureinpicture"),b=De(a,"leavepictureinpicture"),g=new Km(jm(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Km(bu(a));return De(a,"fullscreenchange").pipe(St(()=>bu(a))).subscribe(S),{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$:De(a,"durationchange").pipe(St(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as vt}from"@vkontakte/videoplayer-shared";var yt=a=>{switch(a){case"mobile":return vt.Q_144P;case"lowest":return vt.Q_240P;case"low":return vt.Q_360P;case"sd":case"medium":return vt.Q_480P;case"hd":case"high":return vt.Q_720P;case"fullhd":case"full":return vt.Q_1080P;case"quadhd":case"quad":return vt.Q_1440P;case"ultrahd":case"ultra":return vt.Q_2160P}};var Ht=Qe(vi(),1);import{isNonNullable as Se,isNullable as Su,now as lb,isHigher as vu,isHigherOrEqual as nb,isInvariantQuality as ob,isLower as yu,isLowerOrEqual as ub,videoSizeToQuality as gw,assertNotEmptyArray as db,assertNonNullable as Sw}from"@vkontakte/videoplayer-shared";var gu=!1,it={},ib=a=>{gu=a},ab=()=>{it={}},sb=a=>{a(it)},yi=(a,e)=>{var t;gu&&(it.meta=(t=it.meta)!=null?t:{},it.meta[a]=e)},ne=class{constructor(e){this.name=e}next(e){var r,i;if(!gu)return;it.series=(r=it.series)!=null?r:{};let t=(i=it.series[this.name])!=null?i:[];t.push([Date.now(),e]),it.series[this.name]=t}};var vw=new ne("best_bitrate"),pb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Tu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ti=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=lb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},hb='Assertion "ABR Tracks is empty array" failed',ps=(a,e,t,r)=>{var u;let i=[...e].sort(Tu(1)),s=[...t].sort(Tu(1)),n=s.filter(c=>Se(c.bitrate)&&Se(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,Ht.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Ht.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Ht.default)(n,-1):(0,Ht.default)(s,0)},cb=a=>"quality"in a,fb=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&lb()-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=cb(s)?"video":"audio",o=cb(s)?s.quality:s.bitrate;return e({message:`
7
7
  [last ${n} selected] ${o}
8
8
  `}),s}return r==null||r.recordSwitch(t),t},Tt=(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 H,N,L,F,_;db(a,hb);let h=r.usePixelRatio&&(H=window.devicePixelRatio)!=null?H: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&&gw(f),g=r.considerPlaybackRate&&Se(o)?o:1,S=a.filter(w=>!ob(w.quality)).sort((w,x)=>vu(w.quality,x.quality)?-1:1),T=(N=(0,Ht.default)(S,-1))==null?void 0:N.quality,v=(L=(0,Ht.default)(S,0))==null?void 0:L.quality,y=Su(i)||Se(i.min)&&Se(i.max)&&yu(i.max,i.min)||Se(i.min)&&v&&vu(i.min,v)||Se(i.max)&&T&&yu(i.max,T),I=g*pb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),$={},O=S.filter(w=>{if(!(b?yu(w.quality,b):!0))return $[w.quality]="FitsContainer",!1;if(!(Se(t)&&isFinite(t)&&Se(w.bitrate)?t-s>=w.bitrate*I:!0))return $[w.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Se(r.minBufferToSwitchUp)&&u&&!ob(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&vu(w.quality,u.quality))return $[w.quality]="Buffer",!1;if(!!d&&nb(w.quality,d))return $[w.quality]="DroppedFramesLimit",!1;let X=y||(Su(i.max)||ub(w.quality,i.max))&&(Su(i.min)||nb(w.quality,i.min)),ce=Se(l)&&!l?ub(w.quality,r.backgroundVideoQualityLimit):!0;return!X||!ce?($[w.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&vw.next(O.bitrate);let C=(F=O!=null?O:S[Math.ceil((S.length-1)/2)])!=null?F:a[0];return C.quality!==((_=c==null?void 0:c.last)==null?void 0:_.quality)&&p({message:`
9
9
  [VIDEO TRACKS ABR]
@@ -55,7 +55,7 @@ var pv=Object.create;var gn=Object.defineProperty,hv=Object.defineProperties,fv=
55
55
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
56
56
 
57
57
  [selected audio track] ${h==null?void 0:h.id}
58
- `}),h&&fb(i,u,h,o)};var re=a=>new URL(a).hostname;import{assertNever as Tb,assertNonNullable as Ib,combine as Nw,debounce as Fw,ErrorCategory as Eb,filter as xb,filterChanged as qw,isNonNullable as Au,map as gs,merge as Pb,observableFrom as Uw,once as Hw,Subscription as jw,ValueSubject as wu,videoQualityToHeight as Gw,videoSizeToQuality as Ww}from"@vkontakte/videoplayer-shared";var bb=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"))},ve=a=>R(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!bb(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return bb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as fs,isNullable as Iw,assertNonNullable as xi}from"@vkontakte/videoplayer-shared";import{isNonNullable as gb,assertNonNullable as hs,now as yw}from"@vkontakte/videoplayer-shared";function ie(){return yw()}function Iu(a){return ie()-a}function Eu(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 Sb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Pr(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;hs(l);let L=Iu(l),F;if(L<b){F=b-L,setTimeout(g,F);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},S=L=>(s=L,N),T=L=>(d=L,N),v=()=>(h="json",N),y=()=>{if(!u){if(--c>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=L=>(p=L,N),$=()=>{l=ie(),n=new i,n.open("get",a);let L=0,F,_=0,w=()=>(hs(l),Math.max(l,Math.max(F||0,_||0)));if(s&&n.addEventListener("progress",x=>{let D=ie();s.updateChunk&&x.loaded>L&&(s.updateChunk(w(),x.loaded-L),L=x.loaded,F=D)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;hs(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let D=n.response.byteLength-L;D&&s.updateChunk&&s.updateChunk(w(),D)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{hs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(_=ie(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),N},N={withBitrateReporting:S,withParallel:I,withJSONResponse:v,withRetryCount:L=>(c=L,N),withRetryInterval:(L,F)=>(gb(L)&&(b=L),gb(F)&&(f=F),N),withTimeout:L=>(o=L,N),withFinally:T,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return N}var Ii=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 Ei=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=ie(),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=ie()-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=Pr(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=ie()}_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=ie();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 ms=1e4,xu=3;var Ew=6e4,xw=10,Pw=1,Aw=500,Pi=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 Ii(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Eu(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=Eu(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||fs(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=()=>{Sb(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 Ei(xu,ms,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 y=s&&(!l||l===this.rep);return y||t("Not running!"),y},p=(y,I,$)=>{u&&u.abort(),u=Pr(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withTimeout(ms).withBitrateReporting(this.bitrateSwitcher).withRetryCount(xu).withFinally(()=>{u=null}).send()},h=(y,I,$)=>{xi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let I=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${I}=>${y}`),r.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=ie()-1e4,G=0;for(let C=0;C<this.bufferStates.length;C++){let H=this.bufferStates[C];y=Math.min(y,H.buf),H.ts<$&&G++}this.bufferStates.splice(0,G),t(`update playback rate; minBuffer=${y} drop=${G} jitter=${this.sourceJitter}`);let O=y-Pw;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?f(1.15):O>1?f(1.1):O>.3?f(1.05):f(1)}},S=y=>{let I,$=()=>I&&I.start?I.start.length:0,G=x=>I.start[x]/1e3,O=x=>I.dur[x]/1e3,C=x=>I.fragIndex+x,H=(x,D)=>({chunkIdx:C(x),startTS:G(x),dur:O(x),discontinuity:D}),N=()=>{let x=0;if(I&&I.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=D;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let X=I.dur.length-1;for(;X>=0&&(Q-=I.dur[X],!(Q<=0));--X);x=Math.min(X,I.dur.length-1-W),x=Math.max(x,0)}return H(x,!0)},L=x=>{let D=$();if(!(D<=0)){if(fs(x)){for(let W=0;W<D;W++)if(G(W)>x)return H(W)}return N()}},F=x=>{let D=$(),W=x?x.chunkIdx+1:0,Q=W-I.fragIndex;if(!(D<=0)){if(!x||Q<0||Q-D>xw)return t(`Resync: offset=${Q} bChunks=${D} chunk=`+JSON.stringify(x)),N();if(!(Q>=D))return H(W-I.fragIndex,!1)}},_=(x,D,W)=>{c&&c.abort(),c=Pr(this.urlResolver.resolve(x,!0,this.lowLatency),D,W,()=>this._retryCallback()).withTimeout(ms).withRetryCount(xu).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,D)=>{_(y,W=>{if(!d())return;I=W;let Q=!!I.lowLatency;Q!==this.lowLatency&&b(Q);let X=0;for(let ce=0;ce<I.dur.length;++ce)X+=I.dur[ce];X>0&&(xi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(X/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,x(L(D))},()=>this._handleNetworkError())},nextChunk:F}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),xi(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:y=>{let{videoElement:I,logger:$}=this.params,G=S(e.jidxUrl),O,C,H,N,L=0,F,_,w,x=()=>{F&&(clearTimeout(F),F=void 0);let A=Math.max(Aw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=L+A,Ie=ie(),ke=Math.min(1e4,le-Ie);L=Ie;let pt=()=>{c||d()&&G.seek(()=>{d()&&(L=ie(),D(),x())})};ke>0?F=window.setTimeout(()=>{this.paused?x():pt()},ke):pt()},D=()=>{let A;for(;A=G.nextChunk(N);)N=A,kt(A);let le=G.nextChunk(H);if(le){if(H&&le.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?x():(T(),this._initPlayerWith(e));return}ce(le)}else x()},W=(A,le)=>{if(!d()||!this.sourceBuffer)return;let Ie,ke,pt,tr=ht=>{window.setTimeout(()=>{d()&&W(A,le)},ht)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),tr(100);else{let ht=ie(),Rt=I.currentTime;!this.paused&&I.buffered.length>1&&_===Rt&&ht-w>500&&($("Stall suspected; trying to fix"),this._fixupStall()),_!==Rt&&(_=Rt,w=ht);let rr=this._getBufferSizeSec();if(rr>30)$(`Buffered ${rr} seconds; delaying appendBuffer`),tr(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:ht,buf:rr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(qr){if(qr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),pt=this.sourceBuffer.buffered.length,pt!==0&&(Ie=this.sourceBuffer.buffered.start(0),ke=Rt,ke-Ie>4&&this.sourceBuffer.remove(Ie,ke-3)),tr(1e3);else throw qr}}},Q=()=>{C&&O&&($([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(H)]),W(C,function(){C=null,D()}))},X=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),ce=A=>{d()&&h(X(A),(le,Ie)=>{if(d()){if(Ie/=1e3,C=le,H=A,n=A.startTS,Ie){let ke=Math.min(10,A.dur/Ie);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}Q()}},()=>this._handleNetworkError())},kt=A=>{d()&&(xi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(X(A),!1)))},dt=A=>{d()&&(e.cachedHeader=A,W(A,()=>{O=!0,Q()}))};s=!0,G.seek(A=>{if(d()){if(L=ie(),!A){x();return}N=A,!Iw(y)||A.startTS>y?ce(A):(H=A,D())}},y),e.cachedHeader?dt(e.cachedHeader):p(e.headerUrl,dt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),fs(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,xi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return fs(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=ie();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&&Iu(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=ie();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ms).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;ve(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))},Ew))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as ww,filter as vb,fromEvent as kw,interval as Rw,isHigher as $w,isInvariantQuality as Lw,isLower as Mw,merge as Cw,Subject as yb,Subscription as Dw}from"@vkontakte/videoplayer-shared";var Pu=class{constructor(){this.onDroopedVideoFramesLimit$=new yb;this.subscription=new Dw;this.playing=!1;this.tracks=[];this.forceChecker$=new yb;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&&!Lw(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&&$w(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(kw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Rw(this.droppedFramesChecker.checkTime).pipe(vb(()=>this.playing),vb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(ww(this.droppedFramesChecker.checkTime)),r=Cw(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])=>Mw(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}},bs=Pu;import{map as Bw,Observable as Ow}from"@vkontakte/videoplayer-shared";import{fromEvent as Vw}from"@vkontakte/videoplayer-shared";var Ai=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var _w=(a,e)=>new Ow(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ai()))},k(k({},r),e));i.observe(a);let s=Vw(document,"visibilitychange").pipe(Bw(n=>!document.hidden||Ai())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Be=_w;var Yw=["paused","playing","ready"],Qw=["paused","playing","ready"],wi=class{constructor(e){this.subscription=new jw;this.videoState=new M("stopped");this.representations$=new wu([]);this.textTracksManager=new Ce;this.droppedFramesManager=new bs;this.maxSeekBackTime$=new wu(1/0);this.zeroTime$=new wu(void 0);this.liveOffset=new rt;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:Eb.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=yt(u.name))!=null?r:Ww(u.video),d=u.bitrate/1e3,p=k({},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),Au(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(Qw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Yw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(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(ae(this.params.source.url,u))}return;default:return Tb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Eb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Pb(this.videoState.stateChangeStarted$.pipe(gs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(gs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=fe(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(re(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=ge(this.video);this.subscription.add(this.representations$.pipe(gs(i=>i.map(({track:s})=>s)),xb(i=>!!i.length),Hw()).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(qw(),gs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Nw({zeroTime:this.zeroTime$.pipe(xb(Au)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ke(this.video,this.params.desiredState.isLooped,t)).add(be(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Me(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(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Gw(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 Tb(i.to)}},t)).add(Pb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Uw(["init"])).pipe(Fw(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),me(this.video)}createLiveDashPlayer(){let e=new Pi({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&&Au(t)?t:Tt(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;Ib(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;Ib(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(ae(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Ab=wi;var at=(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 vR,debounce as yR,ErrorCategory as tc,filter as Xg,filterChanged as rc,fromEvent as TR,isNonNullable as IR,map as Zg,merge as Us,observableFrom as ER,observeElementSize as xR,once as eS,Subscription as PR,ValueSubject as AR}from"@vkontakte/videoplayer-shared";var Ss=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}},Ar=class extends Ss{constructor(){super(),this.listeners||Ss.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)}},ki=class{constructor(){Object.defineProperty(this,"signal",{value:new Ar,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&&(ki.prototype[Symbol.toStringTag]="AbortController",Ar.prototype[Symbol.toStringTag]="AbortSignal");function vs(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 ku(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!vs({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 Ri=vs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),wb=Ri?ku({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,st=Ri?wb.fetch:window.fetch,LB=Ri?wb.Request:window.Request,nt=Ri?ki:window.AbortController,MB=Ri?Ar:window.AbortSignal;var Fb=Qe(vi(),1);var ot=()=>window.ManagedMediaSource||window.MediaSource,ys=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},kb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Rb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Rs,clientChecker as ks}from"@vkontakte/videoplayer-shared";var Oe=document.createElement("video"),Jw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Xw='video/mp4; codecs="hev1.1.6.L93.B0"',qb='video/webm; codecs="vp09.00.10.08"',Ub='video/webm; codecs="av01.0.00M.08"',Zw='audio/mp4; codecs="mp4a.40.2"',ek='audio/webm; codecs="opus"',$b,Lb,jt={mms:ys(),mse:kb(),hls:!!(($b=Oe.canPlayType)!=null&&$b.call(Oe,"application/x-mpegurl")||(Lb=Oe.canPlayType)!=null&&Lb.call(Oe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Mb,Cb,ye={mp4:!!((Mb=Oe.canPlayType)!=null&&Mb.call(Oe,"video/mp4")),webm:!!((Cb=Oe.canPlayType)!=null&&Cb.call(Oe,"video/webm")),cmaf:!0},Is,Db,Es,Bb,xs,Ob,Ps,Vb,As,_b,ws,Nb,Te={h264:!!((Db=(Is=ot())==null?void 0:Is.isTypeSupported)!=null&&Db.call(Is,Jw)),h265:!!((Bb=(Es=ot())==null?void 0:Es.isTypeSupported)!=null&&Bb.call(Es,Xw)),vp9:!!((Ob=(xs=ot())==null?void 0:xs.isTypeSupported)!=null&&Ob.call(xs,qb)),av1:!!((Vb=(Ps=ot())==null?void 0:Ps.isTypeSupported)!=null&&Vb.call(Ps,Ub)),aac:!!((_b=(As=ot())==null?void 0:As.isTypeSupported)!=null&&_b.call(As,Zw)),opus:!!((Nb=(ws=ot())==null?void 0:ws.isTypeSupported)!=null&&Nb.call(ws,ek))},wr=(Te.h264||Te.h265)&&Te.aac,Gt,tk=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(V(k({},a),{video:V(k({},a.video),{contentType:Ub})})),window.navigator.mediaCapabilities.decodingInfo(V(k({},a),{video:V(k({},a.video),{contentType:qb})}))]);Gt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{tk()}catch(a){console.error(a)}var kr=jt.hls&&ye.mp4,Hb=()=>Object.keys(Te).filter(a=>Te[a]),jb=(a,e=!1,t=!1)=>{let r=jt.mse||jt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ye.mp4&&wr;case"DASH_WEBM":return r&&ye.webm&&Te.vp9&&Te.opus;case"DASH_WEBM_AV1":return r&&ye.webm&&Te.av1&&Te.opus;case"DASH_STREAMS":return r&&(ye.mp4&&wr||ye.webm&&(Te.vp9||Te.av1)&&(Te.opus||Te.aac));case"DASH_LIVE":return jt.mse&&ye.mp4&&wr;case"DASH_LIVE_CMAF":return r&&ye.mp4&&wr&&ye.cmaf;case"DASH_ONDEMAND":return r&&ye.mp4&&wr;case"HLS":case"HLS_ONDEMAND":return kr||e&&jt.mse&&ye.mp4&&wr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return kr;case"MPEG":return ye.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return jt.webrtc&&jt.ws&&Te.h264&&(ye.mp4||ye.webm);default:return Rs(i)}})},Ts=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 Gt?Gt[t].smooth?[t,e]:Gt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Gt?Gt[t].powerEfficient?[t,e]:Gt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Rs(a)}return[e,t]},Gb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ts(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ks.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",...Ts(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ts(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ts(a),...i,"HLS","HLS_ONDEMAND"];default:Rs(e)}return kr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Wb=({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=ks.isMac&&ks.isSafari;if(ks.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:Rs(a)}else kr&&!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"]},Ru=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Yb=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,Fb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as $i}from"@vkontakte/videoplayer-shared";var Qb=a=>{if(!a)return{id:"EmptyResponse",category:$i.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:$i.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:$i.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:$i.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:$i.PARSER,message:"Response is valid XML, but parser failed"}};var Rr=(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 Xu,assertNonNullable as Zt,combine as Os,ErrorCategory as Et,filter as Vs,filterChanged as Gg,fromEvent as Vr,interval as Zu,isNonNullable as Wg,map as ec,merge as _r,Subject as Yg,Subscription as Qg,tap as lR,throttle as dR,clientChecker as pR,ValueSubject as oe,flattenObject as sa,getTraceSubscriptionMethod as hR}from"@vkontakte/videoplayer-shared";var Br=Qe(vi(),1);var rk=(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)},ik=a=>window.clearTimeout(a),zb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",$u=zb?rk:window.requestIdleCallback,YB=zb?ik:window.cancelIdleCallback;var _g=Qe(cs(),1);import{assertNever as ak,ErrorCategory as Kb,clientChecker as Lu,Subject as Jb}from"@vkontakte/videoplayer-shared";var sk=16,Xb=!1;try{Xb=Lu.isSafari&&!!Lu.macVersion&&Lu.macVersion<=sk}catch(a){console.error(a)}var Mu=class{constructor(e){this.bufferFull$=new Jb;this.error$=new Jb;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:Kb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return R(this,null,function*(){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()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let r;Xb&&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:Kb.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:ak(t)}}},Zb=Mu;var Cu=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 Dr,assertNonNullable as je,ErrorCategory as Kt,fromEvent as Wu,getExponentialDelay as Yu,isNonNullable as Qu,isNullable as Ve,once as rR,Subject as iR,Subscription as aR,ValueSubject as Zi}from"@vkontakte/videoplayer-shared";var j=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 $r=class extends j{};var Li=class extends j{};var Mi=class extends j{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 Ci=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var J=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Wt=class extends J{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 Oi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends J{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 Ni=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Fi=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var qi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends J{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 Hi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Wi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends J{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 Qi=class extends J{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 zi=class extends J{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 ok={ftyp:Mi,moov:Ci,moof:Di,mdat:Bi,sidx:Wt,trak:Oi,mdia:qi,mfhd:Gi,tkhd:Ui,traf:Wi,tfhd:Yi,tfdt:Qi,trun:zi,minf:Hi,sv3d:Vi,st3d:_i,prhd:Ni,proj:ji,equi:Fi,uuid:Li,unknown:$r},Yt=class a{constructor(e={}){this.options=k({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=ok[e];return r?new r(t,new a):new $r(t,new a)}};var Lr=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 ck=new TextDecoder("ascii"),lk=a=>ck.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",dk=a=>{let e=new Wt(a,new Yt),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})},pk=(a,e)=>{let r=new Yt().parse(a),i=new Lr(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)},hk=(a,e)=>{let r=new Yt().parse(a),s=new Lr(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},fk=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 Yt().parse(a),i=new Lr(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},eg={validateData:lk,parseInit:fk,getIndexRange:()=>{},parseSegments:dk,parseFeedableSegmentChunk:pk,getSegmentEndTime:hk};import{assertNonNullable as Bu,isNonNullable as ag,isNullable as bk}from"@vkontakte/videoplayer-shared";import{assertNever as mk}from"@vkontakte/videoplayer-shared";var tg={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"}},rg=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=Ki(a,t),i=r in tg,s=i?tg[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=Ki(u),d=c*Ye(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}},Ki=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*Ye(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*Ye(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*Ye(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},He=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ki(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:mk(e)}},Qt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=rg(r);if(!e(i))return;i.type==="master"&&Qt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},ig=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=rg(a);return Qt(i.value,({tag:s,type:n,value:o})=>(s===17143?e=He(o,n):s===17026?t=He(o,n):s===17029&&(r=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var sg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],gk=[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 Qt(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=He(f,h);c=Ki(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=He(f,h):p===17545?i=He(f,h):p===21420&&c===475249515?u=He(f,h):p===374648427?Qt(f,({tag:g,type:S,value:T})=>g===30321?(l=He(T,S)===1,!1):!0):s&&n&&sg.includes(p)&&(o=!0),!o}),Bu(e,"Failed to parse webm Segment start"),Bu(t,"Failed to parse webm Segment end"),Bu(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}}}},vk=a=>{if(bk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},yk=(a,e)=>{let t=!1,r=!1,i=o=>ag(o.time)&&ag(o.position),s=[],n;return Qt(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=He(c,u));break;case 183:break;case 241:n&&(n.position=He(c,u));break;default:t&&sg.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}}})},Tk=a=>{let e=0,t=!1;try{Qt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):gk.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},ng={validateData:ig,parseInit:Sk,getIndexRange:vk,parseSegments:yk,parseFeedableSegmentChunk:Tk};var Mr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return ng;case"mp4":return eg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Uu=Qe(kg(),1);var qu=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 $g,isNullable as Lg}from"@vkontakte/videoplayer-shared";var Rg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Mg=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},zt=(a,e)=>{let t=a;t=(0,Uu.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,Uu.default)(t,n,(o,u)=>Lg(s)?o:Lg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Dg=(a,e)=>{var y,I,$,G,O,C,H,N,L,F,_,w,x,D,W,Q,X,ce,kt,dt,A,le,Ie,ke,pt,tr,ht,Rt,rr,qr,Sc,vc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc,Cc,Dc,Bc,Oc,Vc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=($=(I=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:I.trim())!=null?$:"",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=Mg(h);else if(f){let de=Mg(f);$g(de)&&(p=de)}else g&&(p=parseInt(g,10));let S=0,T=(O=(G=s.getAttribute("profiles"))==null?void 0:G.split(","))!=null?O:[];for(let de of u){let GS=(C=de.getAttribute("id"))!=null?C:"id"+(S++).toString(10),Ur=(H=de.getAttribute("mimeType"))!=null?H:"",an=(N=de.getAttribute("codecs"))!=null?N:"",sn=(L=de.getAttribute("contentType"))!=null?L:Ur==null?void 0:Ur.split("/")[0],WS=(_=(F=de.getAttribute("profiles"))==null?void 0:F.split(","))!=null?_:[],YS=(w=de.getAttribute("lang"))!=null?w:void 0,QS=(W=(D=(x=de.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:D.trim())!=null?W:void 0,zS=de.querySelectorAll("Representation"),KS=de.querySelector("SegmentTemplate"),JS=(X=(Q=de.querySelector("Role"))==null?void 0:Q.getAttribute("value"))!=null?X:void 0,Hr=sn,ee={id:GS,language:YS,isDefault:JS==="main",label:QS,codecs:an,hdr:Hr==="video"&&qu(an),mime:Ur,representations:[]};for(let Z of zS){let XS=(ce=Z.getAttribute("lang"))!=null?ce:void 0,ZS=(kt=Z.getAttribute("label"))!=null?kt:void 0,ev=(le=(A=(dt=Z.querySelector("BaseURL"))==null?void 0:dt.textContent)==null?void 0:A.trim())!=null?le:"",nn=new URL(ev||o,e).toString(),ir=(Ie=Z.getAttribute("mimeType"))!=null?Ie:Ur,ya=(pt=(ke=Z.getAttribute("codecs"))!=null?ke:an)!=null?pt:"",on;if(sn==="text"){let $t=Z.getAttribute("id")||"",un=$t.includes("_auto");on={id:$t,isAuto:un,kind:"text",url:nn}}else{let $t=(ht=(tr=Z.getAttribute("contentType"))!=null?tr:ir==null?void 0:ir.split("/")[0])!=null?ht:sn,un=(rr=(Rt=de.getAttribute("profiles"))==null?void 0:Rt.split(","))!=null?rr:[],tv=parseInt((qr=Z.getAttribute("width"))!=null?qr:"",10),_c=parseInt((Sc=Z.getAttribute("height"))!=null?Sc:"",10),Nc=parseInt((vc=Z.getAttribute("bandwidth"))!=null?vc:"",10)/1e3,Fc=(yc=Z.getAttribute("frameRate"))!=null?yc:"",rv=(Tc=Z.getAttribute("quality"))!=null?Tc:void 0,iv=Fc?Rg(Fc):void 0,av=(Ic=Z.getAttribute("id"))!=null?Ic:"id"+(S++).toString(10),sv=$t==="video"?`${_c}p`:$t==="audio"?`${Nc}Kbps`:ya,nv=`${av}@${sv}`,ov=[...T,...WS,...un],cn,uv=Z.querySelector("SegmentBase"),Lt=(Ec=Z.querySelector("SegmentTemplate"))!=null?Ec:KS;if(uv){let Mt=(Pc=(xc=Z.querySelector("SegmentBase Initialization"))==null?void 0:xc.getAttribute("range"))!=null?Pc:"",[Ct,dn]=Mt.split("-").map(ar=>parseInt(ar,10)),ft={from:Ct,to:dn},jr=(Ac=Z.querySelector("SegmentBase"))==null?void 0:Ac.getAttribute("indexRange"),[pn,Ta]=jr?jr.split("-").map(ar=>parseInt(ar,10)):[],Gr=jr?{from:pn,to:Ta}:void 0;cn={type:"byteRange",url:nn,initRange:ft,indexRange:Gr}}else if(Lt){let Mt={representationId:(wc=Z.getAttribute("id"))!=null?wc:void 0,bandwidth:(kc=Z.getAttribute("bandwidth"))!=null?kc:void 0},Ct=parseInt((Rc=Lt.getAttribute("timescale"))!=null?Rc:"",10),dn=($c=Lt.getAttribute("initialization"))!=null?$c:"",ft=Lt.getAttribute("media"),jr=(Mc=parseInt((Lc=Lt.getAttribute("startNumber"))!=null?Lc:"",10))!=null?Mc:1,pn=zt(dn,Mt);if(!ft)throw new ReferenceError("No media attribute in SegmentTemplate");let Ta=(Cc=Lt.querySelectorAll("SegmentTimeline S"))!=null?Cc:[],Gr=[],ar=0,hn="",fn=0;if(Ta.length){let Ia=jr,_e=0;for(let sr of Ta){let We=parseInt((Dc=sr.getAttribute("d"))!=null?Dc:"",10),Dt=parseInt((Bc=sr.getAttribute("r"))!=null?Bc:"",10)||0,Ea=parseInt((Oc=sr.getAttribute("t"))!=null?Oc:"",10);_e=Number.isFinite(Ea)?Ea:_e;let mn=We/Ct*1e3,bn=_e/Ct*1e3;for(let xa=0;xa<Dt+1;xa++){let lv=zt(ft,V(k({},Mt),{segmentNumber:Ia.toString(10),segmentTime:(_e+xa*We).toString(10)})),qc=(bn!=null?bn:0)+xa*mn,dv=qc+mn;Ia++,Gr.push({time:{from:qc,to:dv},url:lv})}_e+=(Dt+1)*We,ar+=(Dt+1)*mn}fn=_e/Ct*1e3,hn=zt(ft,V(k({},Mt),{segmentNumber:Ia.toString(10),segmentTime:_e.toString(10)}))}else if($g(p)){let _e=parseInt((Vc=Lt.getAttribute("duration"))!=null?Vc:"",10)/Ct*1e3,sr=Math.ceil(p/_e),We=0;for(let Dt=1;Dt<sr;Dt++){let Ea=zt(ft,V(k({},Mt),{segmentNumber:Dt.toString(10),segmentTime:We.toString(10)}));Gr.push({time:{from:We,to:We+_e},url:Ea}),We+=_e}fn=We,hn=zt(ft,V(k({},Mt),{segmentNumber:sr.toString(10),segmentTime:We.toString(10)}))}let cv={time:{from:fn,to:1/0},url:hn};cn={type:"template",baseUrl:nn,segmentTemplateUrl:ft,initUrl:pn,totalSegmentsDurationMs:ar,segments:Gr,nextSegmentBeyondManifest:cv,timescale:Ct}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!$t||!ir)continue;let ln={video:"video",audio:"audio",text:"text"}[$t];if(!ln)continue;Hr||(Hr=ln),on={id:nv,kind:ln,segmentReference:cn,profiles:ov,duration:p,bitrate:Nc,mime:ir,codecs:ya,width:tv,height:_c,fps:iv,quality:rv}}ee.language||(ee.language=XS),ee.label||(ee.label=ZS),ee.mime||(ee.mime=ir),ee.codecs||(ee.codecs=ya),ee.hdr||(ee.hdr=Hr==="video"&&qu(ya)),ee.representations.push(on)}Hr&&i[Hr].push(ee)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Ji=Qe(vi(),1);import{videoSizeToQuality as tR}from"@vkontakte/videoplayer-shared";var Bg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?yt(s):void 0)!=null?o:tR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Og=({id:a,bitrate:e})=>({id:a,bitrate:e}),$s=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Ji.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Ji.default)(t,-1)},Vg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ju=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ji.default)(r.split("."),0),isDefault:i}),Gu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ji.default)(i.split("."),0)}),Ls=a=>"url"in a,ut=a=>a.type==="template",Xi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ea=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Zi(0);this.onLastSegment$=new Zi(!1);this.fullyBuffered$=new Zi(!1);this.playingRepresentation$=new Zi(void 0);this.playingRepresentationInit$=new Zi(void 0);this.error$=new iR;this.gaps=[];this.subscription=new aR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new nt;this.destroyAbortController=new nt;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=Dr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Zb(this.sourceBuffer),this.subscription.add(Wu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Kt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Kt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Wu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Kt.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,Cu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=at(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);je(r,"No init buffer for starting representation"),je(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=Dr(this.destroyAbortController.signal,function(e,t=!1){return te(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);je(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ve(s)||Ve(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),je(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();Qu(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield new vn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Dr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){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||!ut(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);je(i);let s=this.segments.get(r);je(s,"No segments for starting representation");let n=this.initData.get(r);if(je(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 nt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if(Ve(e)||Ve(this.downloadingRepresentationId)||Ve(this.playingRepresentationId)||Ve(this.sourceBuffer)||!Ve(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(je(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=at(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)&&Cu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=at(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,Br.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&&at(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Br.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;Qu(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||!ut(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>V(k({},p),{status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,Br.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;je(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(!ut(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=zt(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,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&!(Rr(this.sourceBuffer.buffered,p)&&Rr(this.sourceBuffer.buffered,h)))&&g&&T});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}loadSegments(e,t,r="auto"){return R(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return R(this,null,function*(){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&&(yield Dr(o,function(){return te(this,null,function*(){let l=Yu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=yield 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=Mr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?yield Promise.all(c):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xi(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return R(this,null,function*(){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&&(yield Dr(n,function(){return te(this,null,function*(){let u=Yu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Wu(window,"online").pipe(rR()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Xi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ut(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Br.default)(e,0).byte.from,to:(0,Br.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:Kt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ut(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:Kt.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)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){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){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Mr(o.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(c.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.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,S=b<i,T=g<=i;if(d.status==="downloading"&&S&&T){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+b,h),y=this.getCurrentPosition();Qu(y)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-y,this.bufferAccumulation.accumulated.push({segmentView:v,segmentProgress:l}),this.activeSegments.delete(l));let I=({segmentView:$,segmentProgress:G})=>this.sourceBufferTaskQueue.append($,s).then(O=>O&&!s.aborted?this.onSegmentFullyAppended(G,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(I),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||Ve(y))&&(I({segmentView:v,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&!T&&(l.loadedBytes=Math.min(h,i-b),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),y=l.loadedBytes===h?v:Mr(o.mime).parseFeedableSegmentChunk(v);y!=null&&y.byteLength&&(d.status="partially_fed",l.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(I=>{if(s.aborted)n();else if(I)l.fedBytes+=y.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let c of this.activeSegments){let{segment:l}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-r,p=l.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(f){if(l.status==="downloading"&&b){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(g,s))&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(c.loadedBytes=Math.min(h,i-d),c.loadedBytes>c.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),S=c.loadedBytes===h?g:Mr(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",c.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(c.fedBytes+=S.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,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",Ls(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");je(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=$u(()=>(0,_g.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return R(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Dr(this.destroyAbortController.signal,function(){return te(this,null,function*(){let o=Yu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mr(e.mime),i)).then(o=>R(this,null,function*(){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&&ut(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:Kt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return R(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Ve(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(k({},u.time)),i=n(i);let c=Ls(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?(yield Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1})}pruneBufferOld(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Ve(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=Ls(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=$u(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Kt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ve(this.sourceBuffer)||Ve(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 ta=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ng=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 ra,assertNever as Fg,fromEvent as qg,merge as sR,now as ia,Subscription as nR,ValueSubject as zu,flattenObject as Or}from"@vkontakte/videoplayer-shared";var Ms=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new zu(void 0);this.lastConnectionReused$=new zu(void 0);this.lastRequestFirstBytes$=new zu(void 0);this.abortAllController=new nt;this.subscription=new nR;this.fetchManifest=ra(this.abortAllController.signal,function(e){return te(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ta(r));let i=yield st(r,{signal:this.abortAllController.signal}).catch(aa);return i?(t.log("success",Or({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Or({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=ra(this.abortAllController.signal,function(c){return te(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,F;let l=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),l=_.toString();break}default:Fg(t)}this.requestQuic&&(l=ta(l));let h=this.abortAllController.signal,f;if(n){let _=new nt;if(f=sR(qg(this.abortAllController.signal,"abort"),qg(n,"abort")).subscribe(()=>{try{_.abort()}catch(w){aa(w)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(w){aa(w)}h=_.signal}let b=ia();p.log("startRequest",Or({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield st(l,{priority:s,headers:d,signal:h}).catch(aa),S=ia();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(S-b),!g.ok||!g.body){f==null||f.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:_}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let _=ia(),w={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",Or(w)),p.end(),g.arrayBuffer()}let[T,v]=g.body.tee(),y=T.getReader();o&&((F=this.throughputEstimator)==null||F.trackStream(v,u));let I=0,$=new Uint8Array(0),G=!1,O=_=>{f==null||f.unsubscribe(),G=!0,aa(_)},C=ra(h,function(x){return te(this,arguments,function*({done:_,value:w}){if(I===0&&this.lastRequestFirstBytes$.next(ia()-b),h.aborted){f==null||f.unsubscribe();return}if(!_&&w){let D=new Uint8Array($.length+w.length);D.set($),D.set(w,$.length),$=D,I+=w.byteLength,i==null||i(new DataView($.buffer),I),yield y==null?void 0:y.read().then(C,O)}})}.bind(this));yield y==null?void 0:y.read().then(C,O),f==null||f.unsubscribe();let H=ia(),N={failed:G,requestStartedAt:b,requestEndedAt:H,duration:H-b};return G?(p.error("endRequest",Or(N)),p.end(),null):(p.log("endRequest",Or(N)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=ra(this.abortAllController.signal,function(e,t,r){return te(this,null,function*(){var S;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=(S=e.indexRange)!=null?S: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 T=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!T)return null;b=new DataView(T)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=ra(this.abortAllController.signal,function(e,t){return te(this,null,function*(){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=>V(k({},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}=Ng(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return R(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Fg(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},aa=a=>{if(!Xi(a))throw a};var Jt=(a,e,t)=>t*e+(1-t)*a,Ku=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Ug=(a,e,t,r)=>{let i=0,s=t,n=Ku(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 oR,ValueSubject as Hg}from"@vkontakte/videoplayer-shared";var It=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 Hg(e.initial),this.debounced$=new Hg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ne(`raw_${t}`),this.smoothedSeries$=new ne(`smoothed_${t}`),this.reportedSeries$=new ne(`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+=Ye(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)&&(oR(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 Cs=class extends It{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Jt(this.slow,e,this.params.emaAlphaSlow),this.fast=Jt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ds=class extends It{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ku(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Jt(this.emaSmoothed,e,this.params.emaAlpha);let r=Ug(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Bs=class extends It{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?Jt(this.smoothed,t,this.params.emaAlpha):t}};var Xt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Cs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ds({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 Bs(k({initial:e,label:"liveEdgeDelay"},t))}};var Ju=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var zg=["timeupdate","progress","play","seeked","stalled","waiting"];var _s=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Qg;this.representationSubscription=new Qg;this.state$=new M("none");this.currentVideoRepresentation$=new oe(void 0);this.currentVideoRepresentationInit$=new oe(void 0);this.currentAudioRepresentation$=new oe(void 0);this.currentVideoSegmentLength$=new oe(0);this.currentAudioSegmentLength$=new oe(0);this.error$=new Yg;this.lastConnectionType$=new oe(void 0);this.lastConnectionReused$=new oe(void 0);this.lastRequestFirstBytes$=new oe(void 0);this.isLive$=new oe(!1);this.liveDuration$=new oe(0);this.liveAvailabilityStartTime$=new oe(void 0);this.bufferLength$=new oe(0);this.liveLoadBufferLength$=new oe(0);this.livePositionFromPlayer$=new oe(0);this.timeInWaiting=0;this.isActiveLowLatency$=new oe(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Yg;this.gapWatchdogActive=!1;this.destroyController=new nt;this.initManifest=Xu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:Et.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Xu(this.destroyController.signal,function(){return te(this,null,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:Et.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=Dg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Qb(e))!=null?n:{id:"ManifestParsing",category:Et.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=ot())==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=Yb(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);pR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=V(k({},t),{streams:i});return this.tracer.log("updateManifestEnd",sa(s)),s})}.bind(this));this.initRepresentations=Xu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",sa({initialVideo:e,initialAudio:t,sourceHls:r})),Zt(this.manifest),Zt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Vr(p,"error").pipe(Vs(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Et.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Rb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ys())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 ea("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Wg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new ea("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(Zu(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=cu(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(_r(...zg.filter(p=>p!=="waiting").map(p=>Vr(this.element,p))).pipe(ec(p=>this.element?at(this.element.buffered,this.element.currentTime*1e3):0),Gg(),Vs(p=>!!p),lR(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Gg()).subscribe(h=>Ju(this.element,1))),this.representationSubscription.add(Os({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Vs(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Os({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,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-b,v=1;Math.abs(T)>g&&(v=1+Math.sign(T)*S),Ju(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let S=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(v=>{var y,I;return(I=(y=v.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?I:S}))-S}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Os({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(dR(1e3)).subscribe(b=>R(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(Zt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=cu(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(h)?h:f,G=this.isActiveLowLatency$.getValue(),O=T<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(G&&O);let C="none";if(G?C="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&O?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),C="active_low_latency"):S!==0&&$<v?C="live_forward_buffering":$<v+I&&(C="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),C==="live_forward_buffering"||C==="live_with_target_offset"){let H=p-(v+y),N=this.normolizeLiveOffset(Math.trunc(S+H/g)),L=Math.abs(N-S),F;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?F=S:N>0&&L>this.tuning.dashCmafLive.offsetCalculationError?F=N:F=0,this.manifestUrlString=ae(this.manifestUrlString,F,2)}C!=="none"&&C!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=_r(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ec(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=_r(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ec(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(_r(this.forceEnded$,Os({allBuffersFull:u,someBufferEnded:c}).pipe(Vs(({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:Et.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(_r(...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),ut(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&Wg(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=Zu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:Et.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 Ms({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Xt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,k({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,i,s,n;Zt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){Zt(this.element),this.state$.setState("running"),this.subscription.add(_r(...zg.map(e=>Vr(this.element,e)),Vr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Et.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Vr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Vr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Rr(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=V(k({},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=V(k({},s),{position:u})}this.tracer.log("stallIntervalCallback",sa(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Zu(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Et.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return R(this,null,function*(){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;Zt(this.element),Zt(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),Rr(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",sa({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=hR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield 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=V(k({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",sa(t)))}}};var Ns=class{constructor(e,t){this.fov=e,this.orientation=t}};var Fs=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/Ye(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=k({},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*Ye(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 Kg=`attribute vec2 a_vertex;
58
+ `}),h&&fb(i,u,h,o)};var re=a=>new URL(a).hostname;import{assertNever as Tb,assertNonNullable as Ib,combine as Nw,debounce as Fw,ErrorCategory as Eb,filter as xb,filterChanged as qw,isNonNullable as Au,map as gs,merge as Pb,observableFrom as Uw,once as Hw,Subscription as jw,ValueSubject as wu,videoQualityToHeight as Gw,videoSizeToQuality as Ww}from"@vkontakte/videoplayer-shared";var bb=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"))},ve=a=>R(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!bb(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return bb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as fs,isNullable as Iw,assertNonNullable as xi}from"@vkontakte/videoplayer-shared";import{isNonNullable as gb,assertNonNullable as hs,now as yw}from"@vkontakte/videoplayer-shared";function ie(){return yw()}function Iu(a){return ie()-a}function Eu(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 Sb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Pr(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;hs(l);let L=Iu(l),F;if(L<b){F=b-L,setTimeout(g,F);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},S=L=>(s=L,N),T=L=>(d=L,N),v=()=>(h="json",N),y=()=>{if(!u){if(--c>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=L=>(p=L,N),$=()=>{l=ie(),n=new i,n.open("get",a);let L=0,F,_=0,w=()=>(hs(l),Math.max(l,Math.max(F||0,_||0)));if(s&&n.addEventListener("progress",x=>{let D=ie();s.updateChunk&&x.loaded>L&&(s.updateChunk(w(),x.loaded-L),L=x.loaded,F=D)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;hs(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let D=n.response.byteLength-L;D&&s.updateChunk&&s.updateChunk(w(),D)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{hs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(_=ie(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),N},N={withBitrateReporting:S,withParallel:I,withJSONResponse:v,withRetryCount:L=>(c=L,N),withRetryInterval:(L,F)=>(gb(L)&&(b=L),gb(F)&&(f=F),N),withTimeout:L=>(o=L,N),withFinally:T,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return N}var Ii=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 Ei=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=ie(),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=ie()-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=Pr(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=ie()}_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=ie();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 ms=1e4,xu=3;var Ew=6e4,xw=10,Pw=1,Aw=500,Pi=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 Ii(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Eu(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=Eu(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||fs(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=()=>{Sb(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 Ei(xu,ms,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 y=s&&(!l||l===this.rep);return y||t("Not running!"),y},p=(y,I,$)=>{u&&u.abort(),u=Pr(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withTimeout(ms).withBitrateReporting(this.bitrateSwitcher).withRetryCount(xu).withFinally(()=>{u=null}).send()},h=(y,I,$)=>{xi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let I=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${I}=>${y}`),r.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=ie()-1e4,G=0;for(let C=0;C<this.bufferStates.length;C++){let H=this.bufferStates[C];y=Math.min(y,H.buf),H.ts<$&&G++}this.bufferStates.splice(0,G),t(`update playback rate; minBuffer=${y} drop=${G} jitter=${this.sourceJitter}`);let O=y-Pw;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?f(1.15):O>1?f(1.1):O>.3?f(1.05):f(1)}},S=y=>{let I,$=()=>I&&I.start?I.start.length:0,G=x=>I.start[x]/1e3,O=x=>I.dur[x]/1e3,C=x=>I.fragIndex+x,H=(x,D)=>({chunkIdx:C(x),startTS:G(x),dur:O(x),discontinuity:D}),N=()=>{let x=0;if(I&&I.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=D;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let X=I.dur.length-1;for(;X>=0&&(Q-=I.dur[X],!(Q<=0));--X);x=Math.min(X,I.dur.length-1-W),x=Math.max(x,0)}return H(x,!0)},L=x=>{let D=$();if(!(D<=0)){if(fs(x)){for(let W=0;W<D;W++)if(G(W)>x)return H(W)}return N()}},F=x=>{let D=$(),W=x?x.chunkIdx+1:0,Q=W-I.fragIndex;if(!(D<=0)){if(!x||Q<0||Q-D>xw)return t(`Resync: offset=${Q} bChunks=${D} chunk=`+JSON.stringify(x)),N();if(!(Q>=D))return H(W-I.fragIndex,!1)}},_=(x,D,W)=>{c&&c.abort(),c=Pr(this.urlResolver.resolve(x,!0,this.lowLatency),D,W,()=>this._retryCallback()).withTimeout(ms).withRetryCount(xu).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(x,D)=>{_(y,W=>{if(!d())return;I=W;let Q=!!I.lowLatency;Q!==this.lowLatency&&b(Q);let X=0;for(let ce=0;ce<I.dur.length;++ce)X+=I.dur[ce];X>0&&(xi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(X/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,x(L(D))},()=>this._handleNetworkError())},nextChunk:F}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),xi(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:y=>{let{videoElement:I,logger:$}=this.params,G=S(e.jidxUrl),O,C,H,N,L=0,F,_,w,x=()=>{F&&(clearTimeout(F),F=void 0);let A=Math.max(Aw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=L+A,Ie=ie(),ke=Math.min(1e4,le-Ie);L=Ie;let pt=()=>{c||d()&&G.seek(()=>{d()&&(L=ie(),D(),x())})};ke>0?F=window.setTimeout(()=>{this.paused?x():pt()},ke):pt()},D=()=>{let A;for(;A=G.nextChunk(N);)N=A,kt(A);let le=G.nextChunk(H);if(le){if(H&&le.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?x():(T(),this._initPlayerWith(e));return}ce(le)}else x()},W=(A,le)=>{if(!d()||!this.sourceBuffer)return;let Ie,ke,pt,tr=ht=>{window.setTimeout(()=>{d()&&W(A,le)},ht)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),tr(100);else{let ht=ie(),Rt=I.currentTime;!this.paused&&I.buffered.length>1&&_===Rt&&ht-w>500&&($("Stall suspected; trying to fix"),this._fixupStall()),_!==Rt&&(_=Rt,w=ht);let rr=this._getBufferSizeSec();if(rr>30)$(`Buffered ${rr} seconds; delaying appendBuffer`),tr(2e3);else try{this.sourceBuffer.appendBuffer(A),this.videoPlayStarted?(this.bufferStates.push({ts:ht,buf:rr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(qr){if(qr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),pt=this.sourceBuffer.buffered.length,pt!==0&&(Ie=this.sourceBuffer.buffered.start(0),ke=Rt,ke-Ie>4&&this.sourceBuffer.remove(Ie,ke-3)),tr(1e3);else throw qr}}},Q=()=>{C&&O&&($([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(H)]),W(C,function(){C=null,D()}))},X=A=>e.fragUrlTemplate.replace("%%id%%",A.chunkIdx),ce=A=>{d()&&h(X(A),(le,Ie)=>{if(d()){if(Ie/=1e3,C=le,H=A,n=A.startTS,Ie){let ke=Math.min(10,A.dur/Ie);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ke:ke}Q()}},()=>this._handleNetworkError())},kt=A=>{d()&&(xi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(X(A),!1)))},dt=A=>{d()&&(e.cachedHeader=A,W(A,()=>{O=!0,Q()}))};s=!0,G.seek(A=>{if(d()){if(L=ie(),!A){x();return}N=A,!Iw(y)||A.startTS>y?ce(A):(H=A,D())}},y),e.cachedHeader?dt(e.cachedHeader):p(e.headerUrl,dt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),fs(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,xi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return fs(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=ie();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&&Iu(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=ie();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Pr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ms).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;ve(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))},Ew))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as ww,filter as vb,fromEvent as kw,interval as Rw,isHigher as $w,isInvariantQuality as Lw,isLower as Mw,merge as Cw,Subject as yb,Subscription as Dw}from"@vkontakte/videoplayer-shared";var Pu=class{constructor(){this.onDroopedVideoFramesLimit$=new yb;this.subscription=new Dw;this.playing=!1;this.tracks=[];this.forceChecker$=new yb;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&&!Lw(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&&$w(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(kw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Rw(this.droppedFramesChecker.checkTime).pipe(vb(()=>this.playing),vb(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(ww(this.droppedFramesChecker.checkTime)),r=Cw(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])=>Mw(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}},bs=Pu;import{map as Bw,Observable as Ow}from"@vkontakte/videoplayer-shared";import{fromEvent as Vw}from"@vkontakte/videoplayer-shared";var Ai=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var _w=(a,e)=>new Ow(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ai()))},k(k({},r),e));i.observe(a);let s=Vw(document,"visibilitychange").pipe(Bw(n=>!document.hidden||Ai())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Be=_w;var Yw=["paused","playing","ready"],Qw=["paused","playing","ready"],wi=class{constructor(e){this.subscription=new jw;this.videoState=new M("stopped");this.representations$=new wu([]);this.textTracksManager=new Ce;this.droppedFramesManager=new bs;this.maxSeekBackTime$=new wu(1/0);this.zeroTime$=new wu(void 0);this.liveOffset=new rt;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:Eb.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=yt(u.name))!=null?r:Ww(u.video),d=u.bitrate/1e3,p=k({},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),Au(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(Qw.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Yw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(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(ae(this.params.source.url,u))}return;default:return Tb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Eb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Pb(this.videoState.stateChangeStarted$.pipe(gs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(gs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=fe(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(re(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=ge(this.video);this.subscription.add(this.representations$.pipe(gs(i=>i.map(({track:s})=>s)),xb(i=>!!i.length),Hw()).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(qw(),gs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Nw({zeroTime:this.zeroTime$.pipe(xb(Au)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ke(this.video,this.params.desiredState.isLooped,t)).add(be(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Me(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(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&Gw(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 Tb(i.to)}},t)).add(Pb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Uw(["init"])).pipe(Fw(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),me(this.video)}createLiveDashPlayer(){let e=new Pi({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&&Au(t)?t:Tt(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;Ib(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;Ib(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(ae(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Ab=wi;var at=(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 vR,debounce as yR,ErrorCategory as tc,filter as Xg,filterChanged as rc,fromEvent as TR,isNonNullable as IR,map as Zg,merge as Us,observableFrom as ER,observeElementSize as xR,once as eS,Subscription as PR,ValueSubject as AR}from"@vkontakte/videoplayer-shared";var Ss=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}},Ar=class extends Ss{constructor(){super(),this.listeners||Ss.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)}},ki=class{constructor(){Object.defineProperty(this,"signal",{value:new Ar,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&&(ki.prototype[Symbol.toStringTag]="AbortController",Ar.prototype[Symbol.toStringTag]="AbortSignal");function vs(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 ku(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!vs({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 Ri=vs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),wb=Ri?ku({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,st=Ri?wb.fetch:window.fetch,LB=Ri?wb.Request:window.Request,nt=Ri?ki:window.AbortController,MB=Ri?Ar:window.AbortSignal;var Fb=Qe(vi(),1);var ot=()=>window.ManagedMediaSource||window.MediaSource,ys=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},kb=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Rb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Rs,clientChecker as ks}from"@vkontakte/videoplayer-shared";var Oe=document.createElement("video"),Jw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Xw='video/mp4; codecs="hev1.1.6.L93.B0"',qb='video/webm; codecs="vp09.00.10.08"',Ub='video/webm; codecs="av01.0.00M.08"',Zw='audio/mp4; codecs="mp4a.40.2"',ek='audio/webm; codecs="opus"',$b,Lb,jt={mms:ys(),mse:kb(),hls:!!(($b=Oe.canPlayType)!=null&&$b.call(Oe,"application/x-mpegurl")||(Lb=Oe.canPlayType)!=null&&Lb.call(Oe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Mb,Cb,ye={mp4:!!((Mb=Oe.canPlayType)!=null&&Mb.call(Oe,"video/mp4")),webm:!!((Cb=Oe.canPlayType)!=null&&Cb.call(Oe,"video/webm")),cmaf:!0},Is,Db,Es,Bb,xs,Ob,Ps,Vb,As,_b,ws,Nb,Te={h264:!!((Db=(Is=ot())==null?void 0:Is.isTypeSupported)!=null&&Db.call(Is,Jw)),h265:!!((Bb=(Es=ot())==null?void 0:Es.isTypeSupported)!=null&&Bb.call(Es,Xw)),vp9:!!((Ob=(xs=ot())==null?void 0:xs.isTypeSupported)!=null&&Ob.call(xs,qb)),av1:!!((Vb=(Ps=ot())==null?void 0:Ps.isTypeSupported)!=null&&Vb.call(Ps,Ub)),aac:!!((_b=(As=ot())==null?void 0:As.isTypeSupported)!=null&&_b.call(As,Zw)),opus:!!((Nb=(ws=ot())==null?void 0:ws.isTypeSupported)!=null&&Nb.call(ws,ek))},wr=(Te.h264||Te.h265)&&Te.aac,Gt,tk=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(V(k({},a),{video:V(k({},a.video),{contentType:Ub})})),window.navigator.mediaCapabilities.decodingInfo(V(k({},a),{video:V(k({},a.video),{contentType:qb})}))]);Gt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{tk()}catch(a){console.error(a)}var kr=jt.hls&&ye.mp4,Hb=()=>Object.keys(Te).filter(a=>Te[a]),jb=(a,e=!1,t=!1)=>{let r=jt.mse||jt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&ye.mp4&&wr;case"DASH_WEBM":return r&&ye.webm&&Te.vp9&&Te.opus;case"DASH_WEBM_AV1":return r&&ye.webm&&Te.av1&&Te.opus;case"DASH_STREAMS":return r&&(ye.mp4&&wr||ye.webm&&(Te.vp9||Te.av1)&&(Te.opus||Te.aac));case"DASH_LIVE":return jt.mse&&ye.mp4&&wr;case"DASH_LIVE_CMAF":return r&&ye.mp4&&wr&&ye.cmaf;case"DASH_ONDEMAND":return r&&ye.mp4&&wr;case"HLS":case"HLS_ONDEMAND":return kr||e&&jt.mse&&ye.mp4&&wr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return kr;case"MPEG":return ye.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return jt.webrtc&&jt.ws&&Te.h264&&(ye.mp4||ye.webm);default:return Rs(i)}})},Ts=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 Gt?Gt[t].smooth?[t,e]:Gt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Gt?Gt[t].powerEfficient?[t,e]:Gt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Rs(a)}return[e,t]},Gb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ts(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ks.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",...Ts(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ts(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ts(a),...i,"HLS","HLS_ONDEMAND"];default:Rs(e)}return kr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Wb=({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=ks.isMac&&ks.isSafari;if(ks.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:Rs(a)}else kr&&!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"]},Ru=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Yb=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,Fb.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};import{ErrorCategory as $i}from"@vkontakte/videoplayer-shared";var Qb=a=>{if(!a)return{id:"EmptyResponse",category:$i.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:$i.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:$i.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:$i.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:$i.PARSER,message:"Response is valid XML, but parser failed"}};var Rr=(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 Xu,assertNonNullable as Zt,combine as Os,ErrorCategory as Et,filter as Vs,filterChanged as Gg,fromEvent as Vr,interval as Zu,isNonNullable as Wg,map as ec,merge as _r,Subject as Yg,Subscription as Qg,tap as lR,throttle as dR,clientChecker as pR,ValueSubject as oe,flattenObject as sa,getTraceSubscriptionMethod as hR}from"@vkontakte/videoplayer-shared";var Br=Qe(vi(),1);var rk=(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)},ik=a=>window.clearTimeout(a),zb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",$u=zb?rk:window.requestIdleCallback,YB=zb?ik:window.cancelIdleCallback;var _g=Qe(cs(),1);import{assertNever as ak,ErrorCategory as Kb,clientChecker as Lu,Subject as Jb}from"@vkontakte/videoplayer-shared";var sk=16,Xb=!1;try{Xb=Lu.isSafari&&!!Lu.macVersion&&Lu.macVersion<=sk}catch(a){console.error(a)}var Mu=class{constructor(e){this.bufferFull$=new Jb;this.error$=new Jb;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:Kb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return R(this,null,function*(){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()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let r;Xb&&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:Kb.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:ak(t)}}},Zb=Mu;var Cu=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 Dr,assertNonNullable as Ve,ErrorCategory as Kt,fromEvent as Wu,getExponentialDelay as Yu,isNonNullable as Qu,isNullable as _e,once as rR,Subject as iR,Subscription as aR,ValueSubject as Zi}from"@vkontakte/videoplayer-shared";var j=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 $r=class extends j{};var Li=class extends j{};var Mi=class extends j{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 Ci=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var J=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Wt=class extends J{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 Oi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends J{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 Ni=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Fi=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var qi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends J{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 Hi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Wi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends J{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 Qi=class extends J{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 zi=class extends J{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 ok={ftyp:Mi,moov:Ci,moof:Di,mdat:Bi,sidx:Wt,trak:Oi,mdia:qi,mfhd:Gi,tkhd:Ui,traf:Wi,tfhd:Yi,tfdt:Qi,trun:zi,minf:Hi,sv3d:Vi,st3d:_i,prhd:Ni,proj:ji,equi:Fi,uuid:Li,unknown:$r},Yt=class a{constructor(e={}){this.options=k({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=ok[e];return r?new r(t,new a):new $r(t,new a)}};var Lr=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 ck=new TextDecoder("ascii"),lk=a=>ck.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",dk=a=>{let e=new Wt(a,new Yt),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})},pk=(a,e)=>{let r=new Yt().parse(a),i=new Lr(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)},hk=(a,e)=>{let r=new Yt().parse(a),s=new Lr(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},fk=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 Yt().parse(a),i=new Lr(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},eg={validateData:lk,parseInit:fk,getIndexRange:()=>{},parseSegments:dk,parseFeedableSegmentChunk:pk,getSegmentEndTime:hk};import{assertNonNullable as Bu,isNonNullable as ag,isNullable as bk}from"@vkontakte/videoplayer-shared";import{assertNever as mk}from"@vkontakte/videoplayer-shared";var tg={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"}},rg=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=Ki(a,t),i=r in tg,s=i?tg[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=Ki(u),d=c*Ye(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}},Ki=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*Ye(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*Ye(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*Ye(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},je=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ki(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:mk(e)}},Qt=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=rg(r);if(!e(i))return;i.type==="master"&&Qt(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},ig=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=rg(a);return Qt(i.value,({tag:s,type:n,value:o})=>(s===17143?e=je(o,n):s===17026?t=je(o,n):s===17029&&(r=je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var sg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],gk=[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 Qt(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=je(f,h);c=Ki(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=je(f,h):p===17545?i=je(f,h):p===21420&&c===475249515?u=je(f,h):p===374648427?Qt(f,({tag:g,type:S,value:T})=>g===30321?(l=je(T,S)===1,!1):!0):s&&n&&sg.includes(p)&&(o=!0),!o}),Bu(e,"Failed to parse webm Segment start"),Bu(t,"Failed to parse webm Segment end"),Bu(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}}}},vk=a=>{if(bk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},yk=(a,e)=>{let t=!1,r=!1,i=o=>ag(o.time)&&ag(o.position),s=[],n;return Qt(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=je(c,u));break;case 183:break;case 241:n&&(n.position=je(c,u));break;default:t&&sg.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}}})},Tk=a=>{let e=0,t=!1;try{Qt(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):gk.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},ng={validateData:ig,parseInit:Sk,getIndexRange:vk,parseSegments:yk,parseFeedableSegmentChunk:Tk};var Mr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return ng;case"mp4":return eg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Uu=Qe(kg(),1);var qu=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 $g,isNullable as Lg}from"@vkontakte/videoplayer-shared";var Rg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Mg=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},zt=(a,e)=>{let t=a;t=(0,Uu.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,Uu.default)(t,n,(o,u)=>Lg(s)?o:Lg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Dg=(a,e)=>{var y,I,$,G,O,C,H,N,L,F,_,w,x,D,W,Q,X,ce,kt,dt,A,le,Ie,ke,pt,tr,ht,Rt,rr,qr,Sc,vc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc,Cc,Dc,Bc,Oc,Vc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=($=(I=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:I.trim())!=null?$:"",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=Mg(h);else if(f){let de=Mg(f);$g(de)&&(p=de)}else g&&(p=parseInt(g,10));let S=0,T=(O=(G=s.getAttribute("profiles"))==null?void 0:G.split(","))!=null?O:[];for(let de of u){let GS=(C=de.getAttribute("id"))!=null?C:"id"+(S++).toString(10),Ur=(H=de.getAttribute("mimeType"))!=null?H:"",an=(N=de.getAttribute("codecs"))!=null?N:"",sn=(L=de.getAttribute("contentType"))!=null?L:Ur==null?void 0:Ur.split("/")[0],WS=(_=(F=de.getAttribute("profiles"))==null?void 0:F.split(","))!=null?_:[],YS=(w=de.getAttribute("lang"))!=null?w:void 0,QS=(W=(D=(x=de.querySelector("Label"))==null?void 0:x.textContent)==null?void 0:D.trim())!=null?W:void 0,zS=de.querySelectorAll("Representation"),KS=de.querySelector("SegmentTemplate"),JS=(X=(Q=de.querySelector("Role"))==null?void 0:Q.getAttribute("value"))!=null?X:void 0,Hr=sn,ee={id:GS,language:YS,isDefault:JS==="main",label:QS,codecs:an,hdr:Hr==="video"&&qu(an),mime:Ur,representations:[]};for(let Z of zS){let XS=(ce=Z.getAttribute("lang"))!=null?ce:void 0,ZS=(kt=Z.getAttribute("label"))!=null?kt:void 0,ev=(le=(A=(dt=Z.querySelector("BaseURL"))==null?void 0:dt.textContent)==null?void 0:A.trim())!=null?le:"",nn=new URL(ev||o,e).toString(),ir=(Ie=Z.getAttribute("mimeType"))!=null?Ie:Ur,ya=(pt=(ke=Z.getAttribute("codecs"))!=null?ke:an)!=null?pt:"",on;if(sn==="text"){let $t=Z.getAttribute("id")||"",un=$t.includes("_auto");on={id:$t,isAuto:un,kind:"text",url:nn}}else{let $t=(ht=(tr=Z.getAttribute("contentType"))!=null?tr:ir==null?void 0:ir.split("/")[0])!=null?ht:sn,un=(rr=(Rt=de.getAttribute("profiles"))==null?void 0:Rt.split(","))!=null?rr:[],tv=parseInt((qr=Z.getAttribute("width"))!=null?qr:"",10),_c=parseInt((Sc=Z.getAttribute("height"))!=null?Sc:"",10),Nc=parseInt((vc=Z.getAttribute("bandwidth"))!=null?vc:"",10)/1e3,Fc=(yc=Z.getAttribute("frameRate"))!=null?yc:"",rv=(Tc=Z.getAttribute("quality"))!=null?Tc:void 0,iv=Fc?Rg(Fc):void 0,av=(Ic=Z.getAttribute("id"))!=null?Ic:"id"+(S++).toString(10),sv=$t==="video"?`${_c}p`:$t==="audio"?`${Nc}Kbps`:ya,nv=`${av}@${sv}`,ov=[...T,...WS,...un],cn,uv=Z.querySelector("SegmentBase"),Lt=(Ec=Z.querySelector("SegmentTemplate"))!=null?Ec:KS;if(uv){let Mt=(Pc=(xc=Z.querySelector("SegmentBase Initialization"))==null?void 0:xc.getAttribute("range"))!=null?Pc:"",[Ct,dn]=Mt.split("-").map(ar=>parseInt(ar,10)),ft={from:Ct,to:dn},jr=(Ac=Z.querySelector("SegmentBase"))==null?void 0:Ac.getAttribute("indexRange"),[pn,Ta]=jr?jr.split("-").map(ar=>parseInt(ar,10)):[],Gr=jr?{from:pn,to:Ta}:void 0;cn={type:"byteRange",url:nn,initRange:ft,indexRange:Gr}}else if(Lt){let Mt={representationId:(wc=Z.getAttribute("id"))!=null?wc:void 0,bandwidth:(kc=Z.getAttribute("bandwidth"))!=null?kc:void 0},Ct=parseInt((Rc=Lt.getAttribute("timescale"))!=null?Rc:"",10),dn=($c=Lt.getAttribute("initialization"))!=null?$c:"",ft=Lt.getAttribute("media"),jr=(Mc=parseInt((Lc=Lt.getAttribute("startNumber"))!=null?Lc:"",10))!=null?Mc:1,pn=zt(dn,Mt);if(!ft)throw new ReferenceError("No media attribute in SegmentTemplate");let Ta=(Cc=Lt.querySelectorAll("SegmentTimeline S"))!=null?Cc:[],Gr=[],ar=0,hn="",fn=0;if(Ta.length){let Ia=jr,Ne=0;for(let sr of Ta){let We=parseInt((Dc=sr.getAttribute("d"))!=null?Dc:"",10),Dt=parseInt((Bc=sr.getAttribute("r"))!=null?Bc:"",10)||0,Ea=parseInt((Oc=sr.getAttribute("t"))!=null?Oc:"",10);Ne=Number.isFinite(Ea)?Ea:Ne;let mn=We/Ct*1e3,bn=Ne/Ct*1e3;for(let xa=0;xa<Dt+1;xa++){let lv=zt(ft,V(k({},Mt),{segmentNumber:Ia.toString(10),segmentTime:(Ne+xa*We).toString(10)})),qc=(bn!=null?bn:0)+xa*mn,dv=qc+mn;Ia++,Gr.push({time:{from:qc,to:dv},url:lv})}Ne+=(Dt+1)*We,ar+=(Dt+1)*mn}fn=Ne/Ct*1e3,hn=zt(ft,V(k({},Mt),{segmentNumber:Ia.toString(10),segmentTime:Ne.toString(10)}))}else if($g(p)){let Ne=parseInt((Vc=Lt.getAttribute("duration"))!=null?Vc:"",10)/Ct*1e3,sr=Math.ceil(p/Ne),We=0;for(let Dt=1;Dt<sr;Dt++){let Ea=zt(ft,V(k({},Mt),{segmentNumber:Dt.toString(10),segmentTime:We.toString(10)}));Gr.push({time:{from:We,to:We+Ne},url:Ea}),We+=Ne}fn=We,hn=zt(ft,V(k({},Mt),{segmentNumber:sr.toString(10),segmentTime:We.toString(10)}))}let cv={time:{from:fn,to:1/0},url:hn};cn={type:"template",baseUrl:nn,segmentTemplateUrl:ft,initUrl:pn,totalSegmentsDurationMs:ar,segments:Gr,nextSegmentBeyondManifest:cv,timescale:Ct}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!$t||!ir)continue;let ln={video:"video",audio:"audio",text:"text"}[$t];if(!ln)continue;Hr||(Hr=ln),on={id:nv,kind:ln,segmentReference:cn,profiles:ov,duration:p,bitrate:Nc,mime:ir,codecs:ya,width:tv,height:_c,fps:iv,quality:rv}}ee.language||(ee.language=XS),ee.label||(ee.label=ZS),ee.mime||(ee.mime=ir),ee.codecs||(ee.codecs=ya),ee.hdr||(ee.hdr=Hr==="video"&&qu(ya)),ee.representations.push(on)}Hr&&i[Hr].push(ee)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Ji=Qe(vi(),1);import{videoSizeToQuality as tR}from"@vkontakte/videoplayer-shared";var Bg=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?yt(s):void 0)!=null?o:tR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},Og=({id:a,bitrate:e})=>({id:a,bitrate:e}),$s=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Ji.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Ji.default)(t,-1)},Vg=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ju=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ji.default)(r.split("."),0),isDefault:i}),Gu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ji.default)(i.split("."),0)}),Ls=a=>"url"in a,ut=a=>a.type==="template",Xi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ea=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Zi(0);this.onLastSegment$=new Zi(!1);this.fullyBuffered$=new Zi(!1);this.playingRepresentation$=new Zi(void 0);this.playingRepresentationInit$=new Zi(void 0);this.error$=new iR;this.gaps=[];this.subscription=new aR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new nt;this.destroyAbortController=new nt;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=Dr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){let t=this.representations.get(e);Ve(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Zb(this.sourceBuffer),this.subscription.add(Wu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Kt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Kt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Wu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Kt.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,Cu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=at(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);Ve(r,"No init buffer for starting representation"),Ve(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=Dr(this.destroyAbortController.signal,function(e,t=!1){return te(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Ve(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(_e(s)||_e(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Ve(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();Qu(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield new vn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Dr(this.destroyAbortController.signal,function(e){return te(this,null,function*(){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||!ut(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);Ve(i);let s=this.segments.get(r);Ve(s,"No segments for starting representation");let n=this.initData.get(r);if(Ve(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 nt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if(_e(e)||_e(this.downloadingRepresentationId)||_e(this.playingRepresentationId)||_e(this.sourceBuffer)||!_e(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ve(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=at(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)&&Cu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=at(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,Br.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&&at(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Br.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;Qu(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||!ut(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>V(k({},p),{status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,Br.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;Ve(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(!ut(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=zt(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,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&!(Rr(this.sourceBuffer.buffered,p)&&Rr(this.sourceBuffer.buffered,h)))&&g&&T});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}loadSegments(e,t,r="auto"){return R(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return R(this,null,function*(){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&&(yield Dr(o,function(){return te(this,null,function*(){let l=Yu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=yield 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=Mr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?yield Promise.all(c):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xi(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return R(this,null,function*(){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&&(yield Dr(n,function(){return te(this,null,function*(){let u=Yu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Wu(window,"online").pipe(rR()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Xi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ut(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Br.default)(e,0).byte.from,to:(0,Br.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:Kt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ut(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:Kt.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)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){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){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Mr(o.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(c.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.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,S=b<i,T=g<=i;if(d.status==="downloading"&&S&&T){d.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+b,h),y=this.getCurrentPosition();Qu(y)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-y,this.bufferAccumulation.accumulated.push({segmentView:v,segmentProgress:l}),this.activeSegments.delete(l));let I=({segmentView:$,segmentProgress:G})=>this.sourceBufferTaskQueue.append($,s).then(O=>O&&!s.aborted?this.onSegmentFullyAppended(G,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(I),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||_e(y))&&(I({segmentView:v,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&!T&&(l.loadedBytes=Math.min(h,i-b),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+b+l.feedingBytes,l.loadedBytes-l.feedingBytes),y=l.loadedBytes===h?v:Mr(o.mime).parseFeedableSegmentChunk(v);y!=null&&y.byteLength&&(d.status="partially_fed",l.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(I=>{if(s.aborted)n();else if(I)l.fedBytes+=y.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let c of this.activeSegments){let{segment:l}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-r,p=l.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(f){if(l.status==="downloading"&&b){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(g,s))&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(c.loadedBytes=Math.min(h,i-d),c.loadedBytes>c.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),S=c.loadedBytes===h?g:Mr(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",c.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(c.fedBytes+=S.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,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",Ls(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");Ve(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=$u(()=>(0,_g.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return R(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Dr(this.destroyAbortController.signal,function(){return te(this,null,function*(){let o=Yu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mr(e.mime),i)).then(o=>R(this,null,function*(){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&&ut(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:Kt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return R(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||_e(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(k({},u.time)),i=n(i);let c=Ls(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?(yield Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1})}pruneBufferOld(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||_e(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=Ls(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){Ve(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=$u(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Kt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(_e(this.sourceBuffer)||_e(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 ta=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ng=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 ra,assertNever as Fg,fromEvent as qg,merge as sR,now as ia,Subscription as nR,ValueSubject as zu,flattenObject as Or}from"@vkontakte/videoplayer-shared";var Ms=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new zu(void 0);this.lastConnectionReused$=new zu(void 0);this.lastRequestFirstBytes$=new zu(void 0);this.abortAllController=new nt;this.subscription=new nR;this.fetchManifest=ra(this.abortAllController.signal,function(e){return te(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ta(r));let i=yield st(r,{signal:this.abortAllController.signal}).catch(aa);return i?(t.log("success",Or({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Or({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=ra(this.abortAllController.signal,function(c){return te(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,F;let l=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),l=_.toString();break}default:Fg(t)}this.requestQuic&&(l=ta(l));let h=this.abortAllController.signal,f;if(n){let _=new nt;if(f=sR(qg(this.abortAllController.signal,"abort"),qg(n,"abort")).subscribe(()=>{try{_.abort()}catch(w){aa(w)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(w){aa(w)}h=_.signal}let b=ia();p.log("startRequest",Or({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield st(l,{priority:s,headers:d,signal:h}).catch(aa),S=ia();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(S-b),!g.ok||!g.body){f==null||f.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:_}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let _=ia(),w={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",Or(w)),p.end(),g.arrayBuffer()}let[T,v]=g.body.tee(),y=T.getReader();o&&((F=this.throughputEstimator)==null||F.trackStream(v,u));let I=0,$=new Uint8Array(0),G=!1,O=_=>{f==null||f.unsubscribe(),G=!0,aa(_)},C=ra(h,function(x){return te(this,arguments,function*({done:_,value:w}){if(I===0&&this.lastRequestFirstBytes$.next(ia()-b),h.aborted){f==null||f.unsubscribe();return}if(!_&&w){let D=new Uint8Array($.length+w.length);D.set($),D.set(w,$.length),$=D,I+=w.byteLength,i==null||i(new DataView($.buffer),I),yield y==null?void 0:y.read().then(C,O)}})}.bind(this));yield y==null?void 0:y.read().then(C,O),f==null||f.unsubscribe();let H=ia(),N={failed:G,requestStartedAt:b,requestEndedAt:H,duration:H-b};return G?(p.error("endRequest",Or(N)),p.end(),null):(p.log("endRequest",Or(N)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=ra(this.abortAllController.signal,function(e,t,r){return te(this,null,function*(){var S;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=(S=e.indexRange)!=null?S: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 T=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!T)return null;b=new DataView(T)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=ra(this.abortAllController.signal,function(e,t){return te(this,null,function*(){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=>V(k({},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}=Ng(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return R(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Fg(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},aa=a=>{if(!Xi(a))throw a};var Jt=(a,e,t)=>t*e+(1-t)*a,Ku=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Ug=(a,e,t,r)=>{let i=0,s=t,n=Ku(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 oR,ValueSubject as Hg}from"@vkontakte/videoplayer-shared";var It=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 Hg(e.initial),this.debounced$=new Hg(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ne(`raw_${t}`),this.smoothedSeries$=new ne(`smoothed_${t}`),this.reportedSeries$=new ne(`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+=Ye(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)&&(oR(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 Cs=class extends It{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Jt(this.slow,e,this.params.emaAlphaSlow),this.fast=Jt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ds=class extends It{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ku(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Jt(this.emaSmoothed,e,this.params.emaAlpha);let r=Ug(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Bs=class extends It{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?Jt(this.smoothed,t,this.params.emaAlpha):t}};var Xt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Cs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ds({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 Bs(k({initial:e,label:"liveEdgeDelay"},t))}};var Ju=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var zg=["timeupdate","progress","play","seeked","stalled","waiting"];var _s=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Qg;this.representationSubscription=new Qg;this.state$=new M("none");this.currentVideoRepresentation$=new oe(void 0);this.currentVideoRepresentationInit$=new oe(void 0);this.currentAudioRepresentation$=new oe(void 0);this.currentVideoSegmentLength$=new oe(0);this.currentAudioSegmentLength$=new oe(0);this.error$=new Yg;this.lastConnectionType$=new oe(void 0);this.lastConnectionReused$=new oe(void 0);this.lastRequestFirstBytes$=new oe(void 0);this.isLive$=new oe(!1);this.liveDuration$=new oe(0);this.liveAvailabilityStartTime$=new oe(void 0);this.bufferLength$=new oe(0);this.liveLoadBufferLength$=new oe(0);this.livePositionFromPlayer$=new oe(0);this.timeInWaiting=0;this.isActiveLowLatency$=new oe(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Yg;this.gapWatchdogActive=!1;this.destroyController=new nt;this.initManifest=Xu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:Et.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Xu(this.destroyController.signal,function(){return te(this,null,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:Et.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=Dg(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Qb(e))!=null?n:{id:"ManifestParsing",category:Et.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=ot())==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=Yb(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);pR.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=V(k({},t),{streams:i});return this.tracer.log("updateManifestEnd",sa(s)),s})}.bind(this));this.initRepresentations=Xu(this.destroyController.signal,function(e,t,r){return te(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",sa({initialVideo:e,initialAudio:t,sourceHls:r})),Zt(this.manifest),Zt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Vr(p,"error").pipe(Vs(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Et.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Rb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ys())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 ea("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Wg(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new ea("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(Zu(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=cu(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,f+1e3,2)}})),this.representationSubscription.add(_r(...zg.filter(p=>p!=="waiting").map(p=>Vr(this.element,p))).pipe(ec(p=>this.element?at(this.element.buffered,this.element.currentTime*1e3):0),Gg(),Vs(p=>!!p),lR(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Gg()).subscribe(h=>Ju(this.element,1))),this.representationSubscription.add(Os({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Vs(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(Os({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,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-b,v=1;Math.abs(T)>g&&(v=1+Math.sign(T)*S),Ju(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let S=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(v=>{var y,I;return(I=(y=v.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?I:S}))-S}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Os({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(dR(1e3)).subscribe(b=>R(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(Zt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=cu(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(h)?h:f,G=this.isActiveLowLatency$.getValue(),O=T<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(G&&O);let C="none";if(G?C="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&O?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),C="active_low_latency"):S!==0&&$<v?C="live_forward_buffering":$<v+I&&(C="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),C==="live_forward_buffering"||C==="live_with_target_offset"){let H=p-(v+y),N=this.normolizeLiveOffset(Math.trunc(S+H/g)),L=Math.abs(N-S),F;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?F=S:N>0&&L>this.tuning.dashCmafLive.offsetCalculationError?F=N:F=0,this.manifestUrlString=ae(this.manifestUrlString,F,2)}C!=="none"&&C!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=_r(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ec(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=_r(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ec(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(_r(this.forceEnded$,Os({allBuffersFull:u,someBufferEnded:c}).pipe(Vs(({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:Et.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(_r(...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),ut(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&Wg(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=Zu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:Et.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 Ms({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=Xt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,k({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,i,s,n;Zt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){Zt(this.element),this.state$.setState("running"),this.subscription.add(_r(...zg.map(e=>Vr(this.element,e)),Vr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Et.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Vr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Vr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Rr(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=V(k({},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=V(k({},s),{position:u})}this.tracer.log("stallIntervalCallback",sa(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Zu(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Et.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return R(this,null,function*(){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;Zt(this.element),Zt(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),Rr(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",sa({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=hR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield 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=V(k({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",sa(t)))}}};var Ns=class{constructor(e,t){this.fov=e,this.orientation=t}};var Fs=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/Ye(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=k({},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*Ye(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 Kg=`attribute vec2 a_vertex;
59
59
  attribute vec2 a_texel;
60
60
 
61
61
  varying vec2 v_texel;