@vkontakte/videoplayer-core 2.0.104-dev.7ccfc328.0 → 2.0.105-dev.27e8f5c9.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/esnext.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.104-dev.7ccfc328.0
3
- * Mon, 24 Jun 2024 09:56:11 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-104/doc/
2
+ * @vkontakte/videoplayer-core v2.0.105-dev.27e8f5c9.0
3
+ * Wed, 26 Jun 2024 08:17:33 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-105/doc/
5
5
  */
6
- var tg=Object.create;var gu=Object.defineProperty;var rg=Object.getOwnPropertyDescriptor;var ig=Object.getOwnPropertyNames;var ag=Object.getPrototypeOf,sg=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var ng=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ig(e))!sg.call(i,a)&&a!==t&&gu(i,a,{get:()=>e[a],enumerable:!(r=rg(e,a))||r.enumerable});return i};var Oe=(i,e,t)=>(t=i!=null?tg(ag(i)):{},ng(e||!i||!i.__esModule?gu(t,"default",{value:i,enumerable:!0}):t,i));var ce=f((sR,Pu)=>{"use strict";Pu.exports=function(i){try{return!!i()}catch{return!0}}});var yr=f((nR,ku)=>{"use strict";var fg=ce();ku.exports=!fg(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var X=f((oR,Ru)=>{"use strict";var wu=yr(),Au=Function.prototype,ws=Au.call,mg=wu&&Au.bind.bind(ws,ws);Ru.exports=wu?mg:function(i){return function(){return ws.apply(i,arguments)}}});var Ut=f((uR,$u)=>{"use strict";var Lu=X(),bg=Lu({}.toString),gg=Lu("".slice);$u.exports=function(i){return gg(bg(i),8,-1)}});var Du=f((lR,Cu)=>{"use strict";var vg=X(),Sg=ce(),yg=Ut(),As=Object,Tg=vg("".split);Cu.exports=Sg(function(){return!As("z").propertyIsEnumerable(0)})?function(i){return yg(i)=="String"?Tg(i,""):As(i)}:As});var Ht=f((cR,Mu)=>{"use strict";Mu.exports=function(i){return i==null}});var Wi=f((dR,Ou)=>{"use strict";var Ig=Ht(),Eg=TypeError;Ou.exports=function(i){if(Ig(i))throw Eg("Can't call method on "+i);return i}});var jt=f((pR,Bu)=>{"use strict";var xg=Du(),Pg=Wi();Bu.exports=function(i){return xg(Pg(i))}});var Rs=f((hR,Vu)=>{"use strict";Vu.exports=function(){}});var vt=f((fR,_u)=>{"use strict";_u.exports={}});var G=f((Nu,Fu)=>{"use strict";var Qi=function(i){return i&&i.Math==Math&&i};Fu.exports=Qi(typeof globalThis=="object"&&globalThis)||Qi(typeof window=="object"&&window)||Qi(typeof self=="object"&&self)||Qi(typeof global=="object"&&global)||function(){return this}()||Nu||Function("return this")()});var $s=f((mR,qu)=>{"use strict";var Ls=typeof document=="object"&&document.all,kg=typeof Ls>"u"&&Ls!==void 0;qu.exports={all:Ls,IS_HTMLDDA:kg}});var F=f((bR,Hu)=>{"use strict";var Uu=$s(),wg=Uu.all;Hu.exports=Uu.IS_HTMLDDA?function(i){return typeof i=="function"||i===wg}:function(i){return typeof i=="function"}});var Yu=f((gR,Gu)=>{"use strict";var Ag=G(),Rg=F(),ju=Ag.WeakMap;Gu.exports=Rg(ju)&&/native code/.test(String(ju))});var Be=f((vR,zu)=>{"use strict";var Wu=F(),Qu=$s(),Lg=Qu.all;zu.exports=Qu.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Wu(i)||i===Lg}:function(i){return typeof i=="object"?i!==null:Wu(i)}});var Ve=f((SR,Ku)=>{"use strict";var $g=ce();Ku.exports=!$g(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var zi=f((yR,Xu)=>{"use strict";var Cg=G(),Ju=Be(),Cs=Cg.document,Dg=Ju(Cs)&&Ju(Cs.createElement);Xu.exports=function(i){return Dg?Cs.createElement(i):{}}});var Ds=f((TR,Zu)=>{"use strict";var Mg=Ve(),Og=ce(),Bg=zi();Zu.exports=!Mg&&!Og(function(){return Object.defineProperty(Bg("div"),"a",{get:function(){return 7}}).a!=7})});var Ms=f((IR,el)=>{"use strict";var Vg=Ve(),_g=ce();el.exports=Vg&&_g(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Pe=f((ER,tl)=>{"use strict";var Ng=Be(),Fg=String,qg=TypeError;tl.exports=function(i){if(Ng(i))return i;throw qg(Fg(i)+" is not an object")}});var Z=f((xR,rl)=>{"use strict";var Ug=yr(),Ki=Function.prototype.call;rl.exports=Ug?Ki.bind(Ki):function(){return Ki.apply(Ki,arguments)}});var Ji=f((PR,il)=>{"use strict";il.exports={}});var Ue=f((kR,sl)=>{"use strict";var Os=Ji(),Bs=G(),Hg=F(),al=function(i){return Hg(i)?i:void 0};sl.exports=function(i,e){return arguments.length<2?al(Os[i])||al(Bs[i]):Os[i]&&Os[i][e]||Bs[i]&&Bs[i][e]}});var Tr=f((wR,nl)=>{"use strict";var jg=X();nl.exports=jg({}.isPrototypeOf)});var Ir=f((AR,ol)=>{"use strict";ol.exports=typeof navigator<"u"&&String(navigator.userAgent)||""});var _s=f((RR,hl)=>{"use strict";var pl=G(),Vs=Ir(),ul=pl.process,ll=pl.Deno,cl=ul&&ul.versions||ll&&ll.version,dl=cl&&cl.v8,ke,Xi;dl&&(ke=dl.split("."),Xi=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!Xi&&Vs&&(ke=Vs.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Vs.match(/Chrome\/(\d+)/),ke&&(Xi=+ke[1])));hl.exports=Xi});var Ns=f((LR,ml)=>{"use strict";var fl=_s(),Gg=ce(),Yg=G(),Wg=Yg.String;ml.exports=!!Object.getOwnPropertySymbols&&!Gg(function(){var i=Symbol();return!Wg(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&fl&&fl<41})});var Fs=f(($R,bl)=>{"use strict";var Qg=Ns();bl.exports=Qg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var qs=f((CR,gl)=>{"use strict";var zg=Ue(),Kg=F(),Jg=Tr(),Xg=Fs(),Zg=Object;gl.exports=Xg?function(i){return typeof i=="symbol"}:function(i){var e=zg("Symbol");return Kg(e)&&Jg(e.prototype,Zg(i))}});var Er=f((DR,vl)=>{"use strict";var ev=String;vl.exports=function(i){try{return ev(i)}catch{return"Object"}}});var He=f((MR,Sl)=>{"use strict";var tv=F(),rv=Er(),iv=TypeError;Sl.exports=function(i){if(tv(i))return i;throw iv(rv(i)+" is not a function")}});var xr=f((OR,yl)=>{"use strict";var av=He(),sv=Ht();yl.exports=function(i,e){var t=i[e];return sv(t)?void 0:av(t)}});var Il=f((BR,Tl)=>{"use strict";var Us=Z(),Hs=F(),js=Be(),nv=TypeError;Tl.exports=function(i,e){var t,r;if(e==="string"&&Hs(t=i.toString)&&!js(r=Us(t,i))||Hs(t=i.valueOf)&&!js(r=Us(t,i))||e!=="string"&&Hs(t=i.toString)&&!js(r=Us(t,i)))return r;throw nv("Can't convert object to primitive value")}});var we=f((VR,El)=>{"use strict";El.exports=!0});var kl=f((_R,Pl)=>{"use strict";var xl=G(),ov=Object.defineProperty;Pl.exports=function(i,e){try{ov(xl,i,{value:e,configurable:!0,writable:!0})}catch{xl[i]=e}return e}});var Zi=f((NR,Al)=>{"use strict";var uv=G(),lv=kl(),wl="__core-js_shared__",cv=uv[wl]||lv(wl,{});Al.exports=cv});var Gs=f((FR,Ll)=>{"use strict";var dv=we(),Rl=Zi();(Ll.exports=function(i,e){return Rl[i]||(Rl[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:dv?"pure":"global",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Pr=f((qR,$l)=>{"use strict";var pv=Wi(),hv=Object;$l.exports=function(i){return hv(pv(i))}});var Ae=f((UR,Cl)=>{"use strict";var fv=X(),mv=Pr(),bv=fv({}.hasOwnProperty);Cl.exports=Object.hasOwn||function(e,t){return bv(mv(e),t)}});var Ys=f((HR,Dl)=>{"use strict";var gv=X(),vv=0,Sv=Math.random(),yv=gv(1 .toString);Dl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+yv(++vv+Sv,36)}});var z=f((jR,Ol)=>{"use strict";var Tv=G(),Iv=Gs(),Ml=Ae(),Ev=Ys(),xv=Ns(),Pv=Fs(),Gt=Tv.Symbol,Ws=Iv("wks"),kv=Pv?Gt.for||Gt:Gt&&Gt.withoutSetter||Ev;Ol.exports=function(i){return Ml(Ws,i)||(Ws[i]=xv&&Ml(Gt,i)?Gt[i]:kv("Symbol."+i)),Ws[i]}});var Nl=f((GR,_l)=>{"use strict";var wv=Z(),Bl=Be(),Vl=qs(),Av=xr(),Rv=Il(),Lv=z(),$v=TypeError,Cv=Lv("toPrimitive");_l.exports=function(i,e){if(!Bl(i)||Vl(i))return i;var t=Av(i,Cv),r;if(t){if(e===void 0&&(e="default"),r=wv(t,i,e),!Bl(r)||Vl(r))return r;throw $v("Can't convert object to primitive value")}return e===void 0&&(e="number"),Rv(i,e)}});var ea=f((YR,Fl)=>{"use strict";var Dv=Nl(),Mv=qs();Fl.exports=function(i){var e=Dv(i,"string");return Mv(e)?e:e+""}});var St=f(Ul=>{"use strict";var Ov=Ve(),Bv=Ds(),Vv=Ms(),ta=Pe(),ql=ea(),_v=TypeError,Qs=Object.defineProperty,Nv=Object.getOwnPropertyDescriptor,zs="enumerable",Ks="configurable",Js="writable";Ul.f=Ov?Vv?function(e,t,r){if(ta(e),t=ql(t),ta(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Js in r&&!r[Js]){var a=Nv(e,t);a&&a[Js]&&(e[t]=r.value,r={configurable:Ks in r?r[Ks]:a[Ks],enumerable:zs in r?r[zs]:a[zs],writable:!1})}return Qs(e,t,r)}:Qs:function(e,t,r){if(ta(e),t=ql(t),ta(r),Bv)try{return Qs(e,t,r)}catch{}if("get"in r||"set"in r)throw _v("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var kr=f((QR,Hl)=>{"use strict";Hl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var yt=f((zR,jl)=>{"use strict";var Fv=Ve(),qv=St(),Uv=kr();jl.exports=Fv?function(i,e,t){return qv.f(i,e,Uv(1,t))}:function(i,e,t){return i[e]=t,i}});var ra=f((KR,Yl)=>{"use strict";var Hv=Gs(),jv=Ys(),Gl=Hv("keys");Yl.exports=function(i){return Gl[i]||(Gl[i]=jv(i))}});var ia=f((JR,Wl)=>{"use strict";Wl.exports={}});var tn=f((XR,Kl)=>{"use strict";var Gv=Yu(),zl=G(),Yv=Be(),Wv=yt(),Xs=Ae(),Zs=Zi(),Qv=ra(),zv=ia(),Ql="Object already initialized",en=zl.TypeError,Kv=zl.WeakMap,aa,wr,sa,Jv=function(i){return sa(i)?wr(i):aa(i,{})},Xv=function(i){return function(e){var t;if(!Yv(e)||(t=wr(e)).type!==i)throw en("Incompatible receiver, "+i+" required");return t}};Gv||Zs.state?(Re=Zs.state||(Zs.state=new Kv),Re.get=Re.get,Re.has=Re.has,Re.set=Re.set,aa=function(i,e){if(Re.has(i))throw en(Ql);return e.facade=i,Re.set(i,e),e},wr=function(i){return Re.get(i)||{}},sa=function(i){return Re.has(i)}):(Tt=Qv("state"),zv[Tt]=!0,aa=function(i,e){if(Xs(i,Tt))throw en(Ql);return e.facade=i,Wv(i,Tt,e),e},wr=function(i){return Xs(i,Tt)?i[Tt]:{}},sa=function(i){return Xs(i,Tt)});var Re,Tt;Kl.exports={set:aa,get:wr,has:sa,enforce:Jv,getterFor:Xv}});var rn=f((ZR,ec)=>{"use strict";var Zv=yr(),Zl=Function.prototype,Jl=Zl.apply,Xl=Zl.call;ec.exports=typeof Reflect=="object"&&Reflect.apply||(Zv?Xl.bind(Jl):function(){return Xl.apply(Jl,arguments)})});var an=f((eL,tc)=>{"use strict";var eS=Ut(),tS=X();tc.exports=function(i){if(eS(i)==="Function")return tS(i)}});var sc=f(ac=>{"use strict";var rc={}.propertyIsEnumerable,ic=Object.getOwnPropertyDescriptor,rS=ic&&!rc.call({1:2},1);ac.f=rS?function(e){var t=ic(this,e);return!!t&&t.enumerable}:rc});var sn=f(oc=>{"use strict";var iS=Ve(),aS=Z(),sS=sc(),nS=kr(),oS=jt(),uS=ea(),lS=Ae(),cS=Ds(),nc=Object.getOwnPropertyDescriptor;oc.f=iS?nc:function(e,t){if(e=oS(e),t=uS(t),cS)try{return nc(e,t)}catch{}if(lS(e,t))return nS(!aS(sS.f,e,t),e[t])}});var nn=f((iL,uc)=>{"use strict";var dS=ce(),pS=F(),hS=/#|\.prototype\./,Ar=function(i,e){var t=mS[fS(i)];return t==gS?!0:t==bS?!1:pS(e)?dS(e):!!e},fS=Ar.normalize=function(i){return String(i).replace(hS,".").toLowerCase()},mS=Ar.data={},bS=Ar.NATIVE="N",gS=Ar.POLYFILL="P";uc.exports=Ar});var Rr=f((aL,cc)=>{"use strict";var lc=an(),vS=He(),SS=yr(),yS=lc(lc.bind);cc.exports=function(i,e){return vS(i),e===void 0?i:SS?yS(i,e):function(){return i.apply(e,arguments)}}});var fe=f((sL,pc)=>{"use strict";var na=G(),TS=rn(),IS=an(),ES=F(),xS=sn().f,PS=nn(),Yt=Ji(),kS=Rr(),Wt=yt(),dc=Ae(),wS=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return TS(i,this,arguments)};return e.prototype=i.prototype,e};pc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?na:a?na[t]:(na[t]||{}).prototype,o=r?Yt:Yt[t]||Wt(Yt,t,{})[t],l=o.prototype,u,c,d,h,p,m,S,b,v;for(h in e)u=PS(r?h:t+(a?".":"#")+h,i.forced),c=!u&&n&&dc(n,h),m=o[h],c&&(i.dontCallGetSet?(v=xS(n,h),S=v&&v.value):S=n[h]),p=c&&S?S:e[h],!(c&&typeof m==typeof p)&&(i.bind&&c?b=kS(p,na):i.wrap&&c?b=wS(p):s&&ES(p)?b=IS(p):b=p,(i.sham||p&&p.sham||m&&m.sham)&&Wt(b,"sham",!0),Wt(o,h,b),s&&(d=t+"Prototype",dc(Yt,d)||Wt(Yt,d,{}),Wt(Yt[d],h,p),i.real&&l&&(u||!l[h])&&Wt(l,h,p)))}});var mc=f((nL,fc)=>{"use strict";var on=Ve(),AS=Ae(),hc=Function.prototype,RS=on&&Object.getOwnPropertyDescriptor,un=AS(hc,"name"),LS=un&&function(){}.name==="something",$S=un&&(!on||on&&RS(hc,"name").configurable);fc.exports={EXISTS:un,PROPER:LS,CONFIGURABLE:$S}});var gc=f((oL,bc)=>{"use strict";var CS=Math.ceil,DS=Math.floor;bc.exports=Math.trunc||function(e){var t=+e;return(t>0?DS:CS)(t)}});var oa=f((uL,vc)=>{"use strict";var MS=gc();vc.exports=function(i){var e=+i;return e!==e||e===0?0:MS(e)}});var yc=f((lL,Sc)=>{"use strict";var OS=oa(),BS=Math.max,VS=Math.min;Sc.exports=function(i,e){var t=OS(i);return t<0?BS(t+e,0):VS(t,e)}});var Ic=f((cL,Tc)=>{"use strict";var _S=oa(),NS=Math.min;Tc.exports=function(i){return i>0?NS(_S(i),9007199254740991):0}});var ua=f((dL,Ec)=>{"use strict";var FS=Ic();Ec.exports=function(i){return FS(i.length)}});var kc=f((pL,Pc)=>{"use strict";var qS=jt(),US=yc(),HS=ua(),xc=function(i){return function(e,t,r){var a=qS(e),s=HS(a),n=US(r,s),o;if(i&&t!=t){for(;s>n;)if(o=a[n++],o!=o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};Pc.exports={includes:xc(!0),indexOf:xc(!1)}});var Rc=f((hL,Ac)=>{"use strict";var jS=X(),ln=Ae(),GS=jt(),YS=kc().indexOf,WS=ia(),wc=jS([].push);Ac.exports=function(i,e){var t=GS(i),r=0,a=[],s;for(s in t)!ln(WS,s)&&ln(t,s)&&wc(a,s);for(;e.length>r;)ln(t,s=e[r++])&&(~YS(a,s)||wc(a,s));return a}});var cn=f((fL,Lc)=>{"use strict";Lc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Cc=f((mL,$c)=>{"use strict";var QS=Rc(),zS=cn();$c.exports=Object.keys||function(e){return QS(e,zS)}});var Mc=f(Dc=>{"use strict";var KS=Ve(),JS=Ms(),XS=St(),ZS=Pe(),ey=jt(),ty=Cc();Dc.f=KS&&!JS?Object.defineProperties:function(e,t){ZS(e);for(var r=ey(t),a=ty(t),s=a.length,n=0,o;s>n;)XS.f(e,o=a[n++],r[o]);return e}});var dn=f((gL,Oc)=>{"use strict";var ry=Ue();Oc.exports=ry("document","documentElement")});var mn=f((vL,Uc)=>{"use strict";var iy=Pe(),ay=Mc(),Bc=cn(),sy=ia(),ny=dn(),oy=zi(),uy=ra(),Vc=">",_c="<",hn="prototype",fn="script",Fc=uy("IE_PROTO"),pn=function(){},qc=function(i){return _c+fn+Vc+i+_c+"/"+fn+Vc},Nc=function(i){i.write(qc("")),i.close();var e=i.parentWindow.Object;return i=null,e},ly=function(){var i=oy("iframe"),e="java"+fn+":",t;return i.style.display="none",ny.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(qc("document.F=Object")),t.close(),t.F},la,ca=function(){try{la=new ActiveXObject("htmlfile")}catch{}ca=typeof document<"u"?document.domain&&la?Nc(la):ly():Nc(la);for(var i=Bc.length;i--;)delete ca[hn][Bc[i]];return ca()};sy[Fc]=!0;Uc.exports=Object.create||function(e,t){var r;return e!==null?(pn[hn]=iy(e),r=new pn,pn[hn]=null,r[Fc]=e):r=ca(),t===void 0?r:ay.f(r,t)}});var jc=f((SL,Hc)=>{"use strict";var cy=ce();Hc.exports=!cy(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var gn=f((yL,Yc)=>{"use strict";var dy=Ae(),py=F(),hy=Pr(),fy=ra(),my=jc(),Gc=fy("IE_PROTO"),bn=Object,by=bn.prototype;Yc.exports=my?bn.getPrototypeOf:function(i){var e=hy(i);if(dy(e,Gc))return e[Gc];var t=e.constructor;return py(t)&&e instanceof t?t.prototype:e instanceof bn?by:null}});var Qt=f((TL,Wc)=>{"use strict";var gy=yt();Wc.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:gy(i,e,t),i}});var Tn=f((IL,Kc)=>{"use strict";var vy=ce(),Sy=F(),yy=Be(),Ty=mn(),Qc=gn(),Iy=Qt(),Ey=z(),xy=we(),yn=Ey("iterator"),zc=!1,je,vn,Sn;[].keys&&(Sn=[].keys(),"next"in Sn?(vn=Qc(Qc(Sn)),vn!==Object.prototype&&(je=vn)):zc=!0);var Py=!yy(je)||vy(function(){var i={};return je[yn].call(i)!==i});Py?je={}:xy&&(je=Ty(je));Sy(je[yn])||Iy(je,yn,function(){return this});Kc.exports={IteratorPrototype:je,BUGGY_SAFARI_ITERATORS:zc}});var da=f((EL,Xc)=>{"use strict";var ky=z(),wy=ky("toStringTag"),Jc={};Jc[wy]="z";Xc.exports=String(Jc)==="[object z]"});var zt=f((xL,Zc)=>{"use strict";var Ay=da(),Ry=F(),pa=Ut(),Ly=z(),$y=Ly("toStringTag"),Cy=Object,Dy=pa(function(){return arguments}())=="Arguments",My=function(i,e){try{return i[e]}catch{}};Zc.exports=Ay?pa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=My(e=Cy(i),$y))=="string"?t:Dy?pa(e):(r=pa(e))=="Object"&&Ry(e.callee)?"Arguments":r}});var td=f((PL,ed)=>{"use strict";var Oy=da(),By=zt();ed.exports=Oy?{}.toString:function(){return"[object "+By(this)+"]"}});var ha=f((kL,id)=>{"use strict";var Vy=da(),_y=St().f,Ny=yt(),Fy=Ae(),qy=td(),Uy=z(),rd=Uy("toStringTag");id.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;Fy(a,rd)||_y(a,rd,{configurable:!0,value:e}),r&&!Vy&&Ny(a,"toString",qy)}}});var sd=f((wL,ad)=>{"use strict";var Hy=Tn().IteratorPrototype,jy=mn(),Gy=kr(),Yy=ha(),Wy=vt(),Qy=function(){return this};ad.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=jy(Hy,{next:Gy(+!r,t)}),Yy(i,a,!1,!0),Wy[a]=Qy,i}});var od=f((AL,nd)=>{"use strict";var zy=X(),Ky=He();nd.exports=function(i,e,t){try{return zy(Ky(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var ld=f((RL,ud)=>{"use strict";var Jy=F(),Xy=String,Zy=TypeError;ud.exports=function(i){if(typeof i=="object"||Jy(i))return i;throw Zy("Can't set "+Xy(i)+" as a prototype")}});var In=f((LL,cd)=>{"use strict";var eT=od(),tT=Pe(),rT=ld();cd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=eT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return tT(a),rT(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var Td=f(($L,yd)=>{"use strict";var iT=fe(),aT=Z(),fa=we(),vd=mc(),sT=F(),nT=sd(),dd=gn(),pd=In(),oT=ha(),uT=yt(),En=Qt(),lT=z(),hd=vt(),Sd=Tn(),cT=vd.PROPER,dT=vd.CONFIGURABLE,fd=Sd.IteratorPrototype,ma=Sd.BUGGY_SAFARI_ITERATORS,Lr=lT("iterator"),md="keys",$r="values",bd="entries",gd=function(){return this};yd.exports=function(i,e,t,r,a,s,n){nT(t,e,r);var o=function(v){if(v===a&&h)return h;if(!ma&&v in c)return c[v];switch(v){case md:return function(){return new t(this,v)};case $r:return function(){return new t(this,v)};case bd:return function(){return new t(this,v)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[Lr]||c["@@iterator"]||a&&c[a],h=!ma&&d||o(a),p=e=="Array"&&c.entries||d,m,S,b;if(p&&(m=dd(p.call(new i)),m!==Object.prototype&&m.next&&(!fa&&dd(m)!==fd&&(pd?pd(m,fd):sT(m[Lr])||En(m,Lr,gd)),oT(m,l,!0,!0),fa&&(hd[l]=gd))),cT&&a==$r&&d&&d.name!==$r&&(!fa&&dT?uT(c,"name",$r):(u=!0,h=function(){return aT(d,this)})),a)if(S={values:o($r),keys:s?h:o(md),entries:o(bd)},n)for(b in S)(ma||u||!(b in c))&&En(c,b,S[b]);else iT({target:e,proto:!0,forced:ma||u},S);return(!fa||n)&&c[Lr]!==h&&En(c,Lr,h,{name:a}),hd[e]=h,S}});var Ed=f((CL,Id)=>{"use strict";Id.exports=function(i,e){return{value:i,done:e}}});var Pn=f((DL,Ad)=>{"use strict";var pT=jt(),xn=Rs(),xd=vt(),kd=tn(),hT=St().f,fT=Td(),ba=Ed(),mT=we(),bT=Ve(),wd="Array Iterator",gT=kd.set,vT=kd.getterFor(wd);Ad.exports=fT(Array,"Array",function(i,e){gT(this,{type:wd,target:pT(i),index:0,kind:e})},function(){var i=vT(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,ba(void 0,!0)):t=="keys"?ba(r,!1):t=="values"?ba(e[r],!1):ba([r,e[r]],!1)},"values");var Pd=xd.Arguments=xd.Array;xn("keys");xn("values");xn("entries");if(!mT&&bT&&Pd.name!=="values")try{hT(Pd,"name",{value:"values"})}catch{}});var Ld=f((ML,Rd)=>{"use strict";var ST=z(),yT=vt(),TT=ST("iterator"),IT=Array.prototype;Rd.exports=function(i){return i!==void 0&&(yT.Array===i||IT[TT]===i)}});var kn=f((OL,Cd)=>{"use strict";var ET=zt(),$d=xr(),xT=Ht(),PT=vt(),kT=z(),wT=kT("iterator");Cd.exports=function(i){if(!xT(i))return $d(i,wT)||$d(i,"@@iterator")||PT[ET(i)]}});var Md=f((BL,Dd)=>{"use strict";var AT=Z(),RT=He(),LT=Pe(),$T=Er(),CT=kn(),DT=TypeError;Dd.exports=function(i,e){var t=arguments.length<2?CT(i):e;if(RT(t))return LT(AT(t,i));throw DT($T(i)+" is not iterable")}});var Vd=f((VL,Bd)=>{"use strict";var MT=Z(),Od=Pe(),OT=xr();Bd.exports=function(i,e,t){var r,a;Od(i);try{if(r=OT(i,"return"),!r){if(e==="throw")throw t;return t}r=MT(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Od(r),t}});var va=f((_L,qd)=>{"use strict";var BT=Rr(),VT=Z(),_T=Pe(),NT=Er(),FT=Ld(),qT=ua(),_d=Tr(),UT=Md(),HT=kn(),Nd=Vd(),jT=TypeError,ga=function(i,e){this.stopped=i,this.result=e},Fd=ga.prototype;qd.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=BT(e,r),u,c,d,h,p,m,S,b=function(g){return u&&Nd(u,"normal",g),new ga(!0,g)},v=function(g){return a?(_T(g),o?l(g[0],g[1],b):l(g[0],g[1])):o?l(g,b):l(g)};if(s)u=i.iterator;else if(n)u=i;else{if(c=HT(i),!c)throw jT(NT(i)+" is not iterable");if(FT(c)){for(d=0,h=qT(i);h>d;d++)if(p=v(i[d]),p&&_d(Fd,p))return p;return new ga(!1)}u=UT(i,c)}for(m=s?i.next:u.next;!(S=VT(m,u)).done;){try{p=v(S.value)}catch(g){Nd(u,"throw",g)}if(typeof p=="object"&&p&&_d(Fd,p))return p}return new ga(!1)}});var Hd=f((NL,Ud)=>{"use strict";var GT=ea(),YT=St(),WT=kr();Ud.exports=function(i,e,t){var r=GT(e);r in i?YT.f(i,r,WT(0,t)):i[r]=t}});var jd=f(()=>{"use strict";var QT=fe(),zT=va(),KT=Hd();QT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return zT(e,function(r,a){KT(t,r,a)},{AS_ENTRIES:!0}),t}})});var Yd=f((UL,Gd)=>{"use strict";Pn();jd();var JT=Ji();Gd.exports=JT.Object.fromEntries});var Qd=f((HL,Wd)=>{"use strict";Wd.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 Jd=f(()=>{"use strict";Pn();var XT=Qd(),ZT=G(),eI=zt(),tI=yt(),zd=vt(),rI=z(),Kd=rI("toStringTag");for(Sa in XT)wn=ZT[Sa],ya=wn&&wn.prototype,ya&&eI(ya)!==Kd&&tI(ya,Kd,Sa),zd[Sa]=zd.Array;var wn,ya,Sa});var Zd=f((YL,Xd)=>{"use strict";var iI=Yd();Jd();Xd.exports=iI});var Ta=f((WL,ep)=>{"use strict";var aI=Zd();ep.exports=aI});var tp=f(()=>{"use strict"});var Cr=f((KL,rp)=>{"use strict";var sI=Ut();rp.exports=typeof process<"u"&&sI(process)=="process"});var ap=f((JL,ip)=>{"use strict";var nI=St();ip.exports=function(i,e,t){return nI.f(i,e,t)}});var op=f((XL,np)=>{"use strict";var oI=Ue(),uI=ap(),lI=z(),cI=Ve(),sp=lI("species");np.exports=function(i){var e=oI(i);cI&&e&&!e[sp]&&uI(e,sp,{configurable:!0,get:function(){return this}})}});var lp=f((ZL,up)=>{"use strict";var dI=Tr(),pI=TypeError;up.exports=function(i,e){if(dI(e,i))return i;throw pI("Incorrect invocation")}});var Rn=f((e$,cp)=>{"use strict";var hI=X(),fI=F(),An=Zi(),mI=hI(Function.toString);fI(An.inspectSource)||(An.inspectSource=function(i){return mI(i)});cp.exports=An.inspectSource});var bp=f((t$,mp)=>{"use strict";var bI=X(),gI=ce(),dp=F(),vI=zt(),SI=Ue(),yI=Rn(),pp=function(){},TI=[],hp=SI("Reflect","construct"),Ln=/^\s*(?:class|function)\b/,II=bI(Ln.exec),EI=!Ln.exec(pp),Dr=function(e){if(!dp(e))return!1;try{return hp(pp,TI,e),!0}catch{return!1}},fp=function(e){if(!dp(e))return!1;switch(vI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return EI||!!II(Ln,yI(e))}catch{return!0}};fp.sham=!0;mp.exports=!hp||gI(function(){var i;return Dr(Dr.call)||!Dr(Object)||!Dr(function(){i=!0})||i})?fp:Dr});var vp=f((r$,gp)=>{"use strict";var xI=bp(),PI=Er(),kI=TypeError;gp.exports=function(i){if(xI(i))return i;throw kI(PI(i)+" is not a constructor")}});var $n=f((i$,yp)=>{"use strict";var Sp=Pe(),wI=vp(),AI=Ht(),RI=z(),LI=RI("species");yp.exports=function(i,e){var t=Sp(i).constructor,r;return t===void 0||AI(r=Sp(t)[LI])?e:wI(r)}});var Ip=f((a$,Tp)=>{"use strict";var $I=X();Tp.exports=$I([].slice)});var xp=f((s$,Ep)=>{"use strict";var CI=TypeError;Ep.exports=function(i,e){if(i<e)throw CI("Not enough arguments");return i}});var Cn=f((n$,Pp)=>{"use strict";var DI=Ir();Pp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(DI)});var qn=f((o$,Mp)=>{"use strict";var de=G(),MI=rn(),OI=Rr(),kp=F(),BI=Ae(),Dp=ce(),wp=dn(),VI=Ip(),Ap=zi(),_I=xp(),NI=Cn(),FI=Cr(),_n=de.setImmediate,Nn=de.clearImmediate,qI=de.process,Dn=de.Dispatch,UI=de.Function,Rp=de.MessageChannel,HI=de.String,Mn=0,Mr={},Lp="onreadystatechange",Or,It,On,Bn;Dp(function(){Or=de.location});var Fn=function(i){if(BI(Mr,i)){var e=Mr[i];delete Mr[i],e()}},Vn=function(i){return function(){Fn(i)}},$p=function(i){Fn(i.data)},Cp=function(i){de.postMessage(HI(i),Or.protocol+"//"+Or.host)};(!_n||!Nn)&&(_n=function(e){_I(arguments.length,1);var t=kp(e)?e:UI(e),r=VI(arguments,1);return Mr[++Mn]=function(){MI(t,void 0,r)},It(Mn),Mn},Nn=function(e){delete Mr[e]},FI?It=function(i){qI.nextTick(Vn(i))}:Dn&&Dn.now?It=function(i){Dn.now(Vn(i))}:Rp&&!NI?(On=new Rp,Bn=On.port2,On.port1.onmessage=$p,It=OI(Bn.postMessage,Bn)):de.addEventListener&&kp(de.postMessage)&&!de.importScripts&&Or&&Or.protocol!=="file:"&&!Dp(Cp)?(It=Cp,de.addEventListener("message",$p,!1)):Lp in Ap("script")?It=function(i){wp.appendChild(Ap("script"))[Lp]=function(){wp.removeChild(this),Fn(i)}}:It=function(i){setTimeout(Vn(i),0)});Mp.exports={set:_n,clear:Nn}});var Un=f((u$,Bp)=>{"use strict";var Op=function(){this.head=null,this.tail=null};Op.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};Bp.exports=Op});var _p=f((l$,Vp)=>{"use strict";var jI=Ir();Vp.exports=/ipad|iphone|ipod/i.test(jI)&&typeof Pebble<"u"});var Fp=f((c$,Np)=>{"use strict";var GI=Ir();Np.exports=/web0s(?!.*chrome)/i.test(GI)});var Qp=f((d$,Wp)=>{"use strict";var Et=G(),qp=Rr(),YI=sn().f,Hn=qn().set,WI=Un(),QI=Cn(),zI=_p(),KI=Fp(),jn=Cr(),Up=Et.MutationObserver||Et.WebKitMutationObserver,Hp=Et.document,jp=Et.process,Ia=Et.Promise,Gp=YI(Et,"queueMicrotask"),Wn=Gp&&Gp.value,Kt,Gn,Yn,Ea,Yp;Wn||(Br=new WI,Vr=function(){var i,e;for(jn&&(i=jp.domain)&&i.exit();e=Br.get();)try{e()}catch(t){throw Br.head&&Kt(),t}i&&i.enter()},!QI&&!jn&&!KI&&Up&&Hp?(Gn=!0,Yn=Hp.createTextNode(""),new Up(Vr).observe(Yn,{characterData:!0}),Kt=function(){Yn.data=Gn=!Gn}):!zI&&Ia&&Ia.resolve?(Ea=Ia.resolve(void 0),Ea.constructor=Ia,Yp=qp(Ea.then,Ea),Kt=function(){Yp(Vr)}):jn?Kt=function(){jp.nextTick(Vr)}:(Hn=qp(Hn,Et),Kt=function(){Hn(Vr)}),Wn=function(i){Br.head||Kt(),Br.add(i)});var Br,Vr;Wp.exports=Wn});var Kp=f((p$,zp)=>{"use strict";zp.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch{}}});var xa=f((h$,Jp)=>{"use strict";Jp.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var xt=f((f$,Xp)=>{"use strict";var JI=G();Xp.exports=JI.Promise});var Qn=f((m$,Zp)=>{"use strict";Zp.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var th=f((b$,eh)=>{"use strict";var XI=Qn(),ZI=Cr();eh.exports=!XI&&!ZI&&typeof window=="object"&&typeof document=="object"});var Jt=f((g$,ah)=>{"use strict";var eE=G(),_r=xt(),tE=F(),rE=nn(),iE=Rn(),aE=z(),sE=th(),nE=Qn(),oE=we(),zn=_s(),rh=_r&&_r.prototype,uE=aE("species"),Kn=!1,ih=tE(eE.PromiseRejectionEvent),lE=rE("Promise",function(){var i=iE(_r),e=i!==String(_r);if(!e&&zn===66||oE&&!(rh.catch&&rh.finally))return!0;if(!zn||zn<51||!/native code/.test(i)){var t=new _r(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[uE]=r,Kn=t.then(function(){})instanceof r,!Kn)return!0}return!e&&(sE||nE)&&!ih});ah.exports={CONSTRUCTOR:lE,REJECTION_EVENT:ih,SUBCLASSING:Kn}});var Xt=f((v$,nh)=>{"use strict";var sh=He(),cE=TypeError,dE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw cE("Bad Promise constructor");e=r,t=a}),this.resolve=sh(e),this.reject=sh(t)};nh.exports.f=function(i){return new dE(i)}});var Ph=f(()=>{"use strict";var pE=fe(),hE=we(),Aa=Cr(),it=G(),rr=Z(),oh=Qt(),uh=In(),fE=ha(),mE=op(),bE=He(),wa=F(),gE=Be(),vE=lp(),SE=$n(),hh=qn().set,to=Qp(),yE=Kp(),TE=xa(),IE=Un(),fh=tn(),Ra=xt(),ro=Jt(),mh=Xt(),La="Promise",bh=ro.CONSTRUCTOR,EE=ro.REJECTION_EVENT,xE=ro.SUBCLASSING,Jn=fh.getterFor(La),PE=fh.set,Zt=Ra&&Ra.prototype,Pt=Ra,Pa=Zt,gh=it.TypeError,Xn=it.document,io=it.process,Zn=mh.f,kE=Zn,wE=!!(Xn&&Xn.createEvent&&it.dispatchEvent),vh="unhandledrejection",AE="rejectionhandled",lh=0,Sh=1,RE=2,ao=1,yh=2,ka,ch,LE,dh,Th=function(i){var e;return gE(i)&&wa(e=i.then)?e:!1},Ih=function(i,e){var t=e.value,r=e.state==Sh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===yh&&CE(e),e.rejection=ao),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(gh("Promise-chain cycle")):(u=Th(l))?rr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Eh=function(i,e){i.notified||(i.notified=!0,to(function(){for(var t=i.reactions,r;r=t.get();)Ih(r,i);i.notified=!1,e&&!i.rejection&&$E(i)}))},xh=function(i,e,t){var r,a;wE?(r=Xn.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),it.dispatchEvent(r)):r={promise:e,reason:t},!EE&&(a=it["on"+i])?a(r):i===vh&&yE("Unhandled promise rejection",t)},$E=function(i){rr(hh,it,function(){var e=i.facade,t=i.value,r=ph(i),a;if(r&&(a=TE(function(){Aa?io.emit("unhandledRejection",t,e):xh(vh,e,t)}),i.rejection=Aa||ph(i)?yh:ao,a.error))throw a.value})},ph=function(i){return i.rejection!==ao&&!i.parent},CE=function(i){rr(hh,it,function(){var e=i.facade;Aa?io.emit("rejectionHandled",e):xh(AE,e,i.value)})},er=function(i,e,t){return function(r){i(e,r,t)}},tr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=RE,Eh(i,!0))},eo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw gh("Promise can't be resolved itself");var r=Th(e);r?to(function(){var a={done:!1};try{rr(r,e,er(eo,a,i),er(tr,a,i))}catch(s){tr(a,s,i)}}):(i.value=e,i.state=Sh,Eh(i,!1))}catch(a){tr({done:!1},a,i)}}};if(bh&&(Pt=function(e){vE(this,Pa),bE(e),rr(ka,this);var t=Jn(this);try{e(er(eo,t),er(tr,t))}catch(r){tr(t,r)}},Pa=Pt.prototype,ka=function(e){PE(this,{type:La,done:!1,notified:!1,parent:!1,reactions:new IE,rejection:!1,state:lh,value:void 0})},ka.prototype=oh(Pa,"then",function(e,t){var r=Jn(this),a=Zn(SE(this,Pt));return r.parent=!0,a.ok=wa(e)?e:!0,a.fail=wa(t)&&t,a.domain=Aa?io.domain:void 0,r.state==lh?r.reactions.add(a):to(function(){Ih(a,r)}),a.promise}),ch=function(){var i=new ka,e=Jn(i);this.promise=i,this.resolve=er(eo,e),this.reject=er(tr,e)},mh.f=Zn=function(i){return i===Pt||i===LE?new ch(i):kE(i)},!hE&&wa(Ra)&&Zt!==Object.prototype)){dh=Zt.then,xE||oh(Zt,"then",function(e,t){var r=this;return new Pt(function(a,s){rr(dh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete Zt.constructor}catch{}uh&&uh(Zt,Pa)}pE({global:!0,constructor:!0,wrap:!0,forced:bh},{Promise:Pt});fE(Pt,La,!1,!0);mE(La)});var Lh=f((T$,Rh)=>{"use strict";var DE=z(),wh=DE("iterator"),Ah=!1;try{kh=0,so={next:function(){return{done:!!kh++}},return:function(){Ah=!0}},so[wh]=function(){return this},Array.from(so,function(){throw 2})}catch{}var kh,so;Rh.exports=function(i,e){if(!e&&!Ah)return!1;var t=!1;try{var r={};r[wh]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var no=f((I$,$h)=>{"use strict";var ME=xt(),OE=Lh(),BE=Jt().CONSTRUCTOR;$h.exports=BE||!OE(function(i){ME.all(i).then(void 0,function(){})})});var Ch=f(()=>{"use strict";var VE=fe(),_E=Z(),NE=He(),FE=Xt(),qE=xa(),UE=va(),HE=no();VE({target:"Promise",stat:!0,forced:HE},{all:function(e){var t=this,r=FE.f(t),a=r.resolve,s=r.reject,n=qE(function(){var o=NE(t.resolve),l=[],u=0,c=1;UE(e,function(d){var h=u++,p=!1;c++,_E(o,t,d).then(function(m){p||(p=!0,l[h]=m,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var Mh=f(()=>{"use strict";var jE=fe(),GE=we(),YE=Jt().CONSTRUCTOR,uo=xt(),WE=Ue(),QE=F(),zE=Qt(),Dh=uo&&uo.prototype;jE({target:"Promise",proto:!0,forced:YE,real:!0},{catch:function(i){return this.then(void 0,i)}});!GE&&QE(uo)&&(oo=WE("Promise").prototype.catch,Dh.catch!==oo&&zE(Dh,"catch",oo,{unsafe:!0}));var oo});var Oh=f(()=>{"use strict";var KE=fe(),JE=Z(),XE=He(),ZE=Xt(),ex=xa(),tx=va(),rx=no();KE({target:"Promise",stat:!0,forced:rx},{race:function(e){var t=this,r=ZE.f(t),a=r.reject,s=ex(function(){var n=XE(t.resolve);tx(e,function(o){JE(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Bh=f(()=>{"use strict";var ix=fe(),ax=Z(),sx=Xt(),nx=Jt().CONSTRUCTOR;ix({target:"Promise",stat:!0,forced:nx},{reject:function(e){var t=sx.f(this);return ax(t.reject,void 0,e),t.promise}})});var lo=f(($$,Vh)=>{"use strict";var ox=Pe(),ux=Be(),lx=Xt();Vh.exports=function(i,e){if(ox(i),ux(e)&&e.constructor===i)return e;var t=lx.f(i),r=t.resolve;return r(e),t.promise}});var Fh=f(()=>{"use strict";var cx=fe(),dx=Ue(),_h=we(),px=xt(),Nh=Jt().CONSTRUCTOR,hx=lo(),fx=dx("Promise"),mx=_h&&!Nh;cx({target:"Promise",stat:!0,forced:_h||Nh},{resolve:function(e){return hx(mx&&this===fx?px:this,e)}})});var qh=f(()=>{"use strict";Ph();Ch();Mh();Oh();Bh();Fh()});var Gh=f(()=>{"use strict";var bx=fe(),gx=we(),$a=xt(),vx=ce(),Hh=Ue(),jh=F(),Sx=$n(),Uh=lo(),yx=Qt(),po=$a&&$a.prototype,Tx=!!$a&&vx(function(){po.finally.call({then:function(){}},function(){})});bx({target:"Promise",proto:!0,real:!0,forced:Tx},{finally:function(i){var e=Sx(this,Hh("Promise")),t=jh(i);return this.then(t?function(r){return Uh(e,i()).then(function(){return r})}:i,t?function(r){return Uh(e,i()).then(function(){throw r})}:i)}});!gx&&jh($a)&&(co=Hh("Promise").prototype.finally,po.finally!==co&&yx(po,"finally",co,{unsafe:!0}));var co});var Ca=f((_$,Yh)=>{"use strict";var Ix=Ue();Yh.exports=Ix});var Qh=f((N$,Wh)=>{"use strict";tp();qh();Gh();var Ex=Ca();Wh.exports=Ex("Promise","finally")});var Kh=f((F$,zh)=>{"use strict";var xx=Qh();zh.exports=xx});var Da=f((q$,Jh)=>{"use strict";var Px=Kh();Jh.exports=Px});var If=f(()=>{"use strict";var Jx=fe(),Xx=Pr(),Zx=ua(),eP=oa(),tP=Rs();Jx({target:"Array",proto:!0},{at:function(e){var t=Xx(this),r=Zx(t),a=eP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});tP("at")});var xf=f((KC,Ef)=>{"use strict";If();var rP=Ca();Ef.exports=rP("Array","at")});var kf=f((JC,Pf)=>{"use strict";var iP=xf();Pf.exports=iP});var Ba=f((XC,wf)=>{"use strict";var aP=kf();wf.exports=aP});var im=f(()=>{"use strict"});var am=f(()=>{"use strict"});var nm=f((_O,sm)=>{"use strict";var lk=Be(),ck=Ut(),dk=z(),pk=dk("match");sm.exports=function(i){var e;return lk(i)&&((e=i[pk])!==void 0?!!e:ck(i)=="RegExp")}});var um=f((NO,om)=>{"use strict";var hk=zt(),fk=String;om.exports=function(i){if(hk(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return fk(i)}});var cm=f((FO,lm)=>{"use strict";var mk=Pe();lm.exports=function(){var i=mk(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var hm=f((qO,pm)=>{"use strict";var bk=Z(),gk=Ae(),vk=Tr(),Sk=cm(),dm=RegExp.prototype;pm.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in dm)&&!gk(i,"flags")&&vk(dm,i)?bk(Sk,i):e}});var mm=f((UO,fm)=>{"use strict";var No=X(),yk=Pr(),Tk=Math.floor,Vo=No("".charAt),Ik=No("".replace),_o=No("".slice),Ek=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xk=/\$([$&'`]|\d{1,2})/g;fm.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=xk;return a!==void 0&&(a=yk(a),l=Ek),Ik(s,l,function(u,c){var d;switch(Vo(c,0)){case"$":return"$";case"&":return i;case"`":return _o(e,0,t);case"'":return _o(e,n);case"<":d=a[_o(c,1,-1)];break;default:var h=+c;if(h===0)return u;if(h>o){var p=Tk(h/10);return p===0?u:p<=o?r[p-1]===void 0?Vo(c,1):r[p-1]+Vo(c,1):u}d=r[h-1]}return d===void 0?"":d})}});var ym=f(()=>{"use strict";var Pk=fe(),kk=Z(),Fo=X(),bm=Wi(),wk=F(),Ak=Ht(),Rk=nm(),lr=um(),Lk=xr(),$k=hm(),Ck=mm(),Dk=z(),Mk=we(),Ok=Dk("replace"),Bk=TypeError,Sm=Fo("".indexOf),Vk=Fo("".replace),gm=Fo("".slice),_k=Math.max,vm=function(i,e,t){return t>i.length?-1:e===""?t:Sm(i,e,t)};Pk({target:"String",proto:!0},{replaceAll:function(e,t){var r=bm(this),a,s,n,o,l,u,c,d,h,p=0,m=0,S="";if(!Ak(e)){if(a=Rk(e),a&&(s=lr(bm($k(e))),!~Sm(s,"g")))throw Bk("`.replaceAll` does not allow non-global regexes");if(n=Lk(e,Ok),n)return kk(n,e,r,t);if(Mk&&a)return Vk(lr(r),e,t)}for(o=lr(r),l=lr(e),u=wk(t),u||(t=lr(t)),c=l.length,d=_k(1,c),p=vm(o,l,0);p!==-1;)h=u?lr(t(l,p,o)):Ck(l,o,p,[],void 0,t),S+=gm(o,m,p)+h,m=p+c,p=vm(o,l,p+d);return m<o.length&&(S+=gm(o,m)),S}})});var Im=f((GO,Tm)=>{"use strict";im();am();ym();var Nk=Ca();Tm.exports=Nk("String","replaceAll")});var xm=f((YO,Em)=>{"use strict";var Fk=Im();Em.exports=Fk});var km=f((WO,Pm)=>{"use strict";var qk=xm();Pm.exports=qk});var vu="__VERSION__";var le=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(le||{}),gt=(g=>(g.MPEG="MPEG",g.DASH="DASH_SEP",g.DASH_SEP="DASH_SEP",g.DASH_SEP_VK="DASH_SEP",g.DASH_WEBM="DASH_WEBM",g.DASH_WEBM_AV1="DASH_WEBM_AV1",g.DASH_WEBM_VK="DASH_WEBM",g.DASH_ONDEMAND="DASH_ONDEMAND",g.DASH_ONDEMAND_VK="DASH_ONDEMAND",g.DASH_LIVE="DASH_LIVE",g.DASH_LIVE_CMAF="DASH_LIVE_CMAF",g.DASH_LIVE_WEBM="DASH_LIVE_WEBM",g.HLS="HLS",g.HLS_ONDEMAND="HLS_ONDEMAND",g.HLS_JS="HLS",g.HLS_LIVE="HLS_LIVE",g.HLS_LIVE_CMAF="HLS_LIVE_CMAF",g.WEB_RTC_LIVE="WEB_RTC_LIVE",g))(gt||{});var ji=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(ji||{}),Es=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Es||{});var xs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(xs||{});import{assertNever as xu,assertNonNullable as og,isNonNullable as Gi,ValueSubject as Ps,Subject as ug,Subscription as lg,merge as cg,observableFrom as dg,fromEvent as yu,map as Tu,tap as Iu,filterChanged as pg,isNullable as ks,ErrorCategory as Eu}from"@vkontakte/videoplayer-shared";var Su=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Yi=class{constructor(e){this.connection$=new Ps(void 0);this.castState$=new Ps("NOT_AVAILABLE");this.errorEvent$=new ug;this.realCastState$=new Ps("NOT_AVAILABLE");this.subscription=new lg;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=Gi(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Su("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Eu.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Gi(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();ks(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();ks(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(yu(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media.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 xu(a.sessionState)}})).add(cg(yu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Iu(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Tu(a=>a.castState)),dg([r.getCastState()])).pipe(pg(),Tu(hg),Iu(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Gi(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();og(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;(ks(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Gi(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Eu.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},hg=i=>{switch(i){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 xu(i)}};var Db=Oe(Ta(),1);var uf=Oe(Da(),1);import{assertNever as Xh}from"@vkontakte/videoplayer-shared";var K=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Xh(t)}return i},ho=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:Xh(e)}};var T=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as kx,Subject as Ma,merge as Zh}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Ma;this.transitionEnded$=new Ma;this.transitionUpdated$=new Ma;this.forceChanged$=new Ma;this.stateChangeStarted$=Zh(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Zh(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||kx(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 wx}from"@vkontakte/videoplayer-shared";var ef=i=>{switch(i){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":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 wx(i)}};import{assertNever as ir,assertNonNullable as kt,debounce as tf,ErrorCategory as rf,fromEvent as wt,isNonNullable as af,map as sf,merge as nf,observableFrom as Ax,Subject as Rx,Subscription as fo,timeout as Lx,getHighestQuality as $x}from"@vkontakte/videoplayer-shared";var Cx=5,Dx=5,Mx=500,of=7e3,Nr=class{constructor(e){this.subscription=new fo;this.loadMediaTimeoutSubscription=new fo;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=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(a?.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:ir(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:ir(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:ir(e)}break}default:ir(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ef(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 fo;this.subscription.add(e),this.subscription.add(nf(this.videoState.stateChangeStarted$.pipe(sf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(sf(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new Rx;e.add(a.pipe(tf(Mx)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(wt(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)>Cx)&&a.next(o),s=o})),e.add(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Dx&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:ir(n)}}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=nf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ax(["init"])).pipe(tf(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"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(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();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&T(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??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){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];kt(u);let c=$x(Object.keys(u));kt(c);let d=u[c];kt(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];kt(u),r=u.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let u=t[e];kt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];kt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];kt(u),r=K(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:rf.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return ir(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:l}=this.params.meta;return af(o)&&(n.metadata.title=o),af(l)&&(n.metadata.subtitle=l),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((a,s)=>{this.loadMediaTimeoutSubscription.add(Lx(of).subscribe(()=>s(`timeout(${of})`)))});(0,uf.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()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:rf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Fr=i=>{i.removeAttribute("src"),i.load()};var lf=i=>{try{i.pause(),i.playbackRate=0,Fr(i),i.remove()}catch(e){console.error(e)}};var mo=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)}},bo=window.WeakMap?new WeakMap:new mo,ee=i=>{let e=i.querySelector("video"),t=!!e;return e?Fr(e):(e=document.createElement("video"),i.appendChild(e)),bo.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},te=i=>{let e=bo.get(i);bo.delete(i),e?Fr(i):lf(i)};import{assertNonNullable as qr,isNonNullable as Ne,isNullable as Vx,fromEvent as ar,merge as cf,observableFrom as df,filterChanged as pf,map as Ur,Subject as hf,Subscription as _x,ValueSubject as Nx,ErrorCategory as Fx}from"@vkontakte/videoplayer-shared";import{isNonNullable as go,isNullable as Ox,Subscription as Bx}from"@vkontakte/videoplayer-shared";var Oa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=Ox(a),u=new Bx;return a&&u.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),l&&i.setState(c.to)},s)),u},_e=(i,e,t)=>Oa(e,()=>i.loop,r=>{go(r)&&(i.loop=r)},{onError:t}),re=(i,e,t,r)=>Oa(e,()=>({muted:i.muted,volume:i.volume}),a=>{go(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),me=(i,e,t,r)=>Oa(e,()=>i.playbackRate,a=>{go(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),at=Oa;var qx=i=>["__",i.language,i.label].join("|"),Ux=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},vo=class i{constructor(){this.available$=new hf;this.current$=new Nx(void 0);this.error$=new hf;this.subscription=new _x;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:Fx.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(at(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ne(s)&&this.setInternal(s)},{equal:(s,n)=>Ne(s)&&Ne(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(Ur(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(at(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ne(s)&&this.setExternal(s)},{equal:(s,n)=>Ne(s)&&Ne(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(Ur(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(at(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:a})),this.subscription.add(at(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qr(this.video);let{textTracks:e}=this.video;this.subscription.add(ar(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(cf(ar(e,"addtrack"),ar(e,"removetrack"),df(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),pf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(cf(ar(e,"change"),df(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ur(r=>r&&this.htmlTextTrackToITextTrack(r).id),pf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(ar(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(ar(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;Ne(t.align)&&(a.align=t.align),Ne(t.position)&&(a.position=t.position),Ne(t.size)&&(a.size=t.size),Ne(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){qr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:qx(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.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:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){qr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Vx(e)||!Ux(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){qr(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){qr(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)}},be=vo;var Ye=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 ff=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},So=i=>{let e=ff(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},mf=i=>{let e=ff(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as ge,map as st,merge as gf,filterChanged as jx,isNonNullable as vf,Subject as Gx,filter as Sf,mapTo as yf,combine as Yx,once as Wx,ErrorCategory as Qx,ValueSubject as Tf,getCurrentBrowser as zx,CurrentClientBrowser as Kx}from"@vkontakte/videoplayer-shared";var Hx=3,bf=(i,e,t=Hx)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let l=s-1;l>=0;l--)i.end(l)+t>=r&&(r=i.start(l));for(let l=s+1;l<i.length;l++)i.start(l)-t<=a&&(a=i.end(l))}}return{from:r,to:a}};var ie=i=>{let e=w=>ge(i,w).pipe(yf(void 0)),r=gf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>ge(i,w))).pipe(st(w=>w.type==="ended"?i.readyState<2:i.readyState<3),jx()),a=gf(ge(i,"progress"),ge(i,"timeupdate")).pipe(st(()=>bf(i.buffered,i.currentTime))),n=zx().browser===Kx.Safari?Yx({play:e("play").pipe(Wx()),playing:e("playing")}).pipe(yf(void 0)):e("playing"),o=ge(i,"volumechange").pipe(st(()=>({muted:i.muted,volume:i.volume}))),l=ge(i,"ratechange").pipe(st(()=>i.playbackRate)),u=ge(i,"error").pipe(Sf(()=>!!(i.error||i.played.length)),st(()=>{let w=i.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:Qx.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:i.error??void 0}})),c=ge(i,"timeupdate").pipe(st(()=>i.currentTime)),d=new Gx,h=.3,p;c.subscribe(w=>{i.loop&&vf(p)&&vf(w)&&p>=i.duration-h&&w<=h&&d.next(p),p=w});let m=ge(i,"enterpictureinpicture"),S=ge(i,"leavepictureinpicture"),b=new Tf(mf(i));m.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));let v=new Tf(So(i));return ge(i,"fullscreenchange").pipe(st(()=>So(i))).subscribe(v),{playing$:n,pause$:e("pause").pipe(Sf(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:ge(i,"durationchange").pipe(st(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:b,inFullscreen$:v}};import{VideoQuality as nt}from"@vkontakte/videoplayer-shared";var ot=i=>{switch(i){case"mobile":return nt.Q_144P;case"lowest":return nt.Q_240P;case"low":return nt.Q_360P;case"sd":case"medium":return nt.Q_480P;case"hd":case"high":return nt.Q_720P;case"fullhd":case"full":return nt.Q_1080P;case"quadhd":case"quad":return nt.Q_1440P;case"ultrahd":case"ultra":return nt.Q_2160P}};var xo=Oe(Ba(),1);import{isNonNullable as ut,isNullable as To,now as Df,isHigher as Io,isHigherOrEqual as $f,isInvariantQuality as Cf,isLower as Eo,isLowerOrEqual as sP,videoSizeToQuality as nP,assertNotEmptyArray as oP}from"@vkontakte/videoplayer-shared";var yo=!1,We={},Af=i=>{yo=i},Rf=()=>{We={}},Lf=i=>{i(We)},Hr=(i,e)=>{yo&&(We.meta=We.meta??{},We.meta[i]=e)},J=class{constructor(e){this.name=e}next(e){if(!yo)return;We.series=We.series??{};let t=We.series[this.name]??[];t.push([Date.now(),e]),We.series[this.name]=t}};var uP=new J("best_bitrate"),lP=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Va=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Df()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},cP='Assertion "ABR Tracks is empty array" failed',dP=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{oP(i,cP);let h=r.usePixelRatio?window.devicePixelRatio??1:1,p=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},m=p&&nP(p),S=r.considerPlaybackRate&&ut(o)?o:1,b=i.filter(E=>!Cf(E.quality)).sort((E,x)=>Io(E.quality,x.quality)?-1:1),v=(0,xo.default)(b,-1)?.quality,g=(0,xo.default)(b,0)?.quality,w=To(a)||ut(a.min)&&ut(a.max)&&Eo(a.max,a.min)||ut(a.min)&&g&&Io(a.min,g)||ut(a.max)&&v&&Eo(a.max,v),y=S*lP(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),I={},$=b.filter(E=>(m?Eo(E.quality,m):!0)?(ut(t)&&isFinite(t)&&ut(E.bitrate)?t-s>=E.bitrate*y:!0)?r.lazyQualitySwitch&&ut(r.minBufferToSwitchUp)&&l&&!Cf(l.quality)&&(n??0)<r.minBufferToSwitchUp&&Io(E.quality,l.quality)?(I[E.quality]="Buffer",!1):!!c&&$f(E.quality,c)?(I[E.quality]="DroppedFramesLimit",!1):w||(To(a.max)||sP(E.quality,a.max))&&(To(a.min)||$f(E.quality,a.min))?!0:(I[E.quality]="FitsQualityLimits",!1):(I[E.quality]="FitsThroughput",!1):(I[E.quality]="FitsContainer",!1))[0];$&&$.bitrate&&uP.next($.bitrate);let A=$??b[Math.ceil((b.length-1)/2)]??i[0];A.quality!==u?.last?.quality&&d({message:`
6
+ var sv=Object.create;var Tu=Object.defineProperty;var nv=Object.getOwnPropertyDescriptor;var ov=Object.getOwnPropertyNames;var uv=Object.getPrototypeOf,lv=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var cv=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ov(e))!lv.call(i,a)&&a!==t&&Tu(i,a,{get:()=>e[a],enumerable:!(r=nv(e,a))||r.enumerable});return i};var Oe=(i,e,t)=>(t=i!=null?sv(uv(i)):{},cv(e||!i||!i.__esModule?Tu(t,"default",{value:i,enumerable:!0}):t,i));var ce=f((dR,Ru)=>{"use strict";Ru.exports=function(i){try{return!!i()}catch{return!0}}});var Tr=f((pR,Lu)=>{"use strict";var gv=ce();Lu.exports=!gv(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var X=f((hR,Du)=>{"use strict";var $u=Tr(),Cu=Function.prototype,Ls=Cu.call,Sv=$u&&Cu.bind.bind(Ls,Ls);Du.exports=$u?Sv:function(i){return function(){return Ls.apply(i,arguments)}}});var Ut=f((fR,Ou)=>{"use strict";var Mu=X(),yv=Mu({}.toString),Tv=Mu("".slice);Ou.exports=function(i){return Tv(yv(i),8,-1)}});var Vu=f((mR,Bu)=>{"use strict";var Iv=X(),Ev=ce(),xv=Ut(),$s=Object,Pv=Iv("".split);Bu.exports=Ev(function(){return!$s("z").propertyIsEnumerable(0)})?function(i){return xv(i)=="String"?Pv(i,""):$s(i)}:$s});var Ht=f((bR,_u)=>{"use strict";_u.exports=function(i){return i==null}});var zi=f((vR,Nu)=>{"use strict";var kv=Ht(),wv=TypeError;Nu.exports=function(i){if(kv(i))throw wv("Can't call method on "+i);return i}});var jt=f((gR,Fu)=>{"use strict";var Av=Vu(),Rv=zi();Fu.exports=function(i){return Av(Rv(i))}});var Cs=f((SR,qu)=>{"use strict";qu.exports=function(){}});var gt=f((yR,Uu)=>{"use strict";Uu.exports={}});var G=f((Hu,ju)=>{"use strict";var Ki=function(i){return i&&i.Math==Math&&i};ju.exports=Ki(typeof globalThis=="object"&&globalThis)||Ki(typeof window=="object"&&window)||Ki(typeof self=="object"&&self)||Ki(typeof global=="object"&&global)||function(){return this}()||Hu||Function("return this")()});var Ms=f((TR,Gu)=>{"use strict";var Ds=typeof document=="object"&&document.all,Lv=typeof Ds>"u"&&Ds!==void 0;Gu.exports={all:Ds,IS_HTMLDDA:Lv}});var F=f((IR,Wu)=>{"use strict";var Yu=Ms(),$v=Yu.all;Wu.exports=Yu.IS_HTMLDDA?function(i){return typeof i=="function"||i===$v}:function(i){return typeof i=="function"}});var Ku=f((ER,zu)=>{"use strict";var Cv=G(),Dv=F(),Qu=Cv.WeakMap;zu.exports=Dv(Qu)&&/native code/.test(String(Qu))});var Be=f((xR,Zu)=>{"use strict";var Ju=F(),Xu=Ms(),Mv=Xu.all;Zu.exports=Xu.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Ju(i)||i===Mv}:function(i){return typeof i=="object"?i!==null:Ju(i)}});var Ve=f((PR,el)=>{"use strict";var Ov=ce();el.exports=!Ov(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var Ji=f((kR,rl)=>{"use strict";var Bv=G(),tl=Be(),Os=Bv.document,Vv=tl(Os)&&tl(Os.createElement);rl.exports=function(i){return Vv?Os.createElement(i):{}}});var Bs=f((wR,il)=>{"use strict";var _v=Ve(),Nv=ce(),Fv=Ji();il.exports=!_v&&!Nv(function(){return Object.defineProperty(Fv("div"),"a",{get:function(){return 7}}).a!=7})});var Vs=f((AR,al)=>{"use strict";var qv=Ve(),Uv=ce();al.exports=qv&&Uv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Pe=f((RR,sl)=>{"use strict";var Hv=Be(),jv=String,Gv=TypeError;sl.exports=function(i){if(Hv(i))return i;throw Gv(jv(i)+" is not an object")}});var Z=f((LR,nl)=>{"use strict";var Yv=Tr(),Xi=Function.prototype.call;nl.exports=Yv?Xi.bind(Xi):function(){return Xi.apply(Xi,arguments)}});var Zi=f(($R,ol)=>{"use strict";ol.exports={}});var Ue=f((CR,ll)=>{"use strict";var _s=Zi(),Ns=G(),Wv=F(),ul=function(i){return Wv(i)?i:void 0};ll.exports=function(i,e){return arguments.length<2?ul(_s[i])||ul(Ns[i]):_s[i]&&_s[i][e]||Ns[i]&&Ns[i][e]}});var Ir=f((DR,cl)=>{"use strict";var Qv=X();cl.exports=Qv({}.isPrototypeOf)});var Er=f((MR,dl)=>{"use strict";dl.exports=typeof navigator<"u"&&String(navigator.userAgent)||""});var qs=f((OR,vl)=>{"use strict";var bl=G(),Fs=Er(),pl=bl.process,hl=bl.Deno,fl=pl&&pl.versions||hl&&hl.version,ml=fl&&fl.v8,ke,ea;ml&&(ke=ml.split("."),ea=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!ea&&Fs&&(ke=Fs.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Fs.match(/Chrome\/(\d+)/),ke&&(ea=+ke[1])));vl.exports=ea});var Us=f((BR,Sl)=>{"use strict";var gl=qs(),zv=ce(),Kv=G(),Jv=Kv.String;Sl.exports=!!Object.getOwnPropertySymbols&&!zv(function(){var i=Symbol();return!Jv(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&gl&&gl<41})});var Hs=f((VR,yl)=>{"use strict";var Xv=Us();yl.exports=Xv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var js=f((_R,Tl)=>{"use strict";var Zv=Ue(),eg=F(),tg=Ir(),rg=Hs(),ig=Object;Tl.exports=rg?function(i){return typeof i=="symbol"}:function(i){var e=Zv("Symbol");return eg(e)&&tg(e.prototype,ig(i))}});var xr=f((NR,Il)=>{"use strict";var ag=String;Il.exports=function(i){try{return ag(i)}catch{return"Object"}}});var He=f((FR,El)=>{"use strict";var sg=F(),ng=xr(),og=TypeError;El.exports=function(i){if(sg(i))return i;throw og(ng(i)+" is not a function")}});var Pr=f((qR,xl)=>{"use strict";var ug=He(),lg=Ht();xl.exports=function(i,e){var t=i[e];return lg(t)?void 0:ug(t)}});var kl=f((UR,Pl)=>{"use strict";var Gs=Z(),Ys=F(),Ws=Be(),cg=TypeError;Pl.exports=function(i,e){var t,r;if(e==="string"&&Ys(t=i.toString)&&!Ws(r=Gs(t,i))||Ys(t=i.valueOf)&&!Ws(r=Gs(t,i))||e!=="string"&&Ys(t=i.toString)&&!Ws(r=Gs(t,i)))return r;throw cg("Can't convert object to primitive value")}});var we=f((HR,wl)=>{"use strict";wl.exports=!0});var Ll=f((jR,Rl)=>{"use strict";var Al=G(),dg=Object.defineProperty;Rl.exports=function(i,e){try{dg(Al,i,{value:e,configurable:!0,writable:!0})}catch{Al[i]=e}return e}});var ta=f((GR,Cl)=>{"use strict";var pg=G(),hg=Ll(),$l="__core-js_shared__",fg=pg[$l]||hg($l,{});Cl.exports=fg});var Qs=f((YR,Ml)=>{"use strict";var mg=we(),Dl=ta();(Ml.exports=function(i,e){return Dl[i]||(Dl[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:mg?"pure":"global",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var kr=f((WR,Ol)=>{"use strict";var bg=zi(),vg=Object;Ol.exports=function(i){return vg(bg(i))}});var Ae=f((QR,Bl)=>{"use strict";var gg=X(),Sg=kr(),yg=gg({}.hasOwnProperty);Bl.exports=Object.hasOwn||function(e,t){return yg(Sg(e),t)}});var zs=f((zR,Vl)=>{"use strict";var Tg=X(),Ig=0,Eg=Math.random(),xg=Tg(1 .toString);Vl.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+xg(++Ig+Eg,36)}});var z=f((KR,Nl)=>{"use strict";var Pg=G(),kg=Qs(),_l=Ae(),wg=zs(),Ag=Us(),Rg=Hs(),Gt=Pg.Symbol,Ks=kg("wks"),Lg=Rg?Gt.for||Gt:Gt&&Gt.withoutSetter||wg;Nl.exports=function(i){return _l(Ks,i)||(Ks[i]=Ag&&_l(Gt,i)?Gt[i]:Lg("Symbol."+i)),Ks[i]}});var Hl=f((JR,Ul)=>{"use strict";var $g=Z(),Fl=Be(),ql=js(),Cg=Pr(),Dg=kl(),Mg=z(),Og=TypeError,Bg=Mg("toPrimitive");Ul.exports=function(i,e){if(!Fl(i)||ql(i))return i;var t=Cg(i,Bg),r;if(t){if(e===void 0&&(e="default"),r=$g(t,i,e),!Fl(r)||ql(r))return r;throw Og("Can't convert object to primitive value")}return e===void 0&&(e="number"),Dg(i,e)}});var ra=f((XR,jl)=>{"use strict";var Vg=Hl(),_g=js();jl.exports=function(i){var e=Vg(i,"string");return _g(e)?e:e+""}});var St=f(Yl=>{"use strict";var Ng=Ve(),Fg=Bs(),qg=Vs(),ia=Pe(),Gl=ra(),Ug=TypeError,Js=Object.defineProperty,Hg=Object.getOwnPropertyDescriptor,Xs="enumerable",Zs="configurable",en="writable";Yl.f=Ng?qg?function(e,t,r){if(ia(e),t=Gl(t),ia(r),typeof e=="function"&&t==="prototype"&&"value"in r&&en in r&&!r[en]){var a=Hg(e,t);a&&a[en]&&(e[t]=r.value,r={configurable:Zs in r?r[Zs]:a[Zs],enumerable:Xs in r?r[Xs]:a[Xs],writable:!1})}return Js(e,t,r)}:Js:function(e,t,r){if(ia(e),t=Gl(t),ia(r),Fg)try{return Js(e,t,r)}catch{}if("get"in r||"set"in r)throw Ug("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var wr=f((eL,Wl)=>{"use strict";Wl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var yt=f((tL,Ql)=>{"use strict";var jg=Ve(),Gg=St(),Yg=wr();Ql.exports=jg?function(i,e,t){return Gg.f(i,e,Yg(1,t))}:function(i,e,t){return i[e]=t,i}});var aa=f((rL,Kl)=>{"use strict";var Wg=Qs(),Qg=zs(),zl=Wg("keys");Kl.exports=function(i){return zl[i]||(zl[i]=Qg(i))}});var sa=f((iL,Jl)=>{"use strict";Jl.exports={}});var sn=f((aL,ec)=>{"use strict";var zg=Ku(),Zl=G(),Kg=Be(),Jg=yt(),tn=Ae(),rn=ta(),Xg=aa(),Zg=sa(),Xl="Object already initialized",an=Zl.TypeError,eS=Zl.WeakMap,na,Ar,oa,tS=function(i){return oa(i)?Ar(i):na(i,{})},rS=function(i){return function(e){var t;if(!Kg(e)||(t=Ar(e)).type!==i)throw an("Incompatible receiver, "+i+" required");return t}};zg||rn.state?(Re=rn.state||(rn.state=new eS),Re.get=Re.get,Re.has=Re.has,Re.set=Re.set,na=function(i,e){if(Re.has(i))throw an(Xl);return e.facade=i,Re.set(i,e),e},Ar=function(i){return Re.get(i)||{}},oa=function(i){return Re.has(i)}):(Tt=Xg("state"),Zg[Tt]=!0,na=function(i,e){if(tn(i,Tt))throw an(Xl);return e.facade=i,Jg(i,Tt,e),e},Ar=function(i){return tn(i,Tt)?i[Tt]:{}},oa=function(i){return tn(i,Tt)});var Re,Tt;ec.exports={set:na,get:Ar,has:oa,enforce:tS,getterFor:rS}});var nn=f((sL,ac)=>{"use strict";var iS=Tr(),ic=Function.prototype,tc=ic.apply,rc=ic.call;ac.exports=typeof Reflect=="object"&&Reflect.apply||(iS?rc.bind(tc):function(){return rc.apply(tc,arguments)})});var on=f((nL,sc)=>{"use strict";var aS=Ut(),sS=X();sc.exports=function(i){if(aS(i)==="Function")return sS(i)}});var lc=f(uc=>{"use strict";var nc={}.propertyIsEnumerable,oc=Object.getOwnPropertyDescriptor,nS=oc&&!nc.call({1:2},1);uc.f=nS?function(e){var t=oc(this,e);return!!t&&t.enumerable}:nc});var un=f(dc=>{"use strict";var oS=Ve(),uS=Z(),lS=lc(),cS=wr(),dS=jt(),pS=ra(),hS=Ae(),fS=Bs(),cc=Object.getOwnPropertyDescriptor;dc.f=oS?cc:function(e,t){if(e=dS(e),t=pS(t),fS)try{return cc(e,t)}catch{}if(hS(e,t))return cS(!uS(lS.f,e,t),e[t])}});var ln=f((lL,pc)=>{"use strict";var mS=ce(),bS=F(),vS=/#|\.prototype\./,Rr=function(i,e){var t=SS[gS(i)];return t==TS?!0:t==yS?!1:bS(e)?mS(e):!!e},gS=Rr.normalize=function(i){return String(i).replace(vS,".").toLowerCase()},SS=Rr.data={},yS=Rr.NATIVE="N",TS=Rr.POLYFILL="P";pc.exports=Rr});var Lr=f((cL,fc)=>{"use strict";var hc=on(),IS=He(),ES=Tr(),xS=hc(hc.bind);fc.exports=function(i,e){return IS(i),e===void 0?i:ES?xS(i,e):function(){return i.apply(e,arguments)}}});var fe=f((dL,bc)=>{"use strict";var ua=G(),PS=nn(),kS=on(),wS=F(),AS=un().f,RS=ln(),Yt=Zi(),LS=Lr(),Wt=yt(),mc=Ae(),$S=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return PS(i,this,arguments)};return e.prototype=i.prototype,e};bc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?ua:a?ua[t]:(ua[t]||{}).prototype,o=r?Yt:Yt[t]||Wt(Yt,t,{})[t],l=o.prototype,u,c,d,h,p,m,S,b,g;for(h in e)u=RS(r?h:t+(a?".":"#")+h,i.forced),c=!u&&n&&mc(n,h),m=o[h],c&&(i.dontCallGetSet?(g=AS(n,h),S=g&&g.value):S=n[h]),p=c&&S?S:e[h],!(c&&typeof m==typeof p)&&(i.bind&&c?b=LS(p,ua):i.wrap&&c?b=$S(p):s&&wS(p)?b=kS(p):b=p,(i.sham||p&&p.sham||m&&m.sham)&&Wt(b,"sham",!0),Wt(o,h,b),s&&(d=t+"Prototype",mc(Yt,d)||Wt(Yt,d,{}),Wt(Yt[d],h,p),i.real&&l&&(u||!l[h])&&Wt(l,h,p)))}});var Sc=f((pL,gc)=>{"use strict";var cn=Ve(),CS=Ae(),vc=Function.prototype,DS=cn&&Object.getOwnPropertyDescriptor,dn=CS(vc,"name"),MS=dn&&function(){}.name==="something",OS=dn&&(!cn||cn&&DS(vc,"name").configurable);gc.exports={EXISTS:dn,PROPER:MS,CONFIGURABLE:OS}});var Tc=f((hL,yc)=>{"use strict";var BS=Math.ceil,VS=Math.floor;yc.exports=Math.trunc||function(e){var t=+e;return(t>0?VS:BS)(t)}});var la=f((fL,Ic)=>{"use strict";var _S=Tc();Ic.exports=function(i){var e=+i;return e!==e||e===0?0:_S(e)}});var xc=f((mL,Ec)=>{"use strict";var NS=la(),FS=Math.max,qS=Math.min;Ec.exports=function(i,e){var t=NS(i);return t<0?FS(t+e,0):qS(t,e)}});var kc=f((bL,Pc)=>{"use strict";var US=la(),HS=Math.min;Pc.exports=function(i){return i>0?HS(US(i),9007199254740991):0}});var ca=f((vL,wc)=>{"use strict";var jS=kc();wc.exports=function(i){return jS(i.length)}});var Lc=f((gL,Rc)=>{"use strict";var GS=jt(),YS=xc(),WS=ca(),Ac=function(i){return function(e,t,r){var a=GS(e),s=WS(a),n=YS(r,s),o;if(i&&t!=t){for(;s>n;)if(o=a[n++],o!=o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};Rc.exports={includes:Ac(!0),indexOf:Ac(!1)}});var Dc=f((SL,Cc)=>{"use strict";var QS=X(),pn=Ae(),zS=jt(),KS=Lc().indexOf,JS=sa(),$c=QS([].push);Cc.exports=function(i,e){var t=zS(i),r=0,a=[],s;for(s in t)!pn(JS,s)&&pn(t,s)&&$c(a,s);for(;e.length>r;)pn(t,s=e[r++])&&(~KS(a,s)||$c(a,s));return a}});var hn=f((yL,Mc)=>{"use strict";Mc.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Bc=f((TL,Oc)=>{"use strict";var XS=Dc(),ZS=hn();Oc.exports=Object.keys||function(e){return XS(e,ZS)}});var _c=f(Vc=>{"use strict";var ey=Ve(),ty=Vs(),ry=St(),iy=Pe(),ay=jt(),sy=Bc();Vc.f=ey&&!ty?Object.defineProperties:function(e,t){iy(e);for(var r=ay(t),a=sy(t),s=a.length,n=0,o;s>n;)ry.f(e,o=a[n++],r[o]);return e}});var fn=f((EL,Nc)=>{"use strict";var ny=Ue();Nc.exports=ny("document","documentElement")});var gn=f((xL,Yc)=>{"use strict";var oy=Pe(),uy=_c(),Fc=hn(),ly=sa(),cy=fn(),dy=Ji(),py=aa(),qc=">",Uc="<",bn="prototype",vn="script",jc=py("IE_PROTO"),mn=function(){},Gc=function(i){return Uc+vn+qc+i+Uc+"/"+vn+qc},Hc=function(i){i.write(Gc("")),i.close();var e=i.parentWindow.Object;return i=null,e},hy=function(){var i=dy("iframe"),e="java"+vn+":",t;return i.style.display="none",cy.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Gc("document.F=Object")),t.close(),t.F},da,pa=function(){try{da=new ActiveXObject("htmlfile")}catch{}pa=typeof document<"u"?document.domain&&da?Hc(da):hy():Hc(da);for(var i=Fc.length;i--;)delete pa[bn][Fc[i]];return pa()};ly[jc]=!0;Yc.exports=Object.create||function(e,t){var r;return e!==null?(mn[bn]=oy(e),r=new mn,mn[bn]=null,r[jc]=e):r=pa(),t===void 0?r:uy.f(r,t)}});var Qc=f((PL,Wc)=>{"use strict";var fy=ce();Wc.exports=!fy(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var yn=f((kL,Kc)=>{"use strict";var my=Ae(),by=F(),vy=kr(),gy=aa(),Sy=Qc(),zc=gy("IE_PROTO"),Sn=Object,yy=Sn.prototype;Kc.exports=Sy?Sn.getPrototypeOf:function(i){var e=vy(i);if(my(e,zc))return e[zc];var t=e.constructor;return by(t)&&e instanceof t?t.prototype:e instanceof Sn?yy:null}});var Qt=f((wL,Jc)=>{"use strict";var Ty=yt();Jc.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Ty(i,e,t),i}});var xn=f((AL,ed)=>{"use strict";var Iy=ce(),Ey=F(),xy=Be(),Py=gn(),Xc=yn(),ky=Qt(),wy=z(),Ay=we(),En=wy("iterator"),Zc=!1,je,Tn,In;[].keys&&(In=[].keys(),"next"in In?(Tn=Xc(Xc(In)),Tn!==Object.prototype&&(je=Tn)):Zc=!0);var Ry=!xy(je)||Iy(function(){var i={};return je[En].call(i)!==i});Ry?je={}:Ay&&(je=Py(je));Ey(je[En])||ky(je,En,function(){return this});ed.exports={IteratorPrototype:je,BUGGY_SAFARI_ITERATORS:Zc}});var ha=f((RL,rd)=>{"use strict";var Ly=z(),$y=Ly("toStringTag"),td={};td[$y]="z";rd.exports=String(td)==="[object z]"});var zt=f((LL,id)=>{"use strict";var Cy=ha(),Dy=F(),fa=Ut(),My=z(),Oy=My("toStringTag"),By=Object,Vy=fa(function(){return arguments}())=="Arguments",_y=function(i,e){try{return i[e]}catch{}};id.exports=Cy?fa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=_y(e=By(i),Oy))=="string"?t:Vy?fa(e):(r=fa(e))=="Object"&&Dy(e.callee)?"Arguments":r}});var sd=f(($L,ad)=>{"use strict";var Ny=ha(),Fy=zt();ad.exports=Ny?{}.toString:function(){return"[object "+Fy(this)+"]"}});var ma=f((CL,od)=>{"use strict";var qy=ha(),Uy=St().f,Hy=yt(),jy=Ae(),Gy=sd(),Yy=z(),nd=Yy("toStringTag");od.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;jy(a,nd)||Uy(a,nd,{configurable:!0,value:e}),r&&!qy&&Hy(a,"toString",Gy)}}});var ld=f((DL,ud)=>{"use strict";var Wy=xn().IteratorPrototype,Qy=gn(),zy=wr(),Ky=ma(),Jy=gt(),Xy=function(){return this};ud.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=Qy(Wy,{next:zy(+!r,t)}),Ky(i,a,!1,!0),Jy[a]=Xy,i}});var dd=f((ML,cd)=>{"use strict";var Zy=X(),eT=He();cd.exports=function(i,e,t){try{return Zy(eT(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var hd=f((OL,pd)=>{"use strict";var tT=F(),rT=String,iT=TypeError;pd.exports=function(i){if(typeof i=="object"||tT(i))return i;throw iT("Can't set "+rT(i)+" as a prototype")}});var Pn=f((BL,fd)=>{"use strict";var aT=dd(),sT=Pe(),nT=hd();fd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=aT(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return sT(a),nT(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var Pd=f((VL,xd)=>{"use strict";var oT=fe(),uT=Z(),ba=we(),Id=Sc(),lT=F(),cT=ld(),md=yn(),bd=Pn(),dT=ma(),pT=yt(),kn=Qt(),hT=z(),vd=gt(),Ed=xn(),fT=Id.PROPER,mT=Id.CONFIGURABLE,gd=Ed.IteratorPrototype,va=Ed.BUGGY_SAFARI_ITERATORS,$r=hT("iterator"),Sd="keys",Cr="values",yd="entries",Td=function(){return this};xd.exports=function(i,e,t,r,a,s,n){cT(t,e,r);var o=function(g){if(g===a&&h)return h;if(!va&&g in c)return c[g];switch(g){case Sd:return function(){return new t(this,g)};case Cr:return function(){return new t(this,g)};case yd:return function(){return new t(this,g)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[$r]||c["@@iterator"]||a&&c[a],h=!va&&d||o(a),p=e=="Array"&&c.entries||d,m,S,b;if(p&&(m=md(p.call(new i)),m!==Object.prototype&&m.next&&(!ba&&md(m)!==gd&&(bd?bd(m,gd):lT(m[$r])||kn(m,$r,Td)),dT(m,l,!0,!0),ba&&(vd[l]=Td))),fT&&a==Cr&&d&&d.name!==Cr&&(!ba&&mT?pT(c,"name",Cr):(u=!0,h=function(){return uT(d,this)})),a)if(S={values:o(Cr),keys:s?h:o(Sd),entries:o(yd)},n)for(b in S)(va||u||!(b in c))&&kn(c,b,S[b]);else oT({target:e,proto:!0,forced:va||u},S);return(!ba||n)&&c[$r]!==h&&kn(c,$r,h,{name:a}),vd[e]=h,S}});var wd=f((_L,kd)=>{"use strict";kd.exports=function(i,e){return{value:i,done:e}}});var An=f((NL,Cd)=>{"use strict";var bT=jt(),wn=Cs(),Ad=gt(),Ld=sn(),vT=St().f,gT=Pd(),ga=wd(),ST=we(),yT=Ve(),$d="Array Iterator",TT=Ld.set,IT=Ld.getterFor($d);Cd.exports=gT(Array,"Array",function(i,e){TT(this,{type:$d,target:bT(i),index:0,kind:e})},function(){var i=IT(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,ga(void 0,!0)):t=="keys"?ga(r,!1):t=="values"?ga(e[r],!1):ga([r,e[r]],!1)},"values");var Rd=Ad.Arguments=Ad.Array;wn("keys");wn("values");wn("entries");if(!ST&&yT&&Rd.name!=="values")try{vT(Rd,"name",{value:"values"})}catch{}});var Md=f((FL,Dd)=>{"use strict";var ET=z(),xT=gt(),PT=ET("iterator"),kT=Array.prototype;Dd.exports=function(i){return i!==void 0&&(xT.Array===i||kT[PT]===i)}});var Rn=f((qL,Bd)=>{"use strict";var wT=zt(),Od=Pr(),AT=Ht(),RT=gt(),LT=z(),$T=LT("iterator");Bd.exports=function(i){if(!AT(i))return Od(i,$T)||Od(i,"@@iterator")||RT[wT(i)]}});var _d=f((UL,Vd)=>{"use strict";var CT=Z(),DT=He(),MT=Pe(),OT=xr(),BT=Rn(),VT=TypeError;Vd.exports=function(i,e){var t=arguments.length<2?BT(i):e;if(DT(t))return MT(CT(t,i));throw VT(OT(i)+" is not iterable")}});var qd=f((HL,Fd)=>{"use strict";var _T=Z(),Nd=Pe(),NT=Pr();Fd.exports=function(i,e,t){var r,a;Nd(i);try{if(r=NT(i,"return"),!r){if(e==="throw")throw t;return t}r=_T(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Nd(r),t}});var ya=f((jL,Gd)=>{"use strict";var FT=Lr(),qT=Z(),UT=Pe(),HT=xr(),jT=Md(),GT=ca(),Ud=Ir(),YT=_d(),WT=Rn(),Hd=qd(),QT=TypeError,Sa=function(i,e){this.stopped=i,this.result=e},jd=Sa.prototype;Gd.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=FT(e,r),u,c,d,h,p,m,S,b=function(v){return u&&Hd(u,"normal",v),new Sa(!0,v)},g=function(v){return a?(UT(v),o?l(v[0],v[1],b):l(v[0],v[1])):o?l(v,b):l(v)};if(s)u=i.iterator;else if(n)u=i;else{if(c=WT(i),!c)throw QT(HT(i)+" is not iterable");if(jT(c)){for(d=0,h=GT(i);h>d;d++)if(p=g(i[d]),p&&Ud(jd,p))return p;return new Sa(!1)}u=YT(i,c)}for(m=s?i.next:u.next;!(S=qT(m,u)).done;){try{p=g(S.value)}catch(v){Hd(u,"throw",v)}if(typeof p=="object"&&p&&Ud(jd,p))return p}return new Sa(!1)}});var Wd=f((GL,Yd)=>{"use strict";var zT=ra(),KT=St(),JT=wr();Yd.exports=function(i,e,t){var r=zT(e);r in i?KT.f(i,r,JT(0,t)):i[r]=t}});var Qd=f(()=>{"use strict";var XT=fe(),ZT=ya(),eI=Wd();XT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return ZT(e,function(r,a){eI(t,r,a)},{AS_ENTRIES:!0}),t}})});var Kd=f((QL,zd)=>{"use strict";An();Qd();var tI=Zi();zd.exports=tI.Object.fromEntries});var Xd=f((zL,Jd)=>{"use strict";Jd.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 tp=f(()=>{"use strict";An();var rI=Xd(),iI=G(),aI=zt(),sI=yt(),Zd=gt(),nI=z(),ep=nI("toStringTag");for(Ta in rI)Ln=iI[Ta],Ia=Ln&&Ln.prototype,Ia&&aI(Ia)!==ep&&sI(Ia,ep,Ta),Zd[Ta]=Zd.Array;var Ln,Ia,Ta});var ip=f((XL,rp)=>{"use strict";var oI=Kd();tp();rp.exports=oI});var Ea=f((ZL,ap)=>{"use strict";var uI=ip();ap.exports=uI});var sp=f(()=>{"use strict"});var Dr=f((r$,np)=>{"use strict";var lI=Ut();np.exports=typeof process<"u"&&lI(process)=="process"});var up=f((i$,op)=>{"use strict";var cI=St();op.exports=function(i,e,t){return cI.f(i,e,t)}});var dp=f((a$,cp)=>{"use strict";var dI=Ue(),pI=up(),hI=z(),fI=Ve(),lp=hI("species");cp.exports=function(i){var e=dI(i);fI&&e&&!e[lp]&&pI(e,lp,{configurable:!0,get:function(){return this}})}});var hp=f((s$,pp)=>{"use strict";var mI=Ir(),bI=TypeError;pp.exports=function(i,e){if(mI(e,i))return i;throw bI("Incorrect invocation")}});var Cn=f((n$,fp)=>{"use strict";var vI=X(),gI=F(),$n=ta(),SI=vI(Function.toString);gI($n.inspectSource)||($n.inspectSource=function(i){return SI(i)});fp.exports=$n.inspectSource});var yp=f((o$,Sp)=>{"use strict";var yI=X(),TI=ce(),mp=F(),II=zt(),EI=Ue(),xI=Cn(),bp=function(){},PI=[],vp=EI("Reflect","construct"),Dn=/^\s*(?:class|function)\b/,kI=yI(Dn.exec),wI=!Dn.exec(bp),Mr=function(e){if(!mp(e))return!1;try{return vp(bp,PI,e),!0}catch{return!1}},gp=function(e){if(!mp(e))return!1;switch(II(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return wI||!!kI(Dn,xI(e))}catch{return!0}};gp.sham=!0;Sp.exports=!vp||TI(function(){var i;return Mr(Mr.call)||!Mr(Object)||!Mr(function(){i=!0})||i})?gp:Mr});var Ip=f((u$,Tp)=>{"use strict";var AI=yp(),RI=xr(),LI=TypeError;Tp.exports=function(i){if(AI(i))return i;throw LI(RI(i)+" is not a constructor")}});var Mn=f((l$,xp)=>{"use strict";var Ep=Pe(),$I=Ip(),CI=Ht(),DI=z(),MI=DI("species");xp.exports=function(i,e){var t=Ep(i).constructor,r;return t===void 0||CI(r=Ep(t)[MI])?e:$I(r)}});var kp=f((c$,Pp)=>{"use strict";var OI=X();Pp.exports=OI([].slice)});var Ap=f((d$,wp)=>{"use strict";var BI=TypeError;wp.exports=function(i,e){if(i<e)throw BI("Not enough arguments");return i}});var On=f((p$,Rp)=>{"use strict";var VI=Er();Rp.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(VI)});var jn=f((h$,_p)=>{"use strict";var de=G(),_I=nn(),NI=Lr(),Lp=F(),FI=Ae(),Vp=ce(),$p=fn(),qI=kp(),Cp=Ji(),UI=Ap(),HI=On(),jI=Dr(),qn=de.setImmediate,Un=de.clearImmediate,GI=de.process,Bn=de.Dispatch,YI=de.Function,Dp=de.MessageChannel,WI=de.String,Vn=0,Or={},Mp="onreadystatechange",Br,It,_n,Nn;Vp(function(){Br=de.location});var Hn=function(i){if(FI(Or,i)){var e=Or[i];delete Or[i],e()}},Fn=function(i){return function(){Hn(i)}},Op=function(i){Hn(i.data)},Bp=function(i){de.postMessage(WI(i),Br.protocol+"//"+Br.host)};(!qn||!Un)&&(qn=function(e){UI(arguments.length,1);var t=Lp(e)?e:YI(e),r=qI(arguments,1);return Or[++Vn]=function(){_I(t,void 0,r)},It(Vn),Vn},Un=function(e){delete Or[e]},jI?It=function(i){GI.nextTick(Fn(i))}:Bn&&Bn.now?It=function(i){Bn.now(Fn(i))}:Dp&&!HI?(_n=new Dp,Nn=_n.port2,_n.port1.onmessage=Op,It=NI(Nn.postMessage,Nn)):de.addEventListener&&Lp(de.postMessage)&&!de.importScripts&&Br&&Br.protocol!=="file:"&&!Vp(Bp)?(It=Bp,de.addEventListener("message",Op,!1)):Mp in Cp("script")?It=function(i){$p.appendChild(Cp("script"))[Mp]=function(){$p.removeChild(this),Hn(i)}}:It=function(i){setTimeout(Fn(i),0)});_p.exports={set:qn,clear:Un}});var Gn=f((f$,Fp)=>{"use strict";var Np=function(){this.head=null,this.tail=null};Np.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};Fp.exports=Np});var Up=f((m$,qp)=>{"use strict";var QI=Er();qp.exports=/ipad|iphone|ipod/i.test(QI)&&typeof Pebble<"u"});var jp=f((b$,Hp)=>{"use strict";var zI=Er();Hp.exports=/web0s(?!.*chrome)/i.test(zI)});var Xp=f((v$,Jp)=>{"use strict";var Et=G(),Gp=Lr(),KI=un().f,Yn=jn().set,JI=Gn(),XI=On(),ZI=Up(),eE=jp(),Wn=Dr(),Yp=Et.MutationObserver||Et.WebKitMutationObserver,Wp=Et.document,Qp=Et.process,xa=Et.Promise,zp=KI(Et,"queueMicrotask"),Kn=zp&&zp.value,Kt,Qn,zn,Pa,Kp;Kn||(Vr=new JI,_r=function(){var i,e;for(Wn&&(i=Qp.domain)&&i.exit();e=Vr.get();)try{e()}catch(t){throw Vr.head&&Kt(),t}i&&i.enter()},!XI&&!Wn&&!eE&&Yp&&Wp?(Qn=!0,zn=Wp.createTextNode(""),new Yp(_r).observe(zn,{characterData:!0}),Kt=function(){zn.data=Qn=!Qn}):!ZI&&xa&&xa.resolve?(Pa=xa.resolve(void 0),Pa.constructor=xa,Kp=Gp(Pa.then,Pa),Kt=function(){Kp(_r)}):Wn?Kt=function(){Qp.nextTick(_r)}:(Yn=Gp(Yn,Et),Kt=function(){Yn(_r)}),Kn=function(i){Vr.head||Kt(),Vr.add(i)});var Vr,_r;Jp.exports=Kn});var eh=f((g$,Zp)=>{"use strict";Zp.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch{}}});var ka=f((S$,th)=>{"use strict";th.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var xt=f((y$,rh)=>{"use strict";var tE=G();rh.exports=tE.Promise});var Jn=f((T$,ih)=>{"use strict";ih.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var sh=f((I$,ah)=>{"use strict";var rE=Jn(),iE=Dr();ah.exports=!rE&&!iE&&typeof window=="object"&&typeof document=="object"});var Jt=f((E$,uh)=>{"use strict";var aE=G(),Nr=xt(),sE=F(),nE=ln(),oE=Cn(),uE=z(),lE=sh(),cE=Jn(),dE=we(),Xn=qs(),nh=Nr&&Nr.prototype,pE=uE("species"),Zn=!1,oh=sE(aE.PromiseRejectionEvent),hE=nE("Promise",function(){var i=oE(Nr),e=i!==String(Nr);if(!e&&Xn===66||dE&&!(nh.catch&&nh.finally))return!0;if(!Xn||Xn<51||!/native code/.test(i)){var t=new Nr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[pE]=r,Zn=t.then(function(){})instanceof r,!Zn)return!0}return!e&&(lE||cE)&&!oh});uh.exports={CONSTRUCTOR:hE,REJECTION_EVENT:oh,SUBCLASSING:Zn}});var Xt=f((x$,ch)=>{"use strict";var lh=He(),fE=TypeError,mE=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw fE("Bad Promise constructor");e=r,t=a}),this.resolve=lh(e),this.reject=lh(t)};ch.exports.f=function(i){return new mE(i)}});var Rh=f(()=>{"use strict";var bE=fe(),vE=we(),La=Dr(),it=G(),rr=Z(),dh=Qt(),ph=Pn(),gE=ma(),SE=dp(),yE=He(),Ra=F(),TE=Be(),IE=hp(),EE=Mn(),vh=jn().set,ao=Xp(),xE=eh(),PE=ka(),kE=Gn(),gh=sn(),$a=xt(),so=Jt(),Sh=Xt(),Ca="Promise",yh=so.CONSTRUCTOR,wE=so.REJECTION_EVENT,AE=so.SUBCLASSING,eo=gh.getterFor(Ca),RE=gh.set,Zt=$a&&$a.prototype,Pt=$a,wa=Zt,Th=it.TypeError,to=it.document,no=it.process,ro=Sh.f,LE=ro,$E=!!(to&&to.createEvent&&it.dispatchEvent),Ih="unhandledrejection",CE="rejectionhandled",hh=0,Eh=1,DE=2,oo=1,xh=2,Aa,fh,ME,mh,Ph=function(i){var e;return TE(i)&&Ra(e=i.then)?e:!1},kh=function(i,e){var t=e.value,r=e.state==Eh,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===xh&&BE(e),e.rejection=oo),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(Th("Promise-chain cycle")):(u=Ph(l))?rr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},wh=function(i,e){i.notified||(i.notified=!0,ao(function(){for(var t=i.reactions,r;r=t.get();)kh(r,i);i.notified=!1,e&&!i.rejection&&OE(i)}))},Ah=function(i,e,t){var r,a;$E?(r=to.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),it.dispatchEvent(r)):r={promise:e,reason:t},!wE&&(a=it["on"+i])?a(r):i===Ih&&xE("Unhandled promise rejection",t)},OE=function(i){rr(vh,it,function(){var e=i.facade,t=i.value,r=bh(i),a;if(r&&(a=PE(function(){La?no.emit("unhandledRejection",t,e):Ah(Ih,e,t)}),i.rejection=La||bh(i)?xh:oo,a.error))throw a.value})},bh=function(i){return i.rejection!==oo&&!i.parent},BE=function(i){rr(vh,it,function(){var e=i.facade;La?no.emit("rejectionHandled",e):Ah(CE,e,i.value)})},er=function(i,e,t){return function(r){i(e,r,t)}},tr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=DE,wh(i,!0))},io=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Th("Promise can't be resolved itself");var r=Ph(e);r?ao(function(){var a={done:!1};try{rr(r,e,er(io,a,i),er(tr,a,i))}catch(s){tr(a,s,i)}}):(i.value=e,i.state=Eh,wh(i,!1))}catch(a){tr({done:!1},a,i)}}};if(yh&&(Pt=function(e){IE(this,wa),yE(e),rr(Aa,this);var t=eo(this);try{e(er(io,t),er(tr,t))}catch(r){tr(t,r)}},wa=Pt.prototype,Aa=function(e){RE(this,{type:Ca,done:!1,notified:!1,parent:!1,reactions:new kE,rejection:!1,state:hh,value:void 0})},Aa.prototype=dh(wa,"then",function(e,t){var r=eo(this),a=ro(EE(this,Pt));return r.parent=!0,a.ok=Ra(e)?e:!0,a.fail=Ra(t)&&t,a.domain=La?no.domain:void 0,r.state==hh?r.reactions.add(a):ao(function(){kh(a,r)}),a.promise}),fh=function(){var i=new Aa,e=eo(i);this.promise=i,this.resolve=er(io,e),this.reject=er(tr,e)},Sh.f=ro=function(i){return i===Pt||i===ME?new fh(i):LE(i)},!vE&&Ra($a)&&Zt!==Object.prototype)){mh=Zt.then,AE||dh(Zt,"then",function(e,t){var r=this;return new Pt(function(a,s){rr(mh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete Zt.constructor}catch{}ph&&ph(Zt,wa)}bE({global:!0,constructor:!0,wrap:!0,forced:yh},{Promise:Pt});gE(Pt,Ca,!1,!0);SE(Ca)});var Mh=f((w$,Dh)=>{"use strict";var VE=z(),$h=VE("iterator"),Ch=!1;try{Lh=0,uo={next:function(){return{done:!!Lh++}},return:function(){Ch=!0}},uo[$h]=function(){return this},Array.from(uo,function(){throw 2})}catch{}var Lh,uo;Dh.exports=function(i,e){if(!e&&!Ch)return!1;var t=!1;try{var r={};r[$h]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var lo=f((A$,Oh)=>{"use strict";var _E=xt(),NE=Mh(),FE=Jt().CONSTRUCTOR;Oh.exports=FE||!NE(function(i){_E.all(i).then(void 0,function(){})})});var Bh=f(()=>{"use strict";var qE=fe(),UE=Z(),HE=He(),jE=Xt(),GE=ka(),YE=ya(),WE=lo();qE({target:"Promise",stat:!0,forced:WE},{all:function(e){var t=this,r=jE.f(t),a=r.resolve,s=r.reject,n=GE(function(){var o=HE(t.resolve),l=[],u=0,c=1;YE(e,function(d){var h=u++,p=!1;c++,UE(o,t,d).then(function(m){p||(p=!0,l[h]=m,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var _h=f(()=>{"use strict";var QE=fe(),zE=we(),KE=Jt().CONSTRUCTOR,po=xt(),JE=Ue(),XE=F(),ZE=Qt(),Vh=po&&po.prototype;QE({target:"Promise",proto:!0,forced:KE,real:!0},{catch:function(i){return this.then(void 0,i)}});!zE&&XE(po)&&(co=JE("Promise").prototype.catch,Vh.catch!==co&&ZE(Vh,"catch",co,{unsafe:!0}));var co});var Nh=f(()=>{"use strict";var ex=fe(),tx=Z(),rx=He(),ix=Xt(),ax=ka(),sx=ya(),nx=lo();ex({target:"Promise",stat:!0,forced:nx},{race:function(e){var t=this,r=ix.f(t),a=r.reject,s=ax(function(){var n=rx(t.resolve);sx(e,function(o){tx(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Fh=f(()=>{"use strict";var ox=fe(),ux=Z(),lx=Xt(),cx=Jt().CONSTRUCTOR;ox({target:"Promise",stat:!0,forced:cx},{reject:function(e){var t=lx.f(this);return ux(t.reject,void 0,e),t.promise}})});var ho=f((V$,qh)=>{"use strict";var dx=Pe(),px=Be(),hx=Xt();qh.exports=function(i,e){if(dx(i),px(e)&&e.constructor===i)return e;var t=hx.f(i),r=t.resolve;return r(e),t.promise}});var jh=f(()=>{"use strict";var fx=fe(),mx=Ue(),Uh=we(),bx=xt(),Hh=Jt().CONSTRUCTOR,vx=ho(),gx=mx("Promise"),Sx=Uh&&!Hh;fx({target:"Promise",stat:!0,forced:Uh||Hh},{resolve:function(e){return vx(Sx&&this===gx?bx:this,e)}})});var Gh=f(()=>{"use strict";Rh();Bh();_h();Nh();Fh();jh()});var zh=f(()=>{"use strict";var yx=fe(),Tx=we(),Da=xt(),Ix=ce(),Wh=Ue(),Qh=F(),Ex=Mn(),Yh=ho(),xx=Qt(),mo=Da&&Da.prototype,Px=!!Da&&Ix(function(){mo.finally.call({then:function(){}},function(){})});yx({target:"Promise",proto:!0,real:!0,forced:Px},{finally:function(i){var e=Ex(this,Wh("Promise")),t=Qh(i);return this.then(t?function(r){return Yh(e,i()).then(function(){return r})}:i,t?function(r){return Yh(e,i()).then(function(){throw r})}:i)}});!Tx&&Qh(Da)&&(fo=Wh("Promise").prototype.finally,mo.finally!==fo&&xx(mo,"finally",fo,{unsafe:!0}));var fo});var Ma=f((j$,Kh)=>{"use strict";var kx=Ue();Kh.exports=kx});var Xh=f((G$,Jh)=>{"use strict";sp();Gh();zh();var wx=Ma();Jh.exports=wx("Promise","finally")});var ef=f((Y$,Zh)=>{"use strict";var Ax=Xh();Zh.exports=Ax});var Oa=f((W$,tf)=>{"use strict";var Rx=ef();tf.exports=Rx});var kf=f(()=>{"use strict";var tP=fe(),rP=kr(),iP=ca(),aP=la(),sP=Cs();tP({target:"Array",proto:!0},{at:function(e){var t=rP(this),r=iP(t),a=aP(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});sP("at")});var Af=f((rD,wf)=>{"use strict";kf();var nP=Ma();wf.exports=nP("Array","at")});var Lf=f((iD,Rf)=>{"use strict";var oP=Af();Rf.exports=oP});var _a=f((aD,$f)=>{"use strict";var uP=Lf();$f.exports=uP});var om=f(()=>{"use strict"});var um=f(()=>{"use strict"});var cm=f((jO,lm)=>{"use strict";var hk=Be(),fk=Ut(),mk=z(),bk=mk("match");lm.exports=function(i){var e;return hk(i)&&((e=i[bk])!==void 0?!!e:fk(i)=="RegExp")}});var pm=f((GO,dm)=>{"use strict";var vk=zt(),gk=String;dm.exports=function(i){if(vk(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return gk(i)}});var fm=f((YO,hm)=>{"use strict";var Sk=Pe();hm.exports=function(){var i=Sk(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var vm=f((WO,bm)=>{"use strict";var yk=Z(),Tk=Ae(),Ik=Ir(),Ek=fm(),mm=RegExp.prototype;bm.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in mm)&&!Tk(i,"flags")&&Ik(mm,i)?yk(Ek,i):e}});var Sm=f((QO,gm)=>{"use strict";var Uo=X(),xk=kr(),Pk=Math.floor,Fo=Uo("".charAt),kk=Uo("".replace),qo=Uo("".slice),wk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ak=/\$([$&'`]|\d{1,2})/g;gm.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=Ak;return a!==void 0&&(a=xk(a),l=wk),kk(s,l,function(u,c){var d;switch(Fo(c,0)){case"$":return"$";case"&":return i;case"`":return qo(e,0,t);case"'":return qo(e,n);case"<":d=a[qo(c,1,-1)];break;default:var h=+c;if(h===0)return u;if(h>o){var p=Pk(h/10);return p===0?u:p<=o?r[p-1]===void 0?Fo(c,1):r[p-1]+Fo(c,1):u}d=r[h-1]}return d===void 0?"":d})}});var xm=f(()=>{"use strict";var Rk=fe(),Lk=Z(),Ho=X(),ym=zi(),$k=F(),Ck=Ht(),Dk=cm(),lr=pm(),Mk=Pr(),Ok=vm(),Bk=Sm(),Vk=z(),_k=we(),Nk=Vk("replace"),Fk=TypeError,Em=Ho("".indexOf),qk=Ho("".replace),Tm=Ho("".slice),Uk=Math.max,Im=function(i,e,t){return t>i.length?-1:e===""?t:Em(i,e,t)};Rk({target:"String",proto:!0},{replaceAll:function(e,t){var r=ym(this),a,s,n,o,l,u,c,d,h,p=0,m=0,S="";if(!Ck(e)){if(a=Dk(e),a&&(s=lr(ym(Ok(e))),!~Em(s,"g")))throw Fk("`.replaceAll` does not allow non-global regexes");if(n=Mk(e,Nk),n)return Lk(n,e,r,t);if(_k&&a)return qk(lr(r),e,t)}for(o=lr(r),l=lr(e),u=$k(t),u||(t=lr(t)),c=l.length,d=Uk(1,c),p=Im(o,l,0);p!==-1;)h=u?lr(t(l,p,o)):Bk(l,o,p,[],void 0,t),S+=Tm(o,m,p)+h,m=p+c,p=Im(o,l,p+d);return m<o.length&&(S+=Tm(o,m)),S}})});var km=f((JO,Pm)=>{"use strict";om();um();xm();var Hk=Ma();Pm.exports=Hk("String","replaceAll")});var Am=f((XO,wm)=>{"use strict";var jk=km();wm.exports=jk});var Lm=f((ZO,Rm)=>{"use strict";var Gk=Am();Rm.exports=Gk});var Iu="__VERSION__";var le=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(le||{}),vt=(v=>(v.MPEG="MPEG",v.DASH="DASH_SEP",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_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))(vt||{});var Yi=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Yi||{}),ks=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ks||{});var ws=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ws||{});import{assertNever as Au,assertNonNullable as dv,isNonNullable as Wi,ValueSubject as As,Subject as pv,Subscription as hv,merge as fv,observableFrom as mv,fromEvent as xu,map as Pu,tap as ku,filterChanged as bv,isNullable as Rs,ErrorCategory as wu}from"@vkontakte/videoplayer-shared";var Eu=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Qi=class{constructor(e){this.connection$=new As(void 0);this.castState$=new As("NOT_AVAILABLE");this.errorEvent$=new pv;this.realCastState$=new As("NOT_AVAILABLE");this.subscription=new hv;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=Wi(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Eu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:wu.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Wi(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Rs(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Rs(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(xu(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.getCurrentSession()?.getMediaSession()?.media.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 Au(a.sessionState)}})).add(fv(xu(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ku(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Pu(a=>a.castState)),mv([r.getCastState()])).pipe(bv(),Pu(vv),ku(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Wi(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();dv(o);let l=o.getCastDevice(),u=o.getMediaSession()?.media.contentId;(Rs(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Wi(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:wu.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},vv=i=>{switch(i){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 Au(i)}};var Vb=Oe(Ea(),1);var pf=Oe(Oa(),1);import{assertNever as rf}from"@vkontakte/videoplayer-shared";var K=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:rf(t)}return i},bo=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:rf(e)}};var T=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as Lx,Subject as Ba,merge as af}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Ba;this.transitionEnded$=new Ba;this.transitionUpdated$=new Ba;this.forceChanged$=new Ba;this.stateChangeStarted$=af(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=af(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||Lx(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 $x}from"@vkontakte/videoplayer-shared";var sf=i=>{switch(i){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":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 $x(i)}};import{assertNever as ir,assertNonNullable as kt,debounce as nf,ErrorCategory as of,fromEvent as wt,isNonNullable as uf,map as lf,merge as cf,observableFrom as Cx,Subject as Dx,Subscription as vo,timeout as Mx,getHighestQuality as Ox}from"@vkontakte/videoplayer-shared";var Bx=5,Vx=5,_x=500,df=7e3,Fr=class{constructor(e){this.subscription=new vo;this.loadMediaTimeoutSubscription=new vo;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=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(a?.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:ir(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:ir(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:ir(e)}break}default:ir(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(sf(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 vo;this.subscription.add(e),this.subscription.add(cf(this.videoState.stateChangeStarted$.pipe(lf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(lf(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new Dx;e.add(a.pipe(nf(_x)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(wt(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)>Bx)&&a.next(o),s=o})),e.add(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<Vx&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:ir(n)}}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(wt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=cf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Cx(["init"])).pipe(nf(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"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(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();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&T(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??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){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let u=t[e];kt(u);let c=Ox(Object.keys(u));kt(c);let d=u[c];kt(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let u=t[e];kt(u),r=u.url,a="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let u=t[e];kt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let u=t[e];kt(u),r=u.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=t[e];kt(u),r=K(u.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:of.VIDEO_PIPELINE,message:u,thrown:c}),c}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return ir(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:l}=this.params.meta;return uf(o)&&(n.metadata.title=o),uf(l)&&(n.metadata.subtitle=l),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((a,s)=>{this.loadMediaTimeoutSubscription.add(Mx(df).subscribe(()=>s(`timeout(${df})`)))});(0,pf.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()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:of.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var qr=i=>{i.removeAttribute("src"),i.load()};var hf=i=>{try{i.pause(),i.playbackRate=0,qr(i),i.remove()}catch(e){console.error(e)}};var go=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)}},So=window.WeakMap?new WeakMap:new go,ee=i=>{let e=i.querySelector("video"),t=!!e;return e?qr(e):(e=document.createElement("video"),i.appendChild(e)),So.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},te=i=>{let e=So.get(i);So.delete(i),e?qr(i):hf(i)};import{assertNonNullable as Ur,isNonNullable as Ne,isNullable as qx,fromEvent as ar,merge as ff,observableFrom as mf,filterChanged as bf,map as Hr,Subject as vf,Subscription as Ux,ValueSubject as Hx,ErrorCategory as jx}from"@vkontakte/videoplayer-shared";import{isNonNullable as yo,isNullable as Nx,Subscription as Fx}from"@vkontakte/videoplayer-shared";var Va=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=Nx(a),u=new Fx;return a&&u.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),l&&i.setState(c.to)},s)),u},_e=(i,e,t)=>Va(e,()=>i.loop,r=>{yo(r)&&(i.loop=r)},{onError:t}),re=(i,e,t,r)=>Va(e,()=>({muted:i.muted,volume:i.volume}),a=>{yo(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),me=(i,e,t,r)=>Va(e,()=>i.playbackRate,a=>{yo(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),at=Va;var Gx=i=>["__",i.language,i.label].join("|"),Yx=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},To=class i{constructor(){this.available$=new vf;this.current$=new Hx(void 0);this.error$=new vf;this.subscription=new Ux;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:jx.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(at(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ne(s)&&this.setInternal(s)},{equal:(s,n)=>Ne(s)&&Ne(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(Hr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(at(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ne(s)&&this.setExternal(s)},{equal:(s,n)=>Ne(s)&&Ne(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(Hr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(at(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:a})),this.subscription.add(at(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ur(this.video);let{textTracks:e}=this.video;this.subscription.add(ar(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(ff(ar(e,"addtrack"),ar(e,"removetrack"),mf(["init"])).pipe(Hr(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),bf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(ff(ar(e,"change"),mf(["init"])).pipe(Hr(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Hr(r=>r&&this.htmlTextTrackToITextTrack(r).id),bf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(ar(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(ar(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;Ne(t.align)&&(a.align=t.align),Ne(t.position)&&(a.position=t.position),Ne(t.size)&&(a.size=t.size),Ne(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Ur(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:Gx(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.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:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){Ur(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(qx(e)||!Yx(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){Ur(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){Ur(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)}},be=To;var Ye=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 gf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Io=i=>{let e=gf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Sf=i=>{let e=gf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as ve,map as st,merge as Tf,filterChanged as Qx,isNonNullable as If,Subject as zx,filter as Ef,mapTo as xf,combine as Kx,once as Jx,ErrorCategory as Xx,ValueSubject as Pf,getCurrentBrowser as Zx,CurrentClientBrowser as eP}from"@vkontakte/videoplayer-shared";var Wx=3,yf=(i,e,t=Wx)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let l=s-1;l>=0;l--)i.end(l)+t>=r&&(r=i.start(l));for(let l=s+1;l<i.length;l++)i.start(l)-t<=a&&(a=i.end(l))}}return{from:r,to:a}};var ie=i=>{let e=w=>ve(i,w).pipe(xf(void 0)),r=Tf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>ve(i,w))).pipe(st(w=>w.type==="ended"?i.readyState<2:i.readyState<3),Qx()),a=Tf(ve(i,"progress"),ve(i,"timeupdate")).pipe(st(()=>yf(i.buffered,i.currentTime))),n=Zx().browser===eP.Safari?Kx({play:e("play").pipe(Jx()),playing:e("playing")}).pipe(xf(void 0)):e("playing"),o=ve(i,"volumechange").pipe(st(()=>({muted:i.muted,volume:i.volume}))),l=ve(i,"ratechange").pipe(st(()=>i.playbackRate)),u=ve(i,"error").pipe(Ef(()=>!!(i.error||i.played.length)),st(()=>{let w=i.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:Xx.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:i.error??void 0}})),c=ve(i,"timeupdate").pipe(st(()=>i.currentTime)),d=new zx,h=.3,p;c.subscribe(w=>{i.loop&&If(p)&&If(w)&&p>=i.duration-h&&w<=h&&d.next(p),p=w});let m=ve(i,"enterpictureinpicture"),S=ve(i,"leavepictureinpicture"),b=new Pf(Sf(i));m.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));let g=new Pf(Io(i));return ve(i,"fullscreenchange").pipe(st(()=>Io(i))).subscribe(g),{playing$:n,pause$:e("pause").pipe(Ef(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:ve(i,"durationchange").pipe(st(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:b,inFullscreen$:g}};import{VideoQuality as nt}from"@vkontakte/videoplayer-shared";var ot=i=>{switch(i){case"mobile":return nt.Q_144P;case"lowest":return nt.Q_240P;case"low":return nt.Q_360P;case"sd":case"medium":return nt.Q_480P;case"hd":case"high":return nt.Q_720P;case"fullhd":case"full":return nt.Q_1080P;case"quadhd":case"quad":return nt.Q_1440P;case"ultrahd":case"ultra":return nt.Q_2160P}};var wo=Oe(_a(),1);import{isNonNullable as ut,isNullable as xo,now as Vf,isHigher as Po,isHigherOrEqual as Of,isInvariantQuality as Bf,isLower as ko,isLowerOrEqual as lP,videoSizeToQuality as cP,assertNotEmptyArray as dP}from"@vkontakte/videoplayer-shared";var Eo=!1,We={},Cf=i=>{Eo=i},Df=()=>{We={}},Mf=i=>{i(We)},jr=(i,e)=>{Eo&&(We.meta=We.meta??{},We.meta[i]=e)},J=class{constructor(e){this.name=e}next(e){if(!Eo)return;We.series=We.series??{};let t=We.series[this.name]??[];t.push([Date.now(),e]),We.series[this.name]=t}};var pP=new J("best_bitrate"),hP=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Na=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Vf()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},fP='Assertion "ABR Tracks is empty array" failed',mP=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{dP(i,fP);let h=r.usePixelRatio?window.devicePixelRatio??1:1,p=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*r.containerSizeFactor,height:e.height*h*r.containerSizeFactor},m=p&&cP(p),S=r.considerPlaybackRate&&ut(o)?o:1,b=i.filter(E=>!Bf(E.quality)).sort((E,x)=>Po(E.quality,x.quality)?-1:1),g=(0,wo.default)(b,-1)?.quality,v=(0,wo.default)(b,0)?.quality,w=xo(a)||ut(a.min)&&ut(a.max)&&ko(a.max,a.min)||ut(a.min)&&v&&Po(a.min,v)||ut(a.max)&&g&&ko(a.max,g),y=S*hP(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),I={},$=b.filter(E=>(m?ko(E.quality,m):!0)?(ut(t)&&isFinite(t)&&ut(E.bitrate)?t-s>=E.bitrate*y:!0)?r.lazyQualitySwitch&&ut(r.minBufferToSwitchUp)&&l&&!Bf(l.quality)&&(n??0)<r.minBufferToSwitchUp&&Po(E.quality,l.quality)?(I[E.quality]="Buffer",!1):!!c&&Of(E.quality,c)?(I[E.quality]="DroppedFramesLimit",!1):w||(xo(a.max)||lP(E.quality,a.max))&&(xo(a.min)||Of(E.quality,a.min))?!0:(I[E.quality]="FitsQualityLimits",!1):(I[E.quality]="FitsThroughput",!1):(I[E.quality]="FitsContainer",!1))[0];$&&$.bitrate&&pP.next($.bitrate);let A=$??b[Math.ceil((b.length-1)/2)]??i[0];A.quality!==u?.last?.quality&&d({message:`
7
7
  [available tracks]
8
8
  ${i.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate} }`).join(`
9
9
  `)}
@@ -32,9 +32,9 @@ var tg=Object.create;var gu=Object.defineProperty;var rg=Object.getOwnPropertyDe
32
32
 
33
33
  [best track] ${$?.quality}
34
34
  [selected track] ${A?.quality}
35
- `});let D=A&&u&&u.history[A.id]&&Df()-u.history[A.id]<=r.trackCooldown&&(!u.last||A.id!==u.last.id);if(A?.id&&u&&!D&&u.recordSelection(A),D&&u?.last){let E=u.last;return u?.recordSwitch(E),d({message:`
35
+ `});let D=A&&u&&u.history[A.id]&&Vf()-u.history[A.id]<=r.trackCooldown&&(!u.last||A.id!==u.last.id);if(A?.id&&u&&!D&&u.recordSelection(A),D&&u?.last){let E=u.last;return u?.recordSwitch(E),d({message:`
36
36
  [last selected] ${E?.quality}
37
- `}),E}return u?.recordSwitch(A),A},lt=dP;var Y=i=>new URL(i).hostname;import{assertNever as Nf,assertNonNullable as Ff,combine as $P,debounce as CP,ErrorCategory as qf,filter as DP,filterChanged as MP,isNonNullable as Ro,map as Ua,merge as Uf,observableFrom as OP,Subscription as BP,ValueSubject as Lo,videoQualityToHeight as VP,videoSizeToQuality as _P}from"@vkontakte/videoplayer-shared";var Mf=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},ae=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Mf(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Mf(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Na,isNullable as fP,assertNonNullable as Yr}from"@vkontakte/videoplayer-shared";import{isNonNullable as Of,assertNonNullable as _a,now as pP}from"@vkontakte/videoplayer-shared";function W(){return pP()}function Po(i){return W()-i}function ko(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Bf(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function sr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,h=!1,p="arraybuffer",m=7e3,S=2e3,b=()=>{if(l)return;_a(c);let R=Po(c),q;if(R<S){q=S-R,setTimeout(b,q);return}S*=2,S>m&&(S=m),n&&n.abort(),n=new a,V()},v=R=>(s=R,x),g=R=>(d=R,x),w=()=>(p="json",x),y=()=>{if(!l){if(--u>=0){b(),r&&r();return}l=!0,d&&d(),t&&t()}},I=R=>(h=R,x),V=()=>{c=W(),n=new a,n.open("get",i);let R=0,q,Q=0,Te=()=>(_a(c),Math.max(c,Math.max(q||0,Q||0)));if(s&&n.addEventListener("progress",k=>{let O=W();s.updateChunk&&k.loaded>R&&(s.updateChunk(Te(),k.loaded-R),R=k.loaded,q=O)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(l)return;_a(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let O=n.response.byteLength-R;O&&s.updateChunk&&s.updateChunk(Te(),O)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),h){let k=()=>{_a(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=W(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=p,n.send(),x},x={withBitrateReporting:v,withParallel:I,withJSONResponse:w,withRetryCount:R=>(u=R,x),withRetryInterval:(R,q)=>(Of(R)&&(S=R),Of(q)&&(m=q),x),withTimeout:R=>(o=R,x),withFinally:g,send:V,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return x}var jr=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,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=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 l=s.bytes*n/o;a+=l,s.start=t,s.bytes-=l}}}if(a>0&&r>0){let s=a*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(a)}/${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 Gr=class{constructor(e,t,r,a,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=a,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=W(),a=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=l=>{e._complete=1,e._responseData=l,e._downloadTime=W()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=sr(t,s,()=>a("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=W()}_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=W();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,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,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=a,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 Fa=1e4,wo=3;var mP=6e4,bP=10,gP=1,vP=500,Wr=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 jr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ko(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=ko(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.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,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,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)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Na(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Bf(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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 Gr(wo,Fa,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,l=null,u=null,c=!1,d=()=>{let y=s&&(!c||c===this.rep);return y||t("Not running!"),y},h=(y,I,V)=>{l&&l.abort(),l=sr(this.urlResolver.resolve(y,!1),I,V,()=>this._retryCallback()).withTimeout(Fa).withBitrateReporting(this.bitrateSwitcher).withRetryCount(wo).withFinally(()=>{l=null}).send()},p=(y,I,V)=>{Yr(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,V,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=y=>{let I=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${I}=>${y}`),r.playbackRate=y)},S=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=W()-1e4,$=0;for(let D=0;D<this.bufferStates.length;D++){let E=this.bufferStates[D];y=Math.min(y,E.buf),E.ts<V&&$++}this.bufferStates.splice(0,$),t(`update playback rate; minBuffer=${y} drop=${$} jitter=${this.sourceJitter}`);let A=y-gP;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?m(1.15):A>1?m(1.1):A>.3?m(1.05):m(1)}},v=y=>{let I,V=()=>I&&I.start?I.start.length:0,$=k=>I.start[k]/1e3,A=k=>I.dur[k]/1e3,D=k=>I.fragIndex+k,E=(k,O)=>({chunkIdx:D(k),startTS:$(k),dur:A(k),discontinuity:O}),x=()=>{let k=0;if(I&&I.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,j=O;this.sourceJitter>1&&(j+=this.sourceJitter-1);let se=I.dur.length-1;for(;se>=0&&(j-=I.dur[se],!(j<=0));--se);k=Math.min(se,I.dur.length-1-U),k=Math.max(k,0)}return E(k,!0)},R=k=>{let O=V();if(!(O<=0)){if(Na(k)){for(let U=0;U<O;U++)if($(U)>k)return E(U)}return x()}},q=k=>{let O=V(),U=k?k.chunkIdx+1:0,j=U-I.fragIndex;if(!(O<=0)){if(!k||j<0||j-O>bP)return t(`Resync: offset=${j} bChunks=${O} chunk=`+JSON.stringify(k)),x();if(!(j>=O))return E(U-I.fragIndex,!1)}},Q=(k,O,U)=>{u&&u.abort(),u=sr(this.urlResolver.resolve(k,!0,this.lowLatency),O,U,()=>this._retryCallback()).withTimeout(Fa).withRetryCount(wo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(k,O)=>{Q(y,U=>{if(!d())return;I=U;let j=!!I.lowLatency;j!==this.lowLatency&&S(j);let se=0;for(let et=0;et<I.dur.length;++et)se+=I.dur[et];se>0&&(Yr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/I.dur.length)),a({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,k(R(O))},()=>this._handleNetworkError())},nextChunk:q}},g=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),Yr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:I,logger:V}=this.params,$=v(e.jidxUrl),A,D,E,x,R=0,q,Q,Te,k=()=>{q&&(clearTimeout(q),q=void 0);let _=Math.max(vP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=R+_,oe=W(),Ie=Math.min(1e4,ne-oe);R=oe;let qe=()=>{u||d()&&$.seek(()=>{d()&&(R=W(),O(),k())})};Ie>0?q=window.setTimeout(()=>{this.paused?k():qe()},Ie):qe()},O=()=>{let _;for(;_=$.nextChunk(x);)x=_,gs(_);let ne=$.nextChunk(E);if(ne){if(E&&ne.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?k():(g(),this._initPlayerWith(e));return}et(ne)}else k()},U=(_,ne)=>{if(!d()||!this.sourceBuffer)return;let oe,Ie,qe,gr=ue=>{window.setTimeout(()=>{d()&&U(_,ne)},ue)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),gr(100);else{let ue=W(),tt=I.currentTime;!this.paused&&I.buffered.length>1&&Q===tt&&ue-Te>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),Q!==tt&&(Q=tt,Te=ue);let Ee=this._getBufferSizeSec();if(Ee>30)V(`Buffered ${Ee} seconds; delaying appendBuffer`),gr(2e3);else try{this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(this.bufferStates.push({ts:ue,buf:Ee}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(De){if(De.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),qe=this.sourceBuffer.buffered.length,qe!==0&&(oe=this.sourceBuffer.buffered.start(0),Ie=tt,Ie-oe>4&&this.sourceBuffer.remove(oe,Ie-3)),gr(1e3);else throw De}}},j=()=>{D&&A&&(V([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(E)]),U(D,function(){D=null,O()}))},se=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),et=_=>{d()&&p(se(_),(ne,oe)=>{if(d()){if(oe/=1e3,D=ne,E=_,n=_.startTS,oe){let Ie=Math.min(10,_.dur/oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}j()}},()=>this._handleNetworkError())},gs=_=>{d()&&(Yr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(_),!1)))},Ni=_=>{d()&&(e.cachedHeader=_,U(_,()=>{A=!0,j()}))};s=!0,$.seek(_=>{if(d()){if(R=W(),!_){k();return}x=_,!fP(y)||_.startTS>y?et(_):(E=_,O())}},y),e.cachedHeader?Ni(e.cachedHeader):h(e.headerUrl,Ni,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Na(a)&&(a+=.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,Yr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Na(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(h,p)=>{let m=W();if(this.chunkRateEstimator.addInterval(h,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:b}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&Po(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&u(),p},notifySwitch:d=>{let h=W();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=sr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Fa).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;ae(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((l,u)=>{l.video&&a.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=u,o.push(l))}),o.sort(function(l,u){return l.video&&u.video?u.video.height-l.video.height:u.bitrate-l.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))},mP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as SP,filter as Vf,fromEvent as yP,interval as TP,isHigher as IP,isInvariantQuality as EP,isLower as xP,merge as PP,Subject as _f,Subscription as kP}from"@vkontakte/videoplayer-shared";var Ao=class{constructor(){this.onDroopedVideoFramesLimit$=new _f;this.subscription=new kP;this.playing=!1;this.tracks=[];this.forceChecker$=new _f;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!EP(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&IP(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??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.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(yP(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=TP(this.droppedFramesChecker.checkTime).pipe(Vf(()=>this.playing),Vf(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(SP(this.droppedFramesChecker.checkTime)),r=PP(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){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>xP(r,a)?-1:1)?.[0]?.[0];return 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}},qa=Ao;import{map as wP,Observable as AP}from"@vkontakte/videoplayer-shared";import{fromEvent as RP}from"@vkontakte/videoplayer-shared";var Qr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var LP=(i,e)=>new AP(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||Qr()))},{...r,...e});a.observe(i);let s=RP(document,"visibilitychange").pipe(wP(n=>!document.hidden||Qr())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),ve=LP;var NP=["paused","playing","ready"],FP=["paused","playing","ready"],zr=class{constructor(e){this.subscription=new BP;this.videoState=new L("stopped");this.representations$=new Lo([]);this.textTracksManager=new be;this.droppedFramesManager=new qa;this.maxSeekBackTime$=new Lo(1/0);this.zeroTime$=new Lo(void 0);this.liveOffset=new Ye;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:qf.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=ot(a.name)??_P(a.video),o=a.bitrate/1e3,l={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:l};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Ro(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);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(),a=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(FP.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&NP.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(K(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 l=a?.from;l&&l==="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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.dash.reinit(K(this.params.source.url,l))}return;default:return Nf(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:qf.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Uf(this.videoState.stateChangeStarted$.pipe(Ua(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ua(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ee(e.container),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(Y(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=ie(this.video);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$:this.representations$.pipe(Ua(a=>a.map(({track:s})=>s)))}),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.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(MP(),Ua(a=>-a/1e3)).subscribe(this.params.output.duration$)).add($P({zeroTime:this.zeroTime$.pipe(DP(Ro)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(_e(this.video,this.params.desiredState.isLooped,t)).add(re(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.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(ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&VP(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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":this.params.desiredState.playbackState.getTransition()?.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 Nf(a.to)}},t)).add(Uf(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,OP(["init"])).pipe(CP(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),te(this.video)}createLiveDashPlayer(){let e=new Wr({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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Ro(t)?t:lt(e.map(({track:u})=>u),{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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let u=e.find(({track:c})=>c.id===s)?.representation;Ff(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Ff(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(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(K(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Hf=zr;var ct=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as sw,assertNonNullable as tb,debounce as nw,ErrorCategory as Zo,filter as ow,filterChanged as rb,fromEvent as uw,isLowerOrEqual as ib,isNonNullable as lw,videoSizeToQuality as ab,map as eu,merge as ts,observableFrom as cw,observeElementSize as dw,once as pw,Subscription as hw,ValueSubject as sb}from"@vkontakte/videoplayer-shared";var Ha=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 a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];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}},nr=class extends Ha{constructor(){super(),this.listeners||Ha.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)}},Kr=class{constructor(){Object.defineProperty(this,"signal",{value:new nr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?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>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Kr.prototype[Symbol.toStringTag]="AbortController",nr.prototype[Symbol.toStringTag]="AbortSignal");function ja(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function $o(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!ja({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(u,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let c=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([h,n(l,u)])}return n(l,u)},Request:s}}var Jr=ja({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),jf=Jr?$o({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Qe=Jr?jf.fetch:window.fetch,yM=Jr?jf.Request:window.Request,ze=Jr?Kr:window.AbortController,TM=Jr?nr:window.AbortSignal;var Xm=Oe(Ta(),1);var Xr=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};import{abortable as Ko,assertNonNullable as Ot,combine as Wm,ErrorCategory as pt,filter as Ka,filterChanged as Xk,fromEvent as hr,interval as Jo,isNonNullable as Qm,map as Xo,merge as fr,Subject as zm,Subscription as Km,tap as Zk,throttle as ew,ValueSubject as pe}from"@vkontakte/videoplayer-shared";var pr=Oe(Ba(),1);var qP=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},UP=i=>window.clearTimeout(i),Gf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Co=Gf?qP:window.requestIdleCallback,xM=Gf?UP:window.cancelIdleCallback;var _m=Oe(Da(),1);import{assertNever as HP,CurrentClientBrowser as jP,ErrorCategory as Yf,getCurrentBrowser as GP,Subject as Wf}from"@vkontakte/videoplayer-shared";var YP=16,Qf=!1;try{Qf=GP().browser===jP.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=YP}catch(i){console.error(i)}var Do=class{constructor(e){this.bufferFull$=new Wf;this.error$=new Wf;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Yf.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Qf&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!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(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Yf.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:HP(t)}}},zf=Do;var Mo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as cr,assertNever as jk,assertNonNullable as Ke,ErrorCategory as dr,fromEvent as Go,getExponentialDelay as Yo,once as Gk,isNonNullable as Vm,isNullable as Je,Subject as Yk,Subscription as Wk,ValueSubject as yi}from"@vkontakte/videoplayer-shared";var B=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 a=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,a),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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 or=class extends B{};var Zr=class extends B{};var ei=class extends B{constructor(t,r){super(t,r);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let a=this.size-this.cursor;for(;a;){let s=this.readString(4);this.compatibleBrands.push(s),a-=4}}};var ti=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ri=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ii=class extends B{constructor(t,r){super(t,r);this.data=this.content}};var H=class extends B{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var At=class extends H{constructor(t,r){super(t,r);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 a=0;a<this.referenceCount;a++){let s=this.readUint32(),n=s>>>31,o=s<<1>>>1,l=this.readUint32();s=this.readUint32();let u=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:u,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var ai=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var si=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ni=class extends H{constructor(t,r){super(t,r);switch(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 oi=class extends H{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ui=class extends H{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var li=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ci=class extends H{constructor(t,r){super(t,r);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 di=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends H{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var fi=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends H{constructor(t,r){super(t,r);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 bi=class extends H{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 gi=class extends H{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 a=0;a<this.sampleCount;a++)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 QP={ftyp:ei,moov:ti,moof:ri,mdat:ii,sidx:At,trak:ai,mdia:li,mfhd:hi,tkhd:ci,traf:fi,tfhd:mi,tfdt:bi,trun:gi,minf:di,sv3d:si,st3d:ni,prhd:oi,proj:pi,equi:ui,uuid:Zr,unknown:or},Rt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=QP[e];return r?new r(t,new i):new or(t,new i)}};var ur=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],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 KP=new TextDecoder("ascii"),JP=i=>KP.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",XP=i=>{let e=new At(i,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.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})},ZP=(i,e)=>{let r=new Rt().parse(i),a=new ur(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,d=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,d)},ek=(i,e)=>{let r=new Rt().parse(i),s=new ur(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"),l=s[s.length-1].children.find(d=>d.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((d,h)=>d+h,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},tk=i=>{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 Rt().parse(i),a=new ur(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let l=a.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},Kf={validateData:JP,parseInit:tk,getIndexRange:()=>{},parseSegments:XP,parseFeedableSegmentChunk:ZP,getSegmentEndTime:ek};import{assertNonNullable as Bo,isNonNullable as em,isNullable as ik}from"@vkontakte/videoplayer-shared";import{assertNever as rk}from"@vkontakte/videoplayer-shared";var Jf={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"}},Xf=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=vi(i,t),a=r in Jf,s=a?Jf[r].type:"binary",n=i.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 l=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,c=vi(l),d=u*2**((o-1)*8)+c,h=t+o,p;return h+d>i.byteLength?p=new DataView(i.buffer,i.byteOffset+h):p=new DataView(i.buffer,i.byteOffset+h,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},vi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Le=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return vi(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:rk(e)}},Lt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Xf(r);if(!e(a))return;a.type==="master"&&Lt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Zf=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Xf(i);return Lt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Le(o,n):s===17026?t=Le(o,n):s===17029&&(r=Le(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var tm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ak=[231,22612,22743,167,171,163,160,175],sk=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Lt(i,({tag:h,type:p,value:m,valueSize:S})=>{if(h===21419){let b=Le(m,p);u=vi(b)}else h!==21420&&(u=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+S):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Le(m,p):h===17545?a=Le(m,p):h===21420&&u===475249515?l=Le(m,p):h===374648427?Lt(m,({tag:b,type:v,value:g})=>b===30321?(c=Le(g,v)===1,!1):!0):s&&n&&tm.includes(h)&&(o=!0),!o}),Bo(e,"Failed to parse webm Segment start"),Bo(t,"Failed to parse webm Segment end"),Bo(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:l,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},nk=i=>{if(ik(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ok=(i,e)=>{let t=!1,r=!1,a=o=>em(o.time)&&em(o.position),s=[],n;return Lt(i,({tag:o,type:l,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Le(u,l));break;case 183:break;case 241:n&&(n.position=Le(u,l));break;default:t&&tm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:c}=o,d=s[l+1];return{status:"none",time:{from:u,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},uk=i=>{let e=0,t=!1;try{Lt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):ak.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},rm={validateData:Zf,parseInit:sk,getIndexRange:nk,parseSegments:ok,parseFeedableSegmentChunk:uk};var qo=Oe(km(),1);import{isNonNullable as Am,isNullable as Rm}from"@vkontakte/videoplayer-shared";var wm=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Lm=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*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(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},$t=(i,e)=>{let t=i;t=(0,qo.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,qo.default)(t,n,(o,l)=>Rm(s)?o:Rm(l)?s:s.padStart(parseInt(l,10),"0"))}return t},Cm=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",l=n.children,u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,h,p=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)h=Lm(p);else if(m){let y=Lm(m);Am(y)&&(h=y)}else b&&(h=parseInt(b,10));let v=0,g=s.getAttribute("profiles")?.split(",")??[],w=g.includes("urn:webm:dash:profile:webm-on-demand:2012")||g.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let y of l){let I=y.getAttribute("mimeType"),V=y.getAttribute("codecs"),$=y.getAttribute("contentType")??I?.split("/")[0],A=y.getAttribute("profiles")?.split(",")??[],D=y.querySelectorAll("Representation"),E=y.querySelector("SegmentTemplate");if($==="text"){for(let x of D){let R=x.getAttribute("id")||"",q=y.getAttribute("lang"),Q=y.getAttribute("label"),Te=x.querySelector("BaseURL")?.textContent?.trim()??"",k=new URL(Te||o,e).toString(),O=R.includes("_auto");a.text.push({id:R,lang:q,label:Q,isAuto:O,kind:"text",url:k})}continue}for(let x of D){let R=x.getAttribute("mimeType")??I,q=x.getAttribute("codecs")??V??"",Q=x.getAttribute("contentType")??R?.split("/")[0]??$,Te=y.getAttribute("profiles")?.split(",")??[],k=parseInt(x.getAttribute("width")??"",10),O=parseInt(x.getAttribute("height")??"",10),U=parseInt(x.getAttribute("bandwidth")??"",10)/1e3,j=x.getAttribute("frameRate")??"",se=x.getAttribute("quality")??void 0,et=j?wm(j):void 0,gs=x.getAttribute("id")??(v++).toString(10),Ni=Q==="video"?`${O}p`:Q==="audio"?`${U}Kbps`:q,_=`${gs}@${Ni}`,ne=x.querySelector("BaseURL")?.textContent?.trim()??"",oe=new URL(ne||o,e).toString(),Ie=[...g,...A,...Te],qe,gr=x.querySelector("SegmentBase"),ue=x.querySelector("SegmentTemplate")??E;if(gr){let Ee=x.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[De,vs]=Ee.split("-").map(Ft=>parseInt(Ft,10)),rt={from:De,to:vs},vr=x.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ss,Fi]=vr?vr.split("-").map(Ft=>parseInt(Ft,10)):[],Sr=vr?{from:Ss,to:Fi}:void 0;qe={type:"byteRange",url:oe,initRange:rt,indexRange:Sr}}else if(ue){let Ee={representationId:x.getAttribute("id")??void 0,bandwidth:x.getAttribute("bandwidth")??void 0},De=parseInt(ue.getAttribute("timescale")??"",10),vs=ue.getAttribute("initialization")??"",rt=ue.getAttribute("media"),vr=parseInt(ue.getAttribute("startNumber")??"",10)??1,Ss=$t(vs,Ee);if(!rt)throw new ReferenceError("No media attribute in SegmentTemplate");let Fi=ue.querySelectorAll("SegmentTimeline S")??[],Sr=[],Ft=0,ys="",Ts=0;if(Fi.length){let qi=vr,xe=0;for(let qt of Fi){let Me=parseInt(qt.getAttribute("d")??"",10),bt=parseInt(qt.getAttribute("r")??"",10)||0,Ui=parseInt(qt.getAttribute("t")??"",10);xe=Number.isFinite(Ui)?Ui:xe;let Is=Me/De*1e3,Xb=xe/De*1e3;for(let Hi=0;Hi<bt+1;Hi++){let Zb=$t(rt,{...Ee,segmentNumber:qi.toString(10),segmentTime:(xe+Hi*Me).toString(10)}),bu=(Xb??0)+Hi*Is,eg=bu+Is;qi++,Sr.push({time:{from:bu,to:eg},url:Zb})}xe+=(bt+1)*Me,Ft+=(bt+1)*Is}Ts=xe/De*1e3,ys=$t(rt,{...Ee,segmentNumber:qi.toString(10),segmentTime:xe.toString(10)})}else if(Am(h)){let xe=parseInt(ue.getAttribute("duration")??"",10)/De*1e3,qt=Math.ceil(h/xe),Me=0;for(let bt=1;bt<qt;bt++){let Ui=$t(rt,{...Ee,segmentNumber:bt.toString(10),segmentTime:Me.toString(10)});Sr.push({time:{from:Me,to:Me+xe},url:Ui}),Me+=xe}Ts=Me,ys=$t(rt,{...Ee,segmentNumber:qt.toString(10),segmentTime:Me.toString(10)})}let Jb={time:{from:Ts,to:1/0},url:ys};qe={type:"template",baseUrl:oe,segmentTemplateUrl:rt,initUrl:Ss,totalSegmentsDurationMs:Ft,segments:Sr,nextSegmentBeyondManifest:Jb,timescale:De}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Q||!R)continue;let tt={video:"video",audio:"audio",text:"text"}[Q];tt&&a[tt].push({id:_,kind:tt,segmentReference:qe,profiles:Ie,duration:h,bitrate:U,mime:R,codecs:q,width:k,height:O,fps:et,quality:se})}}return{dynamic:u,liveAvailabilityStartTime:d,duration:h,container:w,representations:a}};var Ho=Oe(Ba(),1);import{videoSizeToQuality as Hk}from"@vkontakte/videoplayer-shared";var Dm=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?ot(s):void 0)??Hk({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Mm=({id:i,bitrate:e})=>({id:i,bitrate:e}),Om=(i,e,t)=>{let r=e.indexOf(t);return(0,Ho.default)(i,Math.round(i.length*r/e.length))??(0,Ho.default)(i,-1)},Bm=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),jo=i=>"url"in i,Ct=i=>i.type==="template",Si=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Ti=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new yi(0);this.onLastSegment$=new yi(!1);this.fullyBuffered$=new yi(!1);this.playingRepresentation$=new yi(void 0);this.playingRepresentationInit$=new yi(void 0);this.error$=new Yk;this.gaps=[];this.subscription=new Wk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ze;this.destroyAbortController=new ze;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=cr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new zf(this.sourceBuffer),this.subscription.add(Go(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:dr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(Go(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:dr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,Mo(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),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),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ke(r,"No init buffer for starting representation"),Ke(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=cr(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);Ke(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Je(a)||Je(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Ke(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();Vm(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=cr(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let o of this.representations.keys()){let l=e.find(d=>d.id===o);l&&this.representations.set(o,l);let u=this.representations.get(o);if(!u||!Ct(u.segmentReference))return;let c=this.getActualLiveStartingSegments(u.segmentReference);this.segments.set(u.id,c)}let t=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(t);Ke(r);let a=this.segments.get(t);Ke(a,"No segments for starting representation");let s=this.initData.get(t);if(Ke(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));switch(this.fetcher=s,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=l,this.isLive=!!c?.dynamic,this.container=r,r){case"mp4":this.containerParser=Kf;break;case"webm":this.containerParser=rm;break;default:jk(r)}this.initData=new Map(a.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(d=>[d.id,d])),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 ze,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Je(e)||Je(this.downloadingRepresentationId)||Je(this.playingRepresentationId)||Je(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ke(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ct(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Mo(this.sourceBuffer.buffered)>=this.bufferLimit){let u=ct(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let c=(0,pr.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&ct(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,pr.default)(r,-1);l&&l.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===l))}searchGaps(e,t){this.gaps=[];let r=0,a=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+a}),r=s.time.to;Vm(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,a=[],s=0,n=t.length-1;do a.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()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){for(let t of e?.representations[this.kind].values()??[]){if(!t||!Ct(t.segmentReference))return;let r=t.segmentReference.segments.map(o=>({...o,status:"none",size:void 0})),a=this.segments.get(t.id)??[],s=(0,pr.default)(a,-1)?.time.to??0,n=r?.findIndex(o=>Math.floor(s)>=Math.floor(o.time.from)&&Math.floor(s)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;let o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{let o=r.slice(n+1);this.segments.set(t.id,[...a,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(let t of this.representations.values()){let r=t.segmentReference;if(!Ct(r))return;let a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),s=$t(r.segmentTemplateUrl,{segmentTime:a}),n=this.segments.get(t.id)??[],o=n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||n.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:s})}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.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(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}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(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let S=h<=r&&p>=r,b=h>r||S||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&h<=r+v||p<=r+v;return(d==="none"||d==="partially_ejected"&&b&&g&&this.sourceBuffer&&!Xr(this.sourceBuffer.buffered,r))&&b&&g});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=u||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await cr(o,async function*(){let c=Yo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(this.isActiveLowLatency()){let h=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,h)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Si(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await cr(n,async function*(){let l=Yo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),Go(window,"online").pipe(Gk()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),Si(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ct(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,pr.default)(e,0).byte.from,to:(0,pr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,l)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:dr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ct(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 a=r.toString(),{signal:s}=this.downloadAbortController,n=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:dr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:l,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(u,this.isLive);c?.byteLength&&(l.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let l=o.segmentReference.type,u=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,h=l==="byteRange",p=h?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!h||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let S=h?d.byte.from-r:0,b=h?d.byte.to-r:e.byteLength,v=S<a,g=b<=a;if(d.status==="downloading"&&v&&g){d.status="downloaded";let w=new DataView(e.buffer,e.byteOffset+S,p);this.sourceBufferTaskQueue.append(w,s).then(y=>y&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(c.loadedBytes=Math.min(p,a-S),c.loadedBytes>c.feedingBytes)){let w=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===p?w:this.containerParser.parseFeedableSegmentChunk(w);y?.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(I=>{if(s.aborted)n();else if(I)c.fedBytes+=y.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<p)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",jo(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Co(()=>(0,_m.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?cr(this.destroyAbortController.signal,async function*(){let o=Yo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:c}=o,d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Ct(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:dr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Je(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let c=jo(u)?u.size??0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&l(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&l(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3;for(let h of this.segments.values())for(let p of h)if(p.status==="none"&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+u&&d.status==="fed"&&l(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 a={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){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Co(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:dr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Je(this.sourceBuffer)||Je(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),l=e.some(c=>c.from-t<=n&&c.to+t>=o),u=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);l||(u.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Ii=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Nm=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as Ei,assertNever as Fm,fromEvent as qm,merge as Qk,now as Wo,Subscription as zk,ValueSubject as Qo}from"@vkontakte/videoplayer-shared";var Ga=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Qo(void 0);this.lastConnectionReused$=new Qo(void 0);this.lastRequestFirstBytes$=new Qo(void 0);this.abortAllController=new ze;this.subscription=new zk;this.fetchManifest=Ei(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ii(t));let r=yield Qe(t,{signal:this.abortAllController.signal}).catch(xi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Ei(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:l=!1}={}){let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let A=new URL(u,location.href);A.searchParams.append("bytes",`${r.from}-${r.to}`),u=A.toString();break}default:Fm(t)}this.requestQuic&&(u=Ii(u));let d=this.abortAllController.signal,h;if(n){let A=new ze;if(h=Qk(qm(this.abortAllController.signal,"abort"),qm(n,"abort")).subscribe(()=>{try{A.abort()}catch(D){xi(D)}}),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(D){xi(D)}d=A.signal}let p=Wo(),m=yield Qe(u,{priority:s,headers:c,signal:d}).catch(xi),S=Wo();if(!m)return h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-p),!m.ok||!m.body)return h?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!a&&!o)return h?.unsubscribe(),m.arrayBuffer();let[b,v]=m.body.tee(),g=b.getReader();o&&this.throughputEstimator?.trackStream(v,l);let w=0,y=new Uint8Array(0),I=!1,V=A=>{h?.unsubscribe(),I=!0,xi(A)},$=Ei(d,async function*({done:A,value:D}){if(w===0&&this.lastRequestFirstBytes$.next(Wo()-p),d.aborted){h?.unsubscribe();return}if(!A&&D){let E=new Uint8Array(y.length+D.length);E.set(y),E.set(D,y.length),y=E,w+=D.byteLength,a?.(new DataView(y.buffer),w),yield g?.read().then($,V)}}.bind(this));return yield g?.read().then($,V),h?.unsubscribe(),I?null:y.buffer}.bind(this));this.fetchByteRangeRepresentation=Ei(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,l=!1,u,c;e.indexRange&&(u=e.indexRange.from,c=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,a),o=Math.max(c,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 h=new DataView(d,a-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let S;if(l)S=new DataView(d,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!v)return null;S=new DataView(v)}let b=t.parseSegments(S,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=Ei(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=Nm(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:Fm(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},xi=i=>{if(!Si(i))throw i};var Dt=(i,e,t)=>t*e+(1-t)*i,zo=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Um=(i,e,t,r)=>{let a=0,s=t,n=zo(i,e),o=e<r?e:r;for(let l=0;l<o;l++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as Kk,ValueSubject as Hm}from"@vkontakte/videoplayer-shared";var dt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Hm(e.initial),this.debounced$=new Hm(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new J(`raw_${t}`),this.smoothedSeries$=new J(`smoothed_${t}`),this.reportedSeries$=new J(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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)&&(Kk(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 Ya=class extends dt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Dt(this.slow,t,this.params.emaAlphaSlow),this.fast=Dt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var Wa=class extends dt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=zo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,t,this.params.emaAlpha);let a=Um(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var Qa=class extends dt{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?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Mt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ya({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Wa({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 Qa({initial:e,label:"liveEdgeDelay",...t})}};var jm=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Xe=()=>window.ManagedMediaSource||window.MediaSource,za=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Gm=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Ym=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Jm=["timeupdate","progress","play","seeked","stalled","waiting"];var Ja=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Km;this.representationSubscription=new Km;this.state$=new L("none");this.currentVideoRepresentation$=new pe(void 0);this.currentVideoRepresentationInit$=new pe(void 0);this.currentVideoSegmentLength$=new pe(0);this.currentAudioSegmentLength$=new pe(0);this.error$=new zm;this.lastConnectionType$=new pe(void 0);this.lastConnectionReused$=new pe(void 0);this.lastRequestFirstBytes$=new pe(void 0);this.isLive$=new pe(!1);this.liveDuration$=new pe(0);this.liveAvailabilityStartTime$=new pe(void 0);this.bufferLength$=new pe(0);this.liveLoadBufferLength$=new pe(0);this.livePositionFromPlayer$=new pe(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new zm;this.gapWatchdogActive=!1;this.destroyController=new ze;this.initManifest=Ko(this.destroyController.signal,async function*(e,t,r){this.element=e,this.manifestUrlString=K(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:pt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ko(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:pt.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=Cm(e??"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:pt.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;let r=({kind:a,mime:s,codecs:n})=>!!(this.element?.canPlayType?.(s)&&Xe()?.isTypeSupported?.(`${s}; codecs="${n}"`)||a==="text");return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:(0,Xm.default)(Object.entries(t.representations).map(([a,s])=>[a,s.filter(r)]))}}.bind(this));this.initRepresentations=Ko(this.destroyController.signal,async function*(e,t,r){Ot(this.manifest),Ot(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(hr(p,"error").pipe(Ka(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:pt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Ym():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&za())if(r){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=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,manifest:this.manifest};if(this.videoBufferManager=new Ti("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],Qm(t)&&(this.audioBufferManager=new Ti("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),this.bufferManagers.push(this.audioBufferManager)),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(Jo(1e3).subscribe(p=>{if(this.element?.paused){let m=ho(this.manifestUrlString,2);this.manifestUrlString=K(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add(fr(...Jm.filter(p=>p!=="waiting").map(p=>hr(this.element,p))).pipe(Xo(p=>this.element?ct(this.element.buffered,this.element.currentTime*1e3):0),Xk(),Ka(p=>!!p),Zk(p=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(Ka(m=>this.isActiveLowLatency&&!!m)).subscribe(m=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(m=>{if(!this.isActiveLowLatency)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,g=m-S,w=1+Math.sign(g)*v;Math.abs(g)<b?w=1:Math.abs(g)>b*2&&(w=1+Math.sign(g)*v*2),jm(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let S=0;if(m){let b=(this.element?.currentTime??0)*1e3;S=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==S&&this.liveLoadBufferLength$.next(S)}));let p=0;this.representationSubscription.add(Wm({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ew(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:S})=>{if(Ot(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,v=ho(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,w=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,V=this.isActiveLowLatency?S:m,$=3;if(this.isActiveLowLatency?$=0:V<w+I&&V>=w?$=1:v!==0&&V<w&&($=2),isFinite(m)&&(p=m>p?m:p),$===2||$===1){let A=p-(w+y),D=this.normolizeLiveOffset(Math.trunc(v+A/b)),E=Math.abs(D-v),x;!m||E<=this.tuning.dashCmafLive.offsetCalculationError?x=v:D>0&&E>this.tuning.dashCmafLive.offsetCalculationError?x=D:x=0,this.manifestUrlString=K(this.manifestUrlString,x,2)}$!==3&&$!==0&&(p=0,this.updateLive())}))}let o=fr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Xo(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=fr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Xo(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(fr(this.forceEnded$,Wm({allBuffersFull:o,someBufferEnded:l}).pipe(Ka(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:pt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(fr(...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.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(p=>this.source?.addEventListener("sourceopen",p)));let u=this.manifest.duration??0,c=(p,m)=>Math.max(p,m.duration??0),d=this.manifest.representations.audio.reduce(c,u),h=this.manifest.representations.video.reduce(c,u);(d||h)&&(this.source.duration=Math.max(d,h)/1e3),this.audioBufferManager&&Qm(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Jo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:pt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ga({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Mt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){Ot(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=K(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initBuffer(){Ot(this.element),this.state$.setState("running"),this.subscription.add(fr(...Jm.map(e=>hr(this.element,e)),hr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:pt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(hr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(hr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Xr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Jo(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:pt.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t)}seek(e,t){Ot(this.element),Ot(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Xr(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-a<=t&&n.to+a>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var Xa=class{constructor(e,t){this.fov=e,this.orientation=t}};var Za=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=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:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 Zm=`attribute vec2 a_vertex;
37
+ `}),E}return u?.recordSwitch(A),A},lt=mP;var Y=i=>new URL(i).hostname;import{assertNever as Hf,assertNonNullable as jf,combine as OP,debounce as BP,ErrorCategory as Gf,filter as VP,filterChanged as _P,isNonNullable as Co,map as ja,merge as Yf,observableFrom as NP,Subscription as FP,ValueSubject as Do,videoQualityToHeight as qP,videoSizeToQuality as UP}from"@vkontakte/videoplayer-shared";var _f=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},ae=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!_f(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return _f(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as qa,isNullable as gP,assertNonNullable as Wr}from"@vkontakte/videoplayer-shared";import{isNonNullable as Nf,assertNonNullable as Fa,now as bP}from"@vkontakte/videoplayer-shared";function W(){return bP()}function Ao(i){return W()-i}function Ro(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ff(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function sr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,h=!1,p="arraybuffer",m=7e3,S=2e3,b=()=>{if(l)return;Fa(c);let R=Ao(c),q;if(R<S){q=S-R,setTimeout(b,q);return}S*=2,S>m&&(S=m),n&&n.abort(),n=new a,V()},g=R=>(s=R,x),v=R=>(d=R,x),w=()=>(p="json",x),y=()=>{if(!l){if(--u>=0){b(),r&&r();return}l=!0,d&&d(),t&&t()}},I=R=>(h=R,x),V=()=>{c=W(),n=new a,n.open("get",i);let R=0,q,Q=0,Te=()=>(Fa(c),Math.max(c,Math.max(q||0,Q||0)));if(s&&n.addEventListener("progress",k=>{let O=W();s.updateChunk&&k.loaded>R&&(s.updateChunk(Te(),k.loaded-R),R=k.loaded,q=O)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(l)return;Fa(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let O=n.response.byteLength-R;O&&s.updateChunk&&s.updateChunk(Te(),O)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),h){let k=()=>{Fa(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=W(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=p,n.send(),x},x={withBitrateReporting:g,withParallel:I,withJSONResponse:w,withRetryCount:R=>(u=R,x),withRetryInterval:(R,q)=>(Nf(R)&&(S=R),Nf(q)&&(m=q),x),withTimeout:R=>(o=R,x),withFinally:v,send:V,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return x}var Gr=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,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=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 l=s.bytes*n/o;a+=l,s.start=t,s.bytes-=l}}}if(a>0&&r>0){let s=a*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(a)}/${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 Yr=class{constructor(e,t,r,a,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=a,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=W(),a=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=l=>{e._complete=1,e._responseData=l,e._downloadTime=W()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=sr(t,s,()=>a("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=W()}_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=W();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,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,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=a,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 Ua=1e4,Lo=3;var SP=6e4,yP=10,TP=1,IP=500,Qr=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 Gr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ro(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=Ro(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",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.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,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,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)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||qa(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ff(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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 Yr(Lo,Ua,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,l=null,u=null,c=!1,d=()=>{let y=s&&(!c||c===this.rep);return y||t("Not running!"),y},h=(y,I,V)=>{l&&l.abort(),l=sr(this.urlResolver.resolve(y,!1),I,V,()=>this._retryCallback()).withTimeout(Ua).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Lo).withFinally(()=>{l=null}).send()},p=(y,I,V)=>{Wr(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),I,V,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=y=>{let I=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${I}=>${y}`),r.playbackRate=y)},S=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=W()-1e4,$=0;for(let D=0;D<this.bufferStates.length;D++){let E=this.bufferStates[D];y=Math.min(y,E.buf),E.ts<V&&$++}this.bufferStates.splice(0,$),t(`update playback rate; minBuffer=${y} drop=${$} jitter=${this.sourceJitter}`);let A=y-TP;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?m(1.15):A>1?m(1.1):A>.3?m(1.05):m(1)}},g=y=>{let I,V=()=>I&&I.start?I.start.length:0,$=k=>I.start[k]/1e3,A=k=>I.dur[k]/1e3,D=k=>I.fragIndex+k,E=(k,O)=>({chunkIdx:D(k),startTS:$(k),dur:A(k),discontinuity:O}),x=()=>{let k=0;if(I&&I.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,j=O;this.sourceJitter>1&&(j+=this.sourceJitter-1);let se=I.dur.length-1;for(;se>=0&&(j-=I.dur[se],!(j<=0));--se);k=Math.min(se,I.dur.length-1-U),k=Math.max(k,0)}return E(k,!0)},R=k=>{let O=V();if(!(O<=0)){if(qa(k)){for(let U=0;U<O;U++)if($(U)>k)return E(U)}return x()}},q=k=>{let O=V(),U=k?k.chunkIdx+1:0,j=U-I.fragIndex;if(!(O<=0)){if(!k||j<0||j-O>yP)return t(`Resync: offset=${j} bChunks=${O} chunk=`+JSON.stringify(k)),x();if(!(j>=O))return E(U-I.fragIndex,!1)}},Q=(k,O,U)=>{u&&u.abort(),u=sr(this.urlResolver.resolve(k,!0,this.lowLatency),O,U,()=>this._retryCallback()).withTimeout(Ua).withRetryCount(Lo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(k,O)=>{Q(y,U=>{if(!d())return;I=U;let j=!!I.lowLatency;j!==this.lowLatency&&S(j);let se=0;for(let et=0;et<I.dur.length;++et)se+=I.dur[et];se>0&&(Wr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/I.dur.length)),a({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,k(R(O))},()=>this._handleNetworkError())},nextChunk:q}},v=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),Wr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:I,logger:V}=this.params,$=g(e.jidxUrl),A,D,E,x,R=0,q,Q,Te,k=()=>{q&&(clearTimeout(q),q=void 0);let _=Math.max(IP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=R+_,oe=W(),Ie=Math.min(1e4,ne-oe);R=oe;let qe=()=>{u||d()&&$.seek(()=>{d()&&(R=W(),O(),k())})};Ie>0?q=window.setTimeout(()=>{this.paused?k():qe()},Ie):qe()},O=()=>{let _;for(;_=$.nextChunk(x);)x=_,ys(_);let ne=$.nextChunk(E);if(ne){if(E&&ne.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?k():(v(),this._initPlayerWith(e));return}et(ne)}else k()},U=(_,ne)=>{if(!d()||!this.sourceBuffer)return;let oe,Ie,qe,gr=ue=>{window.setTimeout(()=>{d()&&U(_,ne)},ue)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),gr(100);else{let ue=W(),tt=I.currentTime;!this.paused&&I.buffered.length>1&&Q===tt&&ue-Te>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),Q!==tt&&(Q=tt,Te=ue);let Ee=this._getBufferSizeSec();if(Ee>30)V(`Buffered ${Ee} seconds; delaying appendBuffer`),gr(2e3);else try{this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(this.bufferStates.push({ts:ue,buf:Ee}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(De){if(De.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),qe=this.sourceBuffer.buffered.length,qe!==0&&(oe=this.sourceBuffer.buffered.start(0),Ie=tt,Ie-oe>4&&this.sourceBuffer.remove(oe,Ie-3)),gr(1e3);else throw De}}},j=()=>{D&&A&&(V([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(E)]),U(D,function(){D=null,O()}))},se=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),et=_=>{d()&&p(se(_),(ne,oe)=>{if(d()){if(oe/=1e3,D=ne,E=_,n=_.startTS,oe){let Ie=Math.min(10,_.dur/oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}j()}},()=>this._handleNetworkError())},ys=_=>{d()&&(Wr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(_),!1)))},qi=_=>{d()&&(e.cachedHeader=_,U(_,()=>{A=!0,j()}))};s=!0,$.seek(_=>{if(d()){if(R=W(),!_){k();return}x=_,!gP(y)||_.startTS>y?et(_):(E=_,O())}},y),e.cachedHeader?qi(e.cachedHeader):h(e.headerUrl,qi,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),qa(a)&&(a+=.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,Wr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return qa(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(h,p)=>{let m=W();if(this.chunkRateEstimator.addInterval(h,m,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:b}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&Ao(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&u(),p},notifySwitch:d=>{let h=W();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=sr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ua).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;ae(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((l,u)=>{l.video&&a.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=u,o.push(l))}),o.sort(function(l,u){return l.video&&u.video?u.video.height-l.video.height:u.bitrate-l.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))},SP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as EP,filter as qf,fromEvent as xP,interval as PP,isHigher as kP,isInvariantQuality as wP,isLower as AP,merge as RP,Subject as Uf,Subscription as LP}from"@vkontakte/videoplayer-shared";var $o=class{constructor(){this.onDroopedVideoFramesLimit$=new Uf;this.subscription=new LP;this.playing=!1;this.tracks=[];this.forceChecker$=new Uf;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!wP(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&kP(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??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.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(xP(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=PP(this.droppedFramesChecker.checkTime).pipe(qf(()=>this.playing),qf(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(EP(this.droppedFramesChecker.checkTime)),r=RP(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){let t=Object.entries(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>AP(r,a)?-1:1)?.[0]?.[0];return 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}},Ha=$o;import{map as $P,Observable as CP}from"@vkontakte/videoplayer-shared";import{fromEvent as DP}from"@vkontakte/videoplayer-shared";var zr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var MP=(i,e)=>new CP(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||zr()))},{...r,...e});a.observe(i);let s=DP(document,"visibilitychange").pipe($P(n=>!document.hidden||zr())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),ge=MP;var HP=["paused","playing","ready"],jP=["paused","playing","ready"],Kr=class{constructor(e){this.subscription=new FP;this.videoState=new L("stopped");this.representations$=new Do([]);this.textTracksManager=new be;this.droppedFramesManager=new Ha;this.maxSeekBackTime$=new Do(1/0);this.zeroTime$=new Do(void 0);this.liveOffset=new Ye;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Gf.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=ot(a.name)??UP(a.video),o=a.bitrate/1e3,l={...a.video};if(!n)continue;let u={id:s,quality:n,bitrate:o,size:l};r.push({track:u,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Co(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);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(),a=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(jP.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&HP.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(K(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 l=a?.from;l&&l==="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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.dash.reinit(K(this.params.source.url,l))}return;default:return Hf(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Gf.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Yf(this.videoState.stateChangeStarted$.pipe(ja(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ja(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ee(e.container),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(Y(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=ie(this.video);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$:this.representations$.pipe(ja(a=>a.map(({track:s})=>s)))}),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.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(_P(),ja(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(OP({zeroTime:this.zeroTime$.pipe(VP(Co)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(_e(this.video,this.params.desiredState.isLooped,t)).add(re(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.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(ge(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&qP(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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":this.params.desiredState.playbackState.getTransition()?.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 Hf(a.to)}},t)).add(Yf(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,NP(["init"])).pipe(BP(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),te(this.video)}createLiveDashPlayer(){let e=new Qr({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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Co(t)?t:lt(e.map(({track:u})=>u),{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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let u=e.find(({track:c})=>c.id===s)?.representation;jf(u,"Representations missing"),this.dash.startPlay(u,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;jf(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(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(K(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Wf=Kr;var ct=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as lw,assertNonNullable as sb,debounce as cw,ErrorCategory as ru,filter as dw,filterChanged as nb,fromEvent as pw,isLowerOrEqual as ob,isNonNullable as hw,videoSizeToQuality as ub,map as iu,merge as is,observableFrom as fw,observeElementSize as mw,once as bw,Subscription as vw,ValueSubject as lb}from"@vkontakte/videoplayer-shared";var Ga=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 a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];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}},nr=class extends Ga{constructor(){super(),this.listeners||Ga.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)}},Jr=class{constructor(){Object.defineProperty(this,"signal",{value:new nr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?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>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Jr.prototype[Symbol.toStringTag]="AbortController",nr.prototype[Symbol.toStringTag]="AbortSignal");function Ya(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Mo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Ya({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(u,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(u,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(l,u)=>{let c=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([h,n(l,u)])}return n(l,u)},Request:s}}var Xr=Ya({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Qf=Xr?Mo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Qe=Xr?Qf.fetch:window.fetch,kM=Xr?Qf.Request:window.Request,ze=Xr?Jr:window.AbortController,wM=Xr?nr:window.AbortSignal;var rb=Oe(Ea(),1);var Zr=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};import{abortable as Zo,assertNonNullable as Ot,combine as Jm,ErrorCategory as pt,filter as Xa,filterChanged as rw,fromEvent as hr,interval as eu,isNonNullable as Xm,map as tu,merge as fr,Subject as Zm,Subscription as eb,tap as iw,throttle as aw,ValueSubject as pe}from"@vkontakte/videoplayer-shared";var pr=Oe(_a(),1);var GP=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},YP=i=>window.clearTimeout(i),zf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Oo=zf?GP:window.requestIdleCallback,LM=zf?YP:window.cancelIdleCallback;var Um=Oe(Oa(),1);import{assertNever as WP,CurrentClientBrowser as QP,ErrorCategory as Kf,getCurrentBrowser as zP,Subject as Jf}from"@vkontakte/videoplayer-shared";var KP=16,Xf=!1;try{Xf=zP().browser===QP.Safari&&parseInt(navigator.userAgent.match(/Version\/(\d+)/)?.[1]??"",10)<=KP}catch(i){console.error(i)}var Bo=class{constructor(e){this.bufferFull$=new Jf;this.error$=new Jf;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Kf.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Xf&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!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(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Kf.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:WP(t)}}},Zf=Bo;var Vo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as cr,assertNever as Qk,assertNonNullable as Ke,ErrorCategory as dr,fromEvent as Qo,getExponentialDelay as zo,once as zk,isNonNullable as qm,isNullable as Je,Subject as Kk,Subscription as Jk,ValueSubject as Ti}from"@vkontakte/videoplayer-shared";var B=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 a=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,a),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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 or=class extends B{};var ei=class extends B{};var ti=class extends B{constructor(t,r){super(t,r);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let a=this.size-this.cursor;for(;a;){let s=this.readString(4);this.compatibleBrands.push(s),a-=4}}};var ri=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ii=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends B{constructor(t,r){super(t,r);this.data=this.content}};var H=class extends B{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var At=class extends H{constructor(t,r){super(t,r);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 a=0;a<this.referenceCount;a++){let s=this.readUint32(),n=s>>>31,o=s<<1>>>1,l=this.readUint32();s=this.readUint32();let u=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:u,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var si=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ni=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oi=class extends H{constructor(t,r){super(t,r);switch(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 ui=class extends H{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var li=class extends H{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ci=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var di=class extends H{constructor(t,r){super(t,r);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 pi=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fi=class extends H{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var mi=class extends B{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var bi=class extends H{constructor(t,r){super(t,r);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 vi=class extends H{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 gi=class extends H{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 a=0;a<this.sampleCount;a++)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 XP={ftyp:ti,moov:ri,moof:ii,mdat:ai,sidx:At,trak:si,mdia:ci,mfhd:fi,tkhd:di,traf:mi,tfhd:bi,tfdt:vi,trun:gi,minf:pi,sv3d:ni,st3d:oi,prhd:ui,proj:hi,equi:li,uuid:ei,unknown:or},Rt=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=XP[e];return r?new r(t,new i):new or(t,new i)}};var ur=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],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 ek=new TextDecoder("ascii"),tk=i=>ek.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",rk=i=>{let e=new At(i,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.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})},ik=(i,e)=>{let r=new Rt().parse(i),a=new ur(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,d=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,d)},ak=(i,e)=>{let r=new Rt().parse(i),s=new ur(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"),l=s[s.length-1].children.find(d=>d.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((d,h)=>d+h,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},sk=i=>{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 Rt().parse(i),a=new ur(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let l=a.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},em={validateData:tk,parseInit:sk,getIndexRange:()=>{},parseSegments:rk,parseFeedableSegmentChunk:ik,getSegmentEndTime:ak};import{assertNonNullable as No,isNonNullable as am,isNullable as ok}from"@vkontakte/videoplayer-shared";import{assertNever as nk}from"@vkontakte/videoplayer-shared";var tm={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"}},rm=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Si(i,t),a=r in tm,s=a?tm[r].type:"binary",n=i.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 l=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,c=Si(l),d=u*2**((o-1)*8)+c,h=t+o,p;return h+d>i.byteLength?p=new DataView(i.buffer,i.byteOffset+h):p=new DataView(i.buffer,i.byteOffset+h,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},Si=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Le=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Si(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:nk(e)}},Lt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=rm(r);if(!e(a))return;a.type==="master"&&Lt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},im=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=rm(i);return Lt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Le(o,n):s===17026?t=Le(o,n):s===17029&&(r=Le(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var sm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],uk=[231,22612,22743,167,171,163,160,175],lk=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Lt(i,({tag:h,type:p,value:m,valueSize:S})=>{if(h===21419){let b=Le(m,p);u=Si(b)}else h!==21420&&(u=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+S):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Le(m,p):h===17545?a=Le(m,p):h===21420&&u===475249515?l=Le(m,p):h===374648427?Lt(m,({tag:b,type:g,value:v})=>b===30321?(c=Le(v,g)===1,!1):!0):s&&n&&sm.includes(h)&&(o=!0),!o}),No(e,"Failed to parse webm Segment start"),No(t,"Failed to parse webm Segment end"),No(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:l,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ck=i=>{if(ok(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},dk=(i,e)=>{let t=!1,r=!1,a=o=>am(o.time)&&am(o.position),s=[],n;return Lt(i,({tag:o,type:l,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Le(u,l));break;case 183:break;case 241:n&&(n.position=Le(u,l));break;default:t&&sm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:c}=o,d=s[l+1];return{status:"none",time:{from:u,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},pk=i=>{let e=0,t=!1;try{Lt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):uk.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=[163,160,175].includes(r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},nm={validateData:im,parseInit:lk,getIndexRange:ck,parseSegments:dk,parseFeedableSegmentChunk:pk};var jo=Oe(Lm(),1);import{isNonNullable as Cm,isNullable as Dm}from"@vkontakte/videoplayer-shared";var $m=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Mm=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*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(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},$t=(i,e)=>{let t=i;t=(0,jo.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,jo.default)(t,n,(o,l)=>Dm(s)?o:Dm(l)?s:s.padStart(parseInt(l,10),"0"))}return t},Bm=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=s.querySelector("BaseURL")?.textContent?.trim()??"",l=n.children,u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,h,p=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(p)h=Mm(p);else if(m){let y=Mm(m);Cm(y)&&(h=y)}else b&&(h=parseInt(b,10));let g=0,v=s.getAttribute("profiles")?.split(",")??[],w=v.includes("urn:webm:dash:profile:webm-on-demand:2012")||v.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let y of l){let I=y.getAttribute("mimeType"),V=y.getAttribute("codecs"),$=y.getAttribute("contentType")??I?.split("/")[0],A=y.getAttribute("profiles")?.split(",")??[],D=y.querySelectorAll("Representation"),E=y.querySelector("SegmentTemplate");if($==="text"){for(let x of D){let R=x.getAttribute("id")||"",q=y.getAttribute("lang"),Q=y.getAttribute("label"),Te=x.querySelector("BaseURL")?.textContent?.trim()??"",k=new URL(Te||o,e).toString(),O=R.includes("_auto");a.text.push({id:R,lang:q,label:Q,isAuto:O,kind:"text",url:k})}continue}for(let x of D){let R=x.getAttribute("mimeType")??I,q=x.getAttribute("codecs")??V??"",Q=x.getAttribute("contentType")??R?.split("/")[0]??$,Te=y.getAttribute("profiles")?.split(",")??[],k=parseInt(x.getAttribute("width")??"",10),O=parseInt(x.getAttribute("height")??"",10),U=parseInt(x.getAttribute("bandwidth")??"",10)/1e3,j=x.getAttribute("frameRate")??"",se=x.getAttribute("quality")??void 0,et=j?$m(j):void 0,ys=x.getAttribute("id")??(g++).toString(10),qi=Q==="video"?`${O}p`:Q==="audio"?`${U}Kbps`:q,_=`${ys}@${qi}`,ne=x.querySelector("BaseURL")?.textContent?.trim()??"",oe=new URL(ne||o,e).toString(),Ie=[...v,...A,...Te],qe,gr=x.querySelector("SegmentBase"),ue=x.querySelector("SegmentTemplate")??E;if(gr){let Ee=x.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[De,Ts]=Ee.split("-").map(Ft=>parseInt(Ft,10)),rt={from:De,to:Ts},Sr=x.querySelector("SegmentBase")?.getAttribute("indexRange"),[Is,Ui]=Sr?Sr.split("-").map(Ft=>parseInt(Ft,10)):[],yr=Sr?{from:Is,to:Ui}:void 0;qe={type:"byteRange",url:oe,initRange:rt,indexRange:yr}}else if(ue){let Ee={representationId:x.getAttribute("id")??void 0,bandwidth:x.getAttribute("bandwidth")??void 0},De=parseInt(ue.getAttribute("timescale")??"",10),Ts=ue.getAttribute("initialization")??"",rt=ue.getAttribute("media"),Sr=parseInt(ue.getAttribute("startNumber")??"",10)??1,Is=$t(Ts,Ee);if(!rt)throw new ReferenceError("No media attribute in SegmentTemplate");let Ui=ue.querySelectorAll("SegmentTimeline S")??[],yr=[],Ft=0,Es="",xs=0;if(Ui.length){let Hi=Sr,xe=0;for(let qt of Ui){let Me=parseInt(qt.getAttribute("d")??"",10),bt=parseInt(qt.getAttribute("r")??"",10)||0,ji=parseInt(qt.getAttribute("t")??"",10);xe=Number.isFinite(ji)?ji:xe;let Ps=Me/De*1e3,rv=xe/De*1e3;for(let Gi=0;Gi<bt+1;Gi++){let iv=$t(rt,{...Ee,segmentNumber:Hi.toString(10),segmentTime:(xe+Gi*Me).toString(10)}),yu=(rv??0)+Gi*Ps,av=yu+Ps;Hi++,yr.push({time:{from:yu,to:av},url:iv})}xe+=(bt+1)*Me,Ft+=(bt+1)*Ps}xs=xe/De*1e3,Es=$t(rt,{...Ee,segmentNumber:Hi.toString(10),segmentTime:xe.toString(10)})}else if(Cm(h)){let xe=parseInt(ue.getAttribute("duration")??"",10)/De*1e3,qt=Math.ceil(h/xe),Me=0;for(let bt=1;bt<qt;bt++){let ji=$t(rt,{...Ee,segmentNumber:bt.toString(10),segmentTime:Me.toString(10)});yr.push({time:{from:Me,to:Me+xe},url:ji}),Me+=xe}xs=Me,Es=$t(rt,{...Ee,segmentNumber:qt.toString(10),segmentTime:Me.toString(10)})}let tv={time:{from:xs,to:1/0},url:Es};qe={type:"template",baseUrl:oe,segmentTemplateUrl:rt,initUrl:Is,totalSegmentsDurationMs:Ft,segments:yr,nextSegmentBeyondManifest:tv,timescale:De}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Q||!R)continue;let tt={video:"video",audio:"audio",text:"text"}[Q];tt&&a[tt].push({id:_,kind:tt,segmentReference:qe,profiles:Ie,duration:h,bitrate:U,mime:R,codecs:q,width:k,height:O,fps:et,quality:se})}}return{dynamic:u,liveAvailabilityStartTime:d,duration:h,container:w,representations:a}};var Yo=Oe(_a(),1);import{videoSizeToQuality as Wk}from"@vkontakte/videoplayer-shared";var Vm=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{let n=(s?ot(s):void 0)??Wk({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},_m=({id:i,bitrate:e})=>({id:i,bitrate:e}),Nm=(i,e,t)=>{let r=e.indexOf(t);return(0,Yo.default)(i,Math.round(i.length*r/e.length))??(0,Yo.default)(i,-1)},Fm=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),Wo=i=>"url"in i,Ct=i=>i.type==="template",yi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Ii=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Ti(0);this.onLastSegment$=new Ti(!1);this.fullyBuffered$=new Ti(!1);this.playingRepresentation$=new Ti(void 0);this.playingRepresentationInit$=new Ti(void 0);this.error$=new Kk;this.gaps=[];this.subscription=new Jk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ze;this.destroyAbortController=new ze;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=cr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Zf(this.sourceBuffer),this.subscription.add(Qo(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:dr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(Qo(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:dr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,Vo(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),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),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Ke(r,"No init buffer for starting representation"),Ke(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=cr(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);Ke(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Je(a)||Je(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Ke(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();qm(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=cr(this.destroyAbortController.signal,async function*(e){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let o of this.representations.keys()){let l=e.find(d=>d.id===o);l&&this.representations.set(o,l);let u=this.representations.get(o);if(!u||!Ct(u.segmentReference))return;let c=this.getActualLiveStartingSegments(u.segmentReference);this.segments.set(u.id,c)}let t=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(t);Ke(r);let a=this.segments.get(t);Ke(a,"No segments for starting representation");let s=this.initData.get(t);if(Ke(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));switch(this.fetcher=s,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=l,this.isLive=!!c?.dynamic,this.container=r,r){case"mp4":this.containerParser=em;break;case"webm":this.containerParser=nm;break;default:Qk(r)}this.initData=new Map(a.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(d=>[d.id,d])),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 ze,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Je(e)||Je(this.downloadingRepresentationId)||Je(this.playingRepresentationId)||Je(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ke(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(u=>e>=u.time.from&&e<u.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ct(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Vo(this.sourceBuffer.buffered)>=this.bufferLimit){let u=ct(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))u="high";else{let c=(0,pr.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(o,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&ct(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,pr.default)(r,-1);l&&l.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===l))}searchGaps(e,t){this.gaps=[];let r=0,a=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+a}),r=s.time.to;qm(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,a=[],s=0,n=t.length-1;do a.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()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){for(let t of e?.representations[this.kind].values()??[]){if(!t||!Ct(t.segmentReference))return;let r=t.segmentReference.segments.map(o=>({...o,status:"none",size:void 0})),a=this.segments.get(t.id)??[],s=(0,pr.default)(a,-1)?.time.to??0,n=r?.findIndex(o=>Math.floor(s)>=Math.floor(o.time.from)&&Math.floor(s)<=Math.floor(o.time.to));if(n===-1){this.liveUpdateSegmentIndex=0;let o=this.getActualLiveStartingSegments(t.segmentReference);this.segments.set(t.id,o)}else{let o=r.slice(n+1);this.segments.set(t.id,[...a,...o])}}}updateLowLatencyLive(e){if(this.isActiveLowLatency())for(let t of this.representations.values()){let r=t.segmentReference;if(!Ct(r))return;let a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),s=$t(r.segmentTemplateUrl,{segmentTime:a}),n=this.segments.get(t.id)??[],o=n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));o&&(o.time.to=e.segment.time.to),!!n.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||n.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:s})}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.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(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}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(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let S=h<=r&&p>=r,b=h>r||S||m===0&&r===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=r+g||p<=r+g;return(d==="none"||d==="partially_ejected"&&b&&v&&this.sourceBuffer&&!Zr(this.sourceBuffer.buffered,r))&&b&&v});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=u||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await cr(o,async function*(){let c=zo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(this.isActiveLowLatency()){let h=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,h)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),yi(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await cr(n,async function*(){let l=zo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),Qo(window,"online").pipe(zk()).subscribe(()=>{u(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(l){this.abortActiveSegments(e),yi(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ct(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,pr.default)(e,0).byte.from,to:(0,pr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,l)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:dr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ct(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 a=r.toString(),{signal:s}=this.downloadAbortController,n=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:dr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:l,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(u,this.isLive);c?.byteLength&&(l.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let l=o.segmentReference.type,u=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,h=l==="byteRange",p=h?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!h||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let S=h?d.byte.from-r:0,b=h?d.byte.to-r:e.byteLength,g=S<a,v=b<=a;if(d.status==="downloading"&&g&&v){d.status="downloaded";let w=new DataView(e.buffer,e.byteOffset+S,p);this.sourceBufferTaskQueue.append(w,s).then(y=>y&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(c.loadedBytes=Math.min(p,a-S),c.loadedBytes>c.feedingBytes)){let w=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===p?w:this.containerParser.parseFeedableSegmentChunk(w);y?.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(I=>{if(s.aborted)n();else if(I)c.fedBytes+=y.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<p)return;n()}}))}}}onSegmentFullyAppended(e,t){this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Wo(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Oo(()=>(0,Um.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?cr(this.destroyAbortController.signal,async function*(){let o=zo(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:c}=o,d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Ct(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:dr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Je(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let c=Wo(u)?u.size??0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&l(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&l(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3;for(let h of this.segments.values())for(let p of h)if(p.status==="none"&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+u&&d.status==="fed"&&l(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 a={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){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Oo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:dr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Je(this.sourceBuffer)||Je(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;for(let r of this.segments.values())for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),l=e.some(c=>c.from-t<=n&&c.to+t>=o),u=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);l||(u.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Ei=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Hm=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as xi,assertNever as jm,fromEvent as Gm,merge as Xk,now as Ko,Subscription as Zk,ValueSubject as Jo}from"@vkontakte/videoplayer-shared";var Wa=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Jo(void 0);this.lastConnectionReused$=new Jo(void 0);this.lastRequestFirstBytes$=new Jo(void 0);this.abortAllController=new ze;this.subscription=new Zk;this.fetchManifest=xi(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ei(t));let r=yield Qe(t,{signal:this.abortAllController.signal}).catch(Pi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=xi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:l=!1}={}){let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let A=new URL(u,location.href);A.searchParams.append("bytes",`${r.from}-${r.to}`),u=A.toString();break}default:jm(t)}this.requestQuic&&(u=Ei(u));let d=this.abortAllController.signal,h;if(n){let A=new ze;if(h=Xk(Gm(this.abortAllController.signal,"abort"),Gm(n,"abort")).subscribe(()=>{try{A.abort()}catch(D){Pi(D)}}),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(D){Pi(D)}d=A.signal}let p=Ko(),m=yield Qe(u,{priority:s,headers:c,signal:d}).catch(Pi),S=Ko();if(!m)return h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(S-p),!m.ok||!m.body)return h?.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!a&&!o)return h?.unsubscribe(),m.arrayBuffer();let[b,g]=m.body.tee(),v=b.getReader();o&&this.throughputEstimator?.trackStream(g,l);let w=0,y=new Uint8Array(0),I=!1,V=A=>{h?.unsubscribe(),I=!0,Pi(A)},$=xi(d,async function*({done:A,value:D}){if(w===0&&this.lastRequestFirstBytes$.next(Ko()-p),d.aborted){h?.unsubscribe();return}if(!A&&D){let E=new Uint8Array(y.length+D.length);E.set(y),E.set(D,y.length),y=E,w+=D.byteLength,a?.(new DataView(y.buffer),w),yield v?.read().then($,V)}}.bind(this));return yield v?.read().then($,V),h?.unsubscribe(),I?null:y.buffer}.bind(this));this.fetchByteRangeRepresentation=xi(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,l=!1,u,c;e.indexRange&&(u=e.indexRange.from,c=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,a),o=Math.max(c,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 h=new DataView(d,a-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=e.indexRange??t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let S;if(l)S=new DataView(d,m.from-n,m.to-m.from+1);else{let g=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!g)return null;S=new DataView(g)}let b=t.parseSegments(S,p,m);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=xi(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){let{type:t,reused:r}=Hm(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:jm(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Pi=i=>{if(!yi(i))throw i};var Dt=(i,e,t)=>t*e+(1-t)*i,Xo=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Ym=(i,e,t,r)=>{let a=0,s=t,n=Xo(i,e),o=e<r?e:r;for(let l=0;l<o;l++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as ew,ValueSubject as Wm}from"@vkontakte/videoplayer-shared";var dt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Wm(e.initial),this.debounced$=new Wm(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new J(`raw_${t}`),this.smoothedSeries$=new J(`smoothed_${t}`),this.reportedSeries$=new J(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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)&&(ew(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 Qa=class extends dt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Dt(this.slow,t,this.params.emaAlphaSlow),this.fast=Dt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var za=class extends dt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=Xo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,t,this.params.emaAlpha);let a=Ym(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var Ka=class extends dt{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?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Mt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Qa({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new za({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 Ka({initial:e,label:"liveEdgeDelay",...t})}};var Qm=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Xe=()=>window.ManagedMediaSource||window.MediaSource,Ja=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),zm=()=>!!(window.MediaSource&&window.MediaStreamTrack&&window.SourceBuffer?.prototype?.appendBuffer),Km=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var tb=["timeupdate","progress","play","seeked","stalled","waiting"];var Za=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new eb;this.representationSubscription=new eb;this.state$=new L("none");this.currentVideoRepresentation$=new pe(void 0);this.currentVideoRepresentationInit$=new pe(void 0);this.currentVideoSegmentLength$=new pe(0);this.currentAudioSegmentLength$=new pe(0);this.error$=new Zm;this.lastConnectionType$=new pe(void 0);this.lastConnectionReused$=new pe(void 0);this.lastRequestFirstBytes$=new pe(void 0);this.isLive$=new pe(!1);this.liveDuration$=new pe(0);this.liveAvailabilityStartTime$=new pe(void 0);this.bufferLength$=new pe(0);this.liveLoadBufferLength$=new pe(0);this.livePositionFromPlayer$=new pe(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Zm;this.gapWatchdogActive=!1;this.destroyController=new ze;this.initManifest=Zo(this.destroyController.signal,async function*(e,t,r){this.element=e,this.manifestUrlString=K(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:pt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Zo(this.destroyController.signal,async function*(){let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:pt.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=Bm(e??"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:pt.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;let r=({kind:a,mime:s,codecs:n})=>!!(this.element?.canPlayType?.(s)&&Xe()?.isTypeSupported?.(`${s}; codecs="${n}"`)||a==="text");return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:(0,rb.default)(Object.entries(t.representations).map(([a,s])=>[a,s.filter(r)]))}}.bind(this));this.initRepresentations=Zo(this.destroyController.signal,async function*(e,t,r){Ot(this.manifest),Ot(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(hr(p,"error").pipe(Xa(m=>!!this.element?.played.length)).subscribe(m=>{this.error$.next({id:"VideoSource",category:pt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Km():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ja())if(r){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=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,manifest:this.manifest};if(this.videoBufferManager=new Ii("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],Xm(t)&&(this.audioBufferManager=new Ii("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),this.bufferManagers.push(this.audioBufferManager)),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(eu(1e3).subscribe(p=>{if(this.element?.paused){let m=bo(this.manifestUrlString,2);this.manifestUrlString=K(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add(fr(...tb.filter(p=>p!=="waiting").map(p=>hr(this.element,p))).pipe(tu(p=>this.element?ct(this.element.buffered,this.element.currentTime*1e3):0),rw(),Xa(p=>!!p),iw(p=>{this.stallWatchdogSubscription?.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(Xa(m=>this.isActiveLowLatency&&!!m)).subscribe(m=>this.liveEstimatedDelay.next(m))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(m=>{if(!this.isActiveLowLatency)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=m-S,w=1+Math.sign(v)*g;Math.abs(v)<b?w=1:Math.abs(v)>b*2&&(w=1+Math.sign(v)*g*2),Qm(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{let S=0;if(m){let b=(this.element?.currentTime??0)*1e3;S=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==S&&this.liveLoadBufferLength$.next(S)}));let p=0;this.representationSubscription.add(Jm({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(aw(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:S})=>{if(Ot(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=bo(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,w=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,V=this.isActiveLowLatency?S:m,$=3;if(this.isActiveLowLatency?$=0:V<w+I&&V>=w?$=1:g!==0&&V<w&&($=2),isFinite(m)&&(p=m>p?m:p),$===2||$===1){let A=p-(w+y),D=this.normolizeLiveOffset(Math.trunc(g+A/b)),E=Math.abs(D-g),x;!m||E<=this.tuning.dashCmafLive.offsetCalculationError?x=g:D>0&&E>this.tuning.dashCmafLive.offsetCalculationError?x=D:x=0,this.manifestUrlString=K(this.manifestUrlString,x,2)}$!==3&&$!==0&&(p=0,this.updateLive())}))}let o=fr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(tu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=fr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(tu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(fr(this.forceEnded$,Jm({allBuffersFull:o,someBufferEnded:l}).pipe(Xa(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:pt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(fr(...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.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(p=>this.source?.addEventListener("sourceopen",p)));let u=this.manifest.duration??0,c=(p,m)=>Math.max(p,m.duration??0),d=this.manifest.representations.audio.reduce(c,u),h=this.manifest.representations.video.reduce(c,u);(d||h)&&(this.source.duration=Math.max(d,h)/1e3),this.audioBufferManager&&Xm(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=eu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:pt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Wa({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Mt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){Ot(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=K(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest?.representations.video),await this.audioBufferManager?.seekLive(this.manifest?.representations.audio))}initBuffer(){Ot(this.element),this.state$.setState("running"),this.subscription.add(fr(...tb.map(e=>hr(this.element,e)),hr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:pt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(hr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(hr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Zr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=eu(1e3).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:pt.FATAL,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t)}seek(e,t){Ot(this.element),Ot(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Zr(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3}stop(){this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){return this.manifest?.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-a<=t&&n.to+a>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var es=class{constructor(e,t){this.fov=e,this.orientation=t}};var ts=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=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:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 ib=`attribute vec2 a_vertex;
38
38
  attribute vec2 a_texel;
39
39
 
40
40
  varying vec2 v_texel;
@@ -45,7 +45,7 @@ void main(void) {
45
45
  // save texel vector to pass to fragment shader
46
46
  v_texel = a_texel;
47
47
  }
48
- `;var eb=`#ifdef GL_ES
48
+ `;var ab=`#ifdef GL_ES
49
49
  precision highp float;
50
50
  precision highp int;
51
51
  #else
@@ -88,5 +88,5 @@ void main(void) {
88
88
  // sample using new coordinates
89
89
  gl_FragColor = texture2D(u_texture, tc);
90
90
  }
91
- `;var es=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Xa(this.params.fov,this.params.orientation),this.cameraRotationManager=new Za(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Zm,this.gl.VERTEX_SHADER),r=this.createShader(eb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,l=t-a,u=e+r,c=t+a,d=e-r,h=t+a;return[s,n,o,l,u,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Vt=class{constructor(e){this.subscription=new hw;this.videoState=new L("stopped");this.elementSize$=new sb(void 0);this.textTracksManager=new be;this.droppedFramesManager=new qa;this.videoTracks$=new sb([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Va;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&T(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return sw(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new es(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ee(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ja({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ie(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Zo.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,l)=>this.subscription.add(o.subscribe(l,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();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$:this.videoTracks$.pipe(eu(u=>u.map(({track:c})=>c)))}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ow(lw),pw()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(_e(this.video,t.isLooped,a)),this.subscription.add(re(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(me(this.video,t.playbackRate,r.playbackRateState$,a)),s(dw(this.video),this.elementSize$),s(ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){let c=[];this.audioTracks=[],this.textTracks=[];let d=this.player.getRepresentations();tb(d,"Manifest not loaded or empty");let h=Array.from(d.audio).sort((b,v)=>v.bitrate-b.bitrate),p=Array.from(d.video).sort((b,v)=>v.bitrate-b.bitrate),m=Array.from(d.text);if(!this.params.tuning.isAudioDisabled)for(let b of h){let v=Mm(b);v&&this.audioTracks.push({track:v,representation:b})}for(let b of p){let v=Dm(b);if(v){c.push({track:v,representation:b});let g=!this.params.tuning.isAudioDisabled&&Om(h,p,b);g&&this.audioRepresentations.set(b.id,g)}}this.videoTracks$.next(c);for(let b of m){let v=Bm(b);v&&this.textTracks.push({track:v,representation:b})}this.params.output.availableVideoTracks$.next(c.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));let S=this.selectVideoRepresentation();tb(S),this.player.initRepresentations(S.id,this.audioRepresentations.get(S.id)?.id,this.params.sourceHls)}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:Zo.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(ts(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,uw(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);let p=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let S=d.id;!this.params.output.elementVisible$.getValue()&&p&&(S=this.videoTracks$.getValue().map(v=>v.representation).sort((v,g)=>g.bitrate-v.bitrate).filter(v=>{let g=ab(v),w=ab(d);if(g&&w)return ib(g,w)&&ib(g,m)}).map(v=>v.id)[0]),this.player.switchRepresentation("video",S).catch(n);let b=this.audioRepresentations.get(d.id);b&&this.player.switchRepresentation("audio",b.id).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(rb(),eu(u=>u&&this.videoTracks$.getValue().find(({representation:{id:c}})=>c===u)?.track)).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(eu(({to:u})=>u==="ready"),rb());this.subscription.add(ts(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(ts(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=ts(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cw(["init"])).pipe(nw(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,r=this.videoTracks$.getValue().find(({track:{id:d}})=>d===t)?.track,a=this.params.output.currentVideoTrack$.getValue(),s=ct(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(s/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),l=Math.max(r&&!e?this.audioRepresentations.get(r.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),u=lt(this.videoTracks$.getValue().map(({track:d})=>d),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:l,forwardBufferHealth:o,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?u??r:r??u;return c&&this.videoTracks$.getValue().find(({track:d})=>d===c)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ae(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zo.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),te(this.video)}};var Pi=class extends Vt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as nb,interval as fw,map as mw}from"@vkontakte/videoplayer-shared";var ki=class extends Vt{constructor(e){super(e),this.liveOffset=new Ye}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(nb({interval:fw(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let s=e.position$.getValue()+(a-1);e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add(nb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(mw(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var ub=Oe(Da(),1);import{assertNever as wi,assertNonNullable as ob,debounce as bw,ErrorCategory as rs,filter as gw,isNonNullable as vw,isNullable as Sw,map as tu,merge as yw,Observable as Tw,observableFrom as Iw,Subscription as Ew,videoSizeToQuality as xw}from"@vkontakte/videoplayer-shared";var $e={};var mr=(i,e)=>new Tw(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ai=class{constructor(e){this.subscription=new Ew;this.videoState=new L("initializing");this.textTracksManager=new be;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:wi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:wi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:wi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:wi(e)}break;default:wi(t)}};this.video=ee(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),te(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:rs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,ub.default)(import("hls.js").then(a=>{e||($e.Hls=a.default,$e.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){ob($e.Hls,"hls.js not loaded"),this.hls=new $e.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){ob($e.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:rs.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ie(this.video),s=(u,c)=>this.subscription.add(u.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(_e(this.video,e.isLooped,r)),this.subscription.add(re(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(me(this.video,e.playbackRate,a.playbackRateState$,r)),s(ve(this.video),t.elementVisible$),this.subscription.add(mr(this.hls,$e.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:rs.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(mr(this.hls,$e.Events.MANIFEST_PARSED).pipe(tu(({levels:u})=>u.reduce((c,d)=>{let h=d.name||d.height.toString(10),{width:p,height:m}=d,S=ot(d.attrs.QUALITY??"")??xw({width:p,height:m});if(!S)return c;let b=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:S,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:b};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(mr(this.hls,$e.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang,S="internal";c.push({id:h,url:p,language:m,type:S})}e.internalTextTracks.startTransitionTo(c)}}),s(mr(this.hls,$e.Events.LEVEL_LOADING).pipe(tu(({url:u})=>Y(u))),t.hostname$),s(mr(this.hls,$e.Events.FRAG_CHANGED),u=>{let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(at(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=mr(this.hls,$e.Events.LEVEL_SWITCHED).pipe(tu(({level:u})=>n(this.hls.levels[u])));o.pipe(gw(vw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(at(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(Sw(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=yw(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Iw(["init"])).pipe(bw(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ae(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rs.DOM,thrown:t}))||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0)}};var lb="X-Playback-Duration",ru=async i=>{let e=await Qe(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(lb)?parseInt(e.headers.get(lb),10):void 0};import{assertNever as Lw,combine as $w,debounce as Cw,ErrorCategory as as,filter as Dw,filterChanged as Mw,isNonNullable as db,isNullable as ss,map as pb,merge as Ow,observableFrom as Bw,Subscription as Vw,ValueSubject as su,VideoQuality as _w}from"@vkontakte/videoplayer-shared";var au=Oe(Ta(),1);import{videoSizeToQuality as Pw,getExponentialDelay as kw}from"@vkontakte/videoplayer-shared";var ww=i=>{let e=null;if(i.QUALITY&&(e=ot(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=Pw({width:t,height:r})}return e??null},Aw=(i,e)=>{let t=i.split(`
92
- `),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),l=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!l)){if(o){let u=(0,au.default)(o[1].split(",").map(b=>b.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,d=ww(u),h;u.BANDWIDTH&&(h=parseInt(u.BANDWIDTH,10)/1e3||void 0),!h&&u["AVERAGE-BANDWIDTH"]&&(h=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[b,v]=u.RESOLUTION.split("x").map(g=>parseInt(g,10));b&&v&&(m={width:b,height:v})}let S=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:S,bandwidth:h,size:m,fps:p})}if(l){let u=(0,au.default)(l[1].split(",").map(p=>p.split("=")).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),d=u.LANGUAGE,h=u.NAME;c&&d&&a.push({type:"internal",id:d,label:h,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},Rw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),iu=0,cb=async(i,e=i,t)=>{let a=await(await Qe(i)).text();iu+=1;try{let{qualityManifests:s,textTracks:n}=Aw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(iu<=t.manifestRetryMaxCount)return await Rw(kw(iu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),cb(i,e,t)}return{qualityManifests:[],textTracks:[]}},is=cb;var Ri=class{constructor(e){this.subscription=new Vw;this.videoState=new L("stopped");this.textTracksManager=new be;this.manifests$=new su([]);this.liveOffset=new Ye;this.manifestStartTime$=new su(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):a?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");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.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else a?.to==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Lw(t)}};this.params=e,this.video=ee(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:_w.INVARIANT,url:this.params.source.url},is(K(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:as.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:as.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.maxSeekBackTime$=new su(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:as.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ie(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(re(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(me(this.video,t.playbackRate,a.playbackRateState$,r)),s(ve(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(Mw(),pb(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&db(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Y(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add($w({startTime:this.manifestStartTime$.pipe(Dw(db)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe(pb(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:h})=>({id:l,quality:u,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=Ow(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Bw(["init"])).pipe(Cw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),te(this.video)}prepare(){let e=this.selectManifest();if(ss(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:l}=t?.to??r??{};for(let[u,c]of[[o,"mq"],[l,"lq"]]){let d=String(parseFloat(u||""));c&&u&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=K(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ru(n).then(o=>{if(!ss(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(ss(l)||!isFinite(l))try{Qe(n).then(u=>u.text()).then(u=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(c){let d=new URL(c,n).toString();ru(d).then(h=>{ss(h)||this.maxSeekBackTime$.next(h)})}})}catch{}}})}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:as.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as Nw,debounce as Fw,ErrorCategory as nu,fromEvent as ou,isNonNullable as qw,isNullable as Uw,map as Hw,merge as hb,observableFrom as fb,Subscription as jw,ValueSubject as Gw,VideoQuality as Yw,isIOS as Ww}from"@vkontakte/videoplayer-shared";var Li=class{constructor(e){this.subscription=new jw;this.videoState=new L("stopped");this.textTracksManager=new be;this.manifests$=new Gw([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):a?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Nw(t)}};this.params=e,this.video=ee(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Yw.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),is(K(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:nu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:nu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ie(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(_e(this.video,t.isLooped,r)),this.subscription.add(re(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(me(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&qw(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let h=this.manifests$.getValue().find(p=>p.id===d);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Y(h.url));let p=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(p!==m){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(p),S.playbackRate=p)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Hw(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:h})=>({id:l,quality:u,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!Ww()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(hb(ou(o,"addtrack"),ou(o,"removetrack"),ou(o,"change"),fb(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=hb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,fb(["init"])).pipe(Fw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),te(this.video)}prepare(){let e=this.selectManifest();if(Uw(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,l]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));l&&o&&a.searchParams.set(l,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Qw,assertNonNullable as mb,debounce as zw,ErrorCategory as bb,isHigher as Kw,isHigherOrEqual as Jw,isInvariantQuality as gb,isLowerOrEqual as Xw,isNonNullable as Zw,merge as eA,observableFrom as tA,Subscription as rA}from"@vkontakte/videoplayer-shared";var $i=class{constructor(e){this.subscription=new rA;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new be;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:l}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return Qw(e)}};this.params=e,this.video=ee(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:bb.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ie(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(_e(this.video,t.isLooped,r)),this.subscription.add(re(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(me(this.video,t.playbackRate,a.playbackRateState$,r)),s(ve(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&Zw(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(l),c.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=eA(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,tA(["init"])).pipe(zw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),te(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;mb(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];mb(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ii(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Y(t))}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bb.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!gb(o.track.quality)&&Xw(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&Jw(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!gb(u.track.quality)&&Kw(u.track.quality,e)),l=o.length;l&&(t=o[l-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=lt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Sb,debounce as nA,merge as yb,observableFrom as oA,Subscription as uA,map as Tb,ValueSubject as lA,ErrorCategory as lu,VideoQuality as cA}from"@vkontakte/videoplayer-shared";import{ErrorCategory as iA}from"@vkontakte/videoplayer-shared";var vb=["stun:videostun.mycdn.me:80"],aA=1e3,sA=3,uu=()=>null,ns=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=uu;this.externalStopCallback=uu;this.externalErrorCallback=uu;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:vb}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:iA.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),aA)}normalizeOptions(e={}){let t={stunServerList:vb,maxRetryNumber:sA,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ci=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new lA(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return Sb(e)}};this.subscription=new uA,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ee(e.container),this.liveStreamClient=new ns(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:lu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};yb(this.videoState.stateChangeStarted$.pipe(Tb(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Tb(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ie(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(ve(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(re(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Sb(n.to)}},r)).add(yb(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,oA(["init"])).pipe(nA(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:cA.INVARIANT}),this.video.srcObject=e,T(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:lu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Di=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Oi,assertNonNullable as ft,ErrorCategory as ls,filter as EA,isNonNullable as $b,isNullable as xA,map as PA,merge as kA,once as wA,Subject as Ce,Subscription as Cb,ValueSubject as M}from"@vkontakte/videoplayer-shared";import{assertNever as us,CurrentClientDevice as hA,getCurrentBrowser as fA}from"@vkontakte/videoplayer-shared";var Ib=fA().device===hA.Android,os=document.createElement("video"),mA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',bA='video/mp4; codecs="hev1.1.6.L93.B0"',Eb='video/webm; codecs="vp09.00.10.08"',xb='video/webm; codecs="av01.0.00M.08"',gA='audio/mp4; codecs="mp4a.40.2"',vA='audio/webm; codecs="opus"',_t={mms:za(),mse:Gm(),hls:!!(os.canPlayType?.("application/x-mpegurl")||os.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Se={mp4:!!os.canPlayType?.("video/mp4"),webm:!!os.canPlayType?.("video/webm"),cmaf:!0},Fe={h264:!!Xe()?.isTypeSupported?.(mA),h265:!!Xe()?.isTypeSupported?.(bA),vp9:!!Xe()?.isTypeSupported?.(Eb),av1:!!Xe()?.isTypeSupported?.(xb),aac:!!Xe()?.isTypeSupported?.(gA),opus:!!Xe()?.isTypeSupported?.(vA)},Mi=(Fe.h264||Fe.h265)&&Fe.aac,Nt,SA=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:xb}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Eb}})]);Nt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{SA()}catch(i){console.error(i)}var br=_t.hls&&Se.mp4,Pb=()=>Object.keys(Fe).filter(i=>Fe[i]),kb=(i,e=!1,t=!1)=>{let r=_t.mse||_t.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Se.mp4&&Mi;case"DASH_WEBM":return r&&Se.webm&&Fe.vp9&&Fe.opus;case"DASH_WEBM_AV1":return r&&Se.webm&&Fe.av1&&Fe.opus;case"DASH_LIVE":return _t.mse&&Se.mp4&&Mi;case"DASH_LIVE_CMAF":return r&&Se.mp4&&Mi&&Se.cmaf;case"DASH_ONDEMAND":return r&&Se.mp4&&Mi;case"HLS":case"HLS_ONDEMAND":return br||e&&_t.mse&&Se.mp4&&Mi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return br;case"MPEG":return Se.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return _t.webrtc&&_t.ws&&Fe.h264&&(Se.mp4||Se.webm);default:return us(a)}})},ht=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Nt?Nt[t].smooth?[t,e]:Nt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Nt?Nt[t].powerEfficient?[t,e]:Nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:us(i)}return[e,t]},wb=({webmCodec:i,androidPreferredFormat:e})=>{if(Ib)switch(e){case"mpeg":return["MPEG",...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...ht(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...ht(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ht(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ht(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:us(e)}return br?[...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Ab=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o;if(Ib)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:us(i)}else br?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},cu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];import{Observable as yA,map as Rb,Subscription as TA,Subject as IA}from"@vkontakte/videoplayer-shared";var Lb=i=>new yA(e=>{let t=new TA,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Rb(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Rb(({type:u})=>u!==void 0)),n=new IA,o=0,l="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),l=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var AA={chunkDuration:5e3,maxParallelRequests:5},Bi=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new Ce;this.noAvailableProvidersError$=new Ce;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),currentVideoTrack$:new M(void 0),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),availableVideoTracks$:new M([]),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new Ce,warning$:new Ce,willSeekEvent$:new Ce,seekedEvent$:new Ce,loopedEvent$:new Ce,endedEvent$:new Ce,firstBytesEvent$:new Ce,firstFrameEvent$:new Ce,canplay$:new Ce,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1)};this.subscription=new Cb;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=kb([...Ab(this.params.tuning),...wb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>$b(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new Di(s);let n=[...cu(!0),...cu(!1)];this.chromecastFormatsIterator=new Di(n.filter(o=>$b(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(xA(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:ls.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Oi(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ft(o),new Pi({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ft(o),new ki({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return ft(o),br||!this.params.tuning.useHlsJs?new Li({...n,source:o}):new Ai({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ft(o),new Ri({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ft(o),new $i({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ft(o),new Hf({...n,source:o,config:{...AA,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ft(o),new Ci({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return Oi(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ft(o),new Nr({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Oi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Oi(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Oi(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,Db.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Cb,t=!1,r=0;return e.add(kA(this.providerOutput.error$,Lb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(PA(a=>({id:`ProviderHangup:${a}`,category:ls.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(EA(({to:s})=>s==="playing"),wA()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===ls.NETWORK,o=a.category===ls.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=r<this.params.tuning.providerErrorLimit&&!o;l&&!o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}})),e}};import{fromEvent as cs,once as RA,combine as LA,Subscription as Mb,ValueSubject as du,map as $A,filter as CA,isNonNullable as ds,now as he,safeStorage as pu}from"@vkontakte/videoplayer-shared";var DA=5e3,Ob="one_video_throughput",Bb="one_video_rtt",Vi=window.navigator.connection,Vb=()=>{let i=Vi?.downlink;if(ds(i)&&i!==10)return i*1e3},_b=()=>{let i=Vi?.rtt;if(ds(i)&&i!==3e3)return i},Nb=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},hu=class i{constructor(e){this.subscription=new Mb;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Ob)||(e.useBrowserEstimation?Vb():void 0)||DA,r=i.load(Bb)??(e.useBrowserEstimation?_b():void 0)??0;if(this.throughput$=new du(t),this.rtt$=new du(r),this.rttAdjustedThroughput$=new du(Nb(t,r,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Vb();n&&this.throughput.next(n);let o=_b();ds(o)&&this.rtt.next(o)};Vi&&"onchange"in Vi&&this.subscription.add(cs(Vi,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{pu.set(Ob,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{pu.set(Bb,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(LA({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($A(({throughput:a,rtt:s})=>Nb(a,s,e.rttPenaltyRequestSize)),CA(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=he(),a=new Mb;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(cs(e,"progress").pipe(RA()).subscribe(s=>{t=s.loaded,r=he()}));break;case 1:case 0:a.add(cs(e,"loadstart").subscribe(()=>{t=0,r=he()}));break}a.add(cs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=he(),l=n-t,u=o-r;this.addRawSpeed(l,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=he(),n=0,o=he(),l=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,he()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(he()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let p=o-s;p&&this.addRawSpeed(n,p,1,t),n=d.byteLength,s=he()}o=he()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&he()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,he()-o,this.concurrentDownloads.size),n=0,o=he());await r?.read().then(u,l)}};this.concurrentDownloads.add(e),r?.read().then(u,l)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=pu.get(e);if(ds(t))return parseInt(t,10)??void 0}},Fb=hu;import{fillWithDefault as MA,VideoQuality as qb}from"@vkontakte/videoplayer-shared";var Ub={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:qb.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:qb.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Hb=i=>({...MA(i,Ub),configName:[...i.configName??[],...Ub.configName]});import{assertNonNullable as ps,combine as hs,ErrorCategory as fs,filter as _i,filterChanged as ye,fromEvent as mu,isNonNullable as qA,isNullable as UA,Logger as HA,map as C,mapTo as Wb,merge as mt,now as ms,once as Ze,Subject as N,Subscription as Qb,tap as zb,ValueSubject as P,isHigher as jA,isInvariantQuality as Kb}from"@vkontakte/videoplayer-shared";import{merge as OA,map as BA,filter as jb,isNonNullable as VA}from"@vkontakte/videoplayer-shared";var fu=({seekState:i,position$:e})=>OA(i.stateChangeEnded$.pipe(BA(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),jb(VA)),e.pipe(jb(()=>i.getState().state==="none")));import{assertNonNullable as _A}from"@vkontakte/videoplayer-shared";var Gb=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return _A(e,`Wrong container or containerId {${i.container}}`),e};import{filter as NA,once as FA}from"@vkontakte/videoplayer-shared";var Yb=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(NA(a=>a.length>0),FA()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var bs=class{constructor(e={configName:[]}){this.subscription=new Qb;this.logger=new HA;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableQualities$:new P([]),availableQualitiesFps$:new P({}),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,firstBytes$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Lf};if(this.initLogs(),this.tuning=Hb(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Yi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Fb(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,a)=>{let s=Reflect.get(t,r,a);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let l=n.map(d=>JSON.stringify(d,(h,p)=>{let m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:fs.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=Gb(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Bi({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Qr()?mu(document,"visibilitychange").pipe(Ze()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=r&&!a&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){ps(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(_i(r=>r.length>0),Ze()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){ps(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Yb(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(UA(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return qA(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(_i(({from:e})=>e==="stopped"),Ze()).subscribe(()=>{this.initedAt=ms(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:fs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),ye()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,l)=>Kb(o)?1:Kb(l)?-1:jA(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(ye()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ye()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ye()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(C(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(hs({hasLiveOffsetByPaused:mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),ye(),C(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(hs({atLiveEdge:hs({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:fu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),ye(),zb(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(hs({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ye(),zb(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),ye()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),ye()).subscribe(this.info.volume$)).add(fu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(mt(e.providerOutput.endedEvent$.pipe(Wb(!0)),e.providerOutput.seekedEvent$.pipe(Wb(!1))).pipe(ye()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(C(n=>({id:n?`No${n}`:"NoProviders",category:fs.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Ze(),C(n=>n??ms()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ze(),C(()=>ms()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ze(),C(()=>ms()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(_i(({to:n})=>n==="playing"),Ze()).subscribe(()=>r.next(!1)));let a=0,s=mt(e.providerOutput.isBuffering$,t,r).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),ye());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(mt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(mt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":l?u?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Qb;this.subscription.add(t),this.subscription.add(e.current$.pipe(ye((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(_i(r=>r.length>0),Ze()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=lt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(mt(this.desiredState.videoTrack.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;ps(this.providerContainer),ps(e),Rf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Af(t)),this.providerContainer.current$.subscribe(({type:t})=>Hr("provider",t)),e.duration$.subscribe(t=>Hr("duration",t)),e.availableVideoTracks$.pipe(_i(t=>!!t.length),Ze()).subscribe(t=>Hr("tracks",t)),this.events.fatalError$.subscribe(new J("fatalError")),this.events.managedError$.subscribe(new J("managedError")),e.position$.subscribe(new J("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new J("quality")),this.info.currentBuffer$.subscribe(new J("buffer")),e.isBuffering$.subscribe(new J("isBuffering"))].forEach(t=>this.subscription.add(t)),Hr("codecs",Pb())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:fs.DOM,message:String(a)})})};this.subscription.add(mt(mu(document,"visibilitychange"),mu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as G1,Observable as Y1,Subject as W1,ValueSubject as Q1,VideoQuality as z1}from"@vkontakte/videoplayer-shared";var K1=`@vkontakte/videoplayer-core@${vu}`;export{ji as ChromecastState,Es as HttpConnectionType,Y1 as Observable,le as PlaybackState,bs as Player,K1 as SDK_VERSION,W1 as Subject,G1 as Subscription,xs as Surface,vu as VERSION,Q1 as ValueSubject,gt as VideoFormat,z1 as VideoQuality};
91
+ `;var rs=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new es(this.params.fov,this.params.orientation),this.cameraRotationManager=new ts(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(ib,this.gl.VERTEX_SHADER),r=this.createShader(ab,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,l=t-a,u=e+r,c=t+a,d=e-r,h=t+a;return[s,n,o,l,u,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Vt=class{constructor(e){this.subscription=new vw;this.videoState=new L("stopped");this.elementSize$=new lb(void 0);this.textTracksManager=new be;this.droppedFramesManager=new Ha;this.videoTracks$=new lb([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Na;this.textTracks=[];this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&T(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.pause()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return lw(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new rs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ee(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Za({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ie(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:ru.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,l)=>this.subscription.add(o.subscribe(l,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();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$:this.videoTracks$.pipe(iu(u=>u.map(({track:c})=>c)))}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(dw(hw),bw()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(_e(this.video,t.isLooped,a)),this.subscription.add(re(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(me(this.video,t.playbackRate,r.playbackRateState$,a)),s(mw(this.video),this.elementSize$),s(ge(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{if(u==="manifest_ready"){let c=[];this.audioTracks=[],this.textTracks=[];let d=this.player.getRepresentations();sb(d,"Manifest not loaded or empty");let h=Array.from(d.audio).sort((b,g)=>g.bitrate-b.bitrate),p=Array.from(d.video).sort((b,g)=>g.bitrate-b.bitrate),m=Array.from(d.text);if(!this.params.tuning.isAudioDisabled)for(let b of h){let g=_m(b);g&&this.audioTracks.push({track:g,representation:b})}for(let b of p){let g=Vm(b);if(g){c.push({track:g,representation:b});let v=!this.params.tuning.isAudioDisabled&&Nm(h,p,b);v&&this.audioRepresentations.set(b.id,v)}}this.videoTracks$.next(c);for(let b of m){let g=Fm(b);g&&this.textTracks.push({track:g,representation:b})}this.params.output.availableVideoTracks$.next(c.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));let S=this.selectVideoRepresentation();sb(S),this.player.initRepresentations(S.id,this.audioRepresentations.get(S.id)?.id,this.params.sourceHls)}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:ru.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(is(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,pw(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);let p=this.params.desiredState.autoVideoTrackSwitching.getState(),m=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let S=d.id;!this.params.output.elementVisible$.getValue()&&p&&(S=this.videoTracks$.getValue().map(g=>g.representation).sort((g,v)=>v.bitrate-g.bitrate).filter(g=>{let v=ub(g),w=ub(d);if(v&&w)return ob(v,w)&&ob(v,m)}).map(g=>g.id)[0]),this.player.switchRepresentation("video",S).catch(n);let b=this.audioRepresentations.get(d.id);b&&this.player.switchRepresentation("audio",b.id).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(nb(),iu(u=>u&&this.videoTracks$.getValue().find(({representation:{id:c}})=>c===u)?.track)).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(iu(({to:u})=>u==="ready"),nb());this.subscription.add(is(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(is(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=is(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,fw(["init"])).pipe(cw(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=this.params.desiredState.videoTrack.getState()?.id,r=this.videoTracks$.getValue().find(({track:{id:d}})=>d===t)?.track,a=this.params.output.currentVideoTrack$.getValue(),s=ct(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(s/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),l=Math.max(r&&!e?this.audioRepresentations.get(r.id)?.bitrate??0:0,a?this.audioRepresentations.get(a.id)?.bitrate??0:0),u=lt(this.videoTracks$.getValue().map(({track:d})=>d),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:l,forwardBufferHealth:o,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?u??r:r??u;return c&&this.videoTracks$.getValue().find(({track:d})=>d===c)?.representation}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ae(this.video).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ru.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),te(this.video)}};var ki=class extends Vt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as cb,interval as gw,map as Sw}from"@vkontakte/videoplayer-shared";var wi=class extends Vt{constructor(e){super(e),this.liveOffset=new Ye}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(cb({interval:gw(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let s=e.position$.getValue()+(a-1);e.position$.next(s),this.liveOffset?.resetTo(-s*1e3)}})).add(cb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Sw(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var pb=Oe(Oa(),1);import{assertNever as Ai,assertNonNullable as db,debounce as yw,ErrorCategory as as,filter as Tw,isNonNullable as Iw,isNullable as Ew,map as au,merge as xw,Observable as Pw,observableFrom as kw,Subscription as ww,videoSizeToQuality as Aw}from"@vkontakte/videoplayer-shared";var $e={};var mr=(i,e)=>new Pw(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ri=class{constructor(e){this.subscription=new ww;this.videoState=new L("initializing");this.textTracksManager=new be;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ai(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ai(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ai(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ai(e)}break;default:Ai(t)}};this.video=ee(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),te(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:as.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,pb.default)(import("hls.js").then(a=>{e||($e.Hls=a.default,$e.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){db($e.Hls,"hls.js not loaded"),this.hls=new $e.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){db($e.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:as.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ie(this.video),s=(u,c)=>this.subscription.add(u.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(_e(this.video,e.isLooped,r)),this.subscription.add(re(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(me(this.video,e.playbackRate,a.playbackRateState$,r)),s(ge(this.video),t.elementVisible$),this.subscription.add(mr(this.hls,$e.Events.ERROR).subscribe(u=>{u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:as.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${u.err?.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(mr(this.hls,$e.Events.MANIFEST_PARSED).pipe(au(({levels:u})=>u.reduce((c,d)=>{let h=d.name||d.height.toString(10),{width:p,height:m}=d,S=ot(d.attrs.QUALITY??"")??Aw({width:p,height:m});if(!S)return c;let b=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,g={id:h.toString(),quality:S,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:b};return this.trackLevels.set(h,{track:g,level:d}),c.push(g),c},[]))),t.availableVideoTracks$),s(mr(this.hls,$e.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang,S="internal";c.push({id:h,url:p,language:m,type:S})}e.internalTextTracks.startTransitionTo(c)}}),s(mr(this.hls,$e.Events.LEVEL_LOADING).pipe(au(({url:u})=>Y(u))),t.hostname$),s(mr(this.hls,$e.Events.FRAG_CHANGED),u=>{let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(at(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>Array.from(this.trackLevels.values()).find(({level:c})=>c===u)?.track,o=mr(this.hls,$e.Events.LEVEL_SWITCHED).pipe(au(({level:u})=>n(this.hls.levels[u])));o.pipe(Tw(Iw)).subscribe(t.currentVideoTrack$,r),this.subscription.add(at(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{if(Ew(u))return;let c=this.trackLevels.get(u.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let l=xw(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,kw(["init"])).pipe(yw(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ae(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:as.DOM,thrown:t}))||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0)}};var hb="X-Playback-Duration",su=async i=>{let e=await Qe(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(hb)?parseInt(e.headers.get(hb),10):void 0};import{assertNever as Mw,combine as Ow,debounce as Bw,ErrorCategory as ns,filter as Vw,filterChanged as _w,isNonNullable as mb,isNullable as os,map as bb,merge as Nw,observableFrom as Fw,Subscription as qw,ValueSubject as uu,VideoQuality as Uw}from"@vkontakte/videoplayer-shared";var ou=Oe(Ea(),1);import{videoSizeToQuality as Rw,getExponentialDelay as Lw}from"@vkontakte/videoplayer-shared";var $w=i=>{let e=null;if(i.QUALITY&&(e=ot(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=Rw({width:t,height:r})}return e??null},Cw=(i,e)=>{let t=i.split(`
92
+ `),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),l=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!l)){if(o){let u=(0,ou.default)(o[1].split(",").map(b=>b.split("="))),c=u.QUALITY??`stream-${u.BANDWIDTH}`,d=$w(u),h;u.BANDWIDTH&&(h=parseInt(u.BANDWIDTH,10)/1e3||void 0),!h&&u["AVERAGE-BANDWIDTH"]&&(h=parseInt(u["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let p=u["FRAME-RATE"]?parseFloat(u["FRAME-RATE"]):void 0,m;if(u.RESOLUTION){let[b,g]=u.RESOLUTION.split("x").map(v=>parseInt(v,10));b&&g&&(m={width:b,height:g})}let S=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:S,bandwidth:h,size:m,fps:p})}if(l){let u=(0,ou.default)(l[1].split(",").map(p=>p.split("=")).map(([p,m])=>[p,m.replace(/^"|"$/g,"")])),c=u.URI?.replace(/playlist$/,"subtitles.vtt"),d=u.LANGUAGE,h=u.NAME;c&&d&&a.push({type:"internal",id:d,label:h,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},Dw=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),nu=0,fb=async(i,e=i,t)=>{let a=await(await Qe(i)).text();nu+=1;try{let{qualityManifests:s,textTracks:n}=Cw(a,e);return{qualityManifests:s,textTracks:n}}catch{if(nu<=t.manifestRetryMaxCount)return await Dw(Lw(nu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),fb(i,e,t)}return{qualityManifests:[],textTracks:[]}},ss=fb;var Li=class{constructor(e){this.subscription=new qw;this.videoState=new L("stopped");this.textTracksManager=new be;this.manifests$=new uu([]);this.liveOffset=new Ye;this.manifestStartTime$=new uu(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):a?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");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.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else a?.to==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Mw(t)}};this.params=e,this.video=ee(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Uw.INVARIANT,url:this.params.source.url},ss(K(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ns.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:ns.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.maxSeekBackTime$=new uu(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:ns.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ie(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(re(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(me(this.video,t.playbackRate,a.playbackRateState$,r)),s(ge(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(_w(),bb(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&mb(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Y(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(Ow({startTime:this.manifestStartTime$.pipe(Vw(mb)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe(bb(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:h})=>({id:l,quality:u,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=Nw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Fw(["init"])).pipe(Bw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),te(this.video)}prepare(){let e=this.selectManifest();if(os(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:l}=t?.to??r??{};for(let[u,c]of[[o,"mq"],[l,"lq"]]){let d=String(parseFloat(u||""));c&&u&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=K(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),su(n).then(o=>{if(!os(o))this.maxSeekBackTime$.next(o);else{let l=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(os(l)||!isFinite(l))try{Qe(n).then(u=>u.text()).then(u=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(u)?.[1];if(c){let d=new URL(c,n).toString();su(d).then(h=>{os(h)||this.maxSeekBackTime$.next(h)})}})}catch{}}})}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ns.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as Hw,debounce as jw,ErrorCategory as lu,fromEvent as cu,isNonNullable as Gw,isNullable as Yw,map as Ww,merge as vb,observableFrom as gb,Subscription as Qw,ValueSubject as zw,VideoQuality as Kw,isIOS as Jw}from"@vkontakte/videoplayer-shared";var $i=class{constructor(e){this.subscription=new Qw;this.videoState=new L("stopped");this.textTracksManager=new be;this.manifests$=new zw([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let u=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):a?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Hw(t)}};this.params=e,this.video=ee(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Kw.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ss(K(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:lu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(l=>l.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:lu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ie(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(_e(this.video,t.isLooped,r)),this.subscription.add(re(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(me(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&Gw(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let h=this.manifests$.getValue().find(p=>p.id===d);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Y(h.url));let p=this.params.desiredState.playbackRate.getState(),m=this.params.output.element$.getValue()?.playbackRate;if(p!==m){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(p),S.playbackRate=p)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Ww(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:h})=>({id:l,quality:u,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!Jw()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(vb(cu(o,"addtrack"),cu(o,"removetrack"),cu(o,"change"),gb(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=vb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,gb(["init"])).pipe(jw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),te(this.video)}prepare(){let e=this.selectManifest();if(Yw(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,l]of[[s,"mq"],[n,"lq"]]){let u=String(parseFloat(o||""));l&&o&&a.searchParams.set(l,u)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Xw,assertNonNullable as Sb,debounce as Zw,ErrorCategory as yb,isHigher as eA,isHigherOrEqual as tA,isInvariantQuality as Tb,isLowerOrEqual as rA,isNonNullable as iA,merge as aA,observableFrom as sA,Subscription as nA}from"@vkontakte/videoplayer-shared";var Ci=class{constructor(e){this.subscription=new nA;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new be;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:l}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return Xw(e)}};this.params=e,this.video=ee(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:yb.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ie(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(_e(this.video,t.isLooped,r)),this.subscription.add(re(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(me(this.video,t.playbackRate,a.playbackRateState$,r)),s(ge(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&iA(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),u=this.params.output.element$.getValue()?.playbackRate;if(l!==u){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(l),c.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=aA(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,sA(["init"])).pipe(Zw(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),te(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Sb(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Sb(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Y(t))}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:yb.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!Tb(o.track.quality)&&rA(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&tA(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(u=>!Tb(u.track.quality)&&eA(u.track.quality,e)),l=o.length;l&&(t=o[l-1].track)}t&&(r=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=lt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Eb,debounce as cA,merge as xb,observableFrom as dA,Subscription as pA,map as Pb,ValueSubject as hA,ErrorCategory as pu,VideoQuality as fA}from"@vkontakte/videoplayer-shared";import{ErrorCategory as oA}from"@vkontakte/videoplayer-shared";var Ib=["stun:videostun.mycdn.me:80"],uA=1e3,lA=3,du=()=>null,us=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=du;this.externalStopCallback=du;this.externalErrorCallback=du;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Ib}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:oA.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),uA)}normalizeOptions(e={}){let t={stunServerList:Ib,maxRetryNumber:lA,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Di=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new hA(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):r?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return Eb(e)}};this.subscription=new pA,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ee(e.container),this.liveStreamClient=new us(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:pu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};xb(this.videoState.stateChangeStarted$.pipe(Pb(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Pb(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ie(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(ge(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(re(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Eb(n.to)}},r)).add(xb(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,dA(["init"])).pipe(cA(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Y(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:fA.INVARIANT}),this.video.srcObject=e,T(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:pu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ae(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Mi=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Vi,assertNonNullable as ft,ErrorCategory as ps,filter as RA,isNonNullable as Ob,isNullable as LA,map as $A,merge as CA,once as DA,Subject as Ce,Subscription as Bb,ValueSubject as M}from"@vkontakte/videoplayer-shared";import{assertNever as cs,CurrentClientDevice as vA,getCurrentBrowser as gA}from"@vkontakte/videoplayer-shared";var kb=gA().device===vA.Android,ls=document.createElement("video"),SA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',yA='video/mp4; codecs="hev1.1.6.L93.B0"',wb='video/webm; codecs="vp09.00.10.08"',Ab='video/webm; codecs="av01.0.00M.08"',TA='audio/mp4; codecs="mp4a.40.2"',IA='audio/webm; codecs="opus"',_t={mms:Ja(),mse:zm(),hls:!!(ls.canPlayType?.("application/x-mpegurl")||ls.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Se={mp4:!!ls.canPlayType?.("video/mp4"),webm:!!ls.canPlayType?.("video/webm"),cmaf:!0},Fe={h264:!!Xe()?.isTypeSupported?.(SA),h265:!!Xe()?.isTypeSupported?.(yA),vp9:!!Xe()?.isTypeSupported?.(wb),av1:!!Xe()?.isTypeSupported?.(Ab),aac:!!Xe()?.isTypeSupported?.(TA),opus:!!Xe()?.isTypeSupported?.(IA)},Oi=(Fe.h264||Fe.h265)&&Fe.aac,Nt,EA=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Ab}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:wb}})]);Nt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{EA()}catch(i){console.error(i)}var br=_t.hls&&Se.mp4,Rb=()=>Object.keys(Fe).filter(i=>Fe[i]),Lb=(i,e=!1,t=!1)=>{let r=_t.mse||_t.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Se.mp4&&Oi;case"DASH_WEBM":return r&&Se.webm&&Fe.vp9&&Fe.opus;case"DASH_WEBM_AV1":return r&&Se.webm&&Fe.av1&&Fe.opus;case"DASH_LIVE":return _t.mse&&Se.mp4&&Oi;case"DASH_LIVE_CMAF":return r&&Se.mp4&&Oi&&Se.cmaf;case"DASH_ONDEMAND":return r&&Se.mp4&&Oi;case"HLS":case"HLS_ONDEMAND":return br||e&&_t.mse&&Se.mp4&&Oi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return br;case"MPEG":return Se.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return _t.webrtc&&_t.ws&&Fe.h264&&(Se.mp4||Se.webm);default:return cs(a)}})},ht=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Nt?Nt[t].smooth?[t,e]:Nt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Nt?Nt[t].powerEfficient?[t,e]:Nt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:cs(i)}return[e,t]},$b=({webmCodec:i,androidPreferredFormat:e})=>{if(kb)switch(e){case"mpeg":return["MPEG",...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...ht(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...ht(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ht(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ht(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:cs(e)}return br?[...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...ht(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Cb=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o;if(kb)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:cs(i)}else br?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},hu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];import{Observable as xA,map as Db,Subscription as PA,Subject as kA}from"@vkontakte/videoplayer-shared";var Mb=i=>new xA(e=>{let t=new PA,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Db(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Db(({type:u})=>u!==void 0)),n=new kA,o=0,l="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),l=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var vr=null,ds=null;function fu(){return vr||(vr=new(window.AudioContext||window.webkitAudioContext)),ds||(ds=new GainNode(vr,{gain:1}),ds.connect(vr.destination)),vr.resume().catch(),{audioCtx:vr,gainNode:ds}}import{getCurrentBrowser as wA,CurrentClientBrowser as AA}from"@vkontakte/videoplayer-shared";var Bi=class{constructor(e,t,r){this.video$=e;this.volumeMultiplier=t;!r||!this.isSupported()||t===1||this.video$.subscribe(a=>this.listener(a))}isSupported(){let{browser:e}=wA();return e!==AA.Safari&&"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}listener(e){if(!e)return;let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=fu();a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch{}}destroy(){let{gainNode:e}=fu();e.gain.value=1}};var MA={chunkDuration:5e3,maxParallelRequests:5},_i=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new Ce;this.noAvailableProvidersError$=new Ce;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),currentVideoTrack$:new M(void 0),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),availableVideoTracks$:new M([]),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new Ce,warning$:new Ce,willSeekEvent$:new Ce,seekedEvent$:new Ce,loopedEvent$:new Ce,endedEvent$:new Ce,firstBytesEvent$:new Ce,firstFrameEvent$:new Ce,canplay$:new Ce,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1)};this.subscription=new Bb;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Lb([...Cb(this.params.tuning),...$b(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>Ob(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new Mi(s);let n=[...hu(!0),...hu(!1)];this.chromecastFormatsIterator=new Mi(n.filter(o=>Ob(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Bi(this.providerOutput.element$,this.params.volumeMultiplier??1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(LA(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:ps.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Vi(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ft(o),new ki({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ft(o),new wi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return ft(o),br||!this.params.tuning.useHlsJs?new $i({...n,source:o}):new Ri({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return ft(o),new Li({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return ft(o),new Ci({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return ft(o),new Wf({...n,source:o,config:{...MA,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return ft(o),new Di({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return Vi(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ft(o),new Fr({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Vi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Vi(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Vi(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,Vb.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Bb,t=!1,r=0;return e.add(CA(this.providerOutput.error$,Mb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($A(a=>({id:`ProviderHangup:${a}`,category:ps.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(RA(({to:s})=>s==="playing"),DA()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===ps.NETWORK,o=a.category===ps.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=r<this.params.tuning.providerErrorLimit&&!o;l&&!o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(r++,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}})),e}};import{fromEvent as hs,once as OA,combine as BA,Subscription as _b,ValueSubject as mu,map as VA,filter as _A,isNonNullable as fs,now as he,safeStorage as bu}from"@vkontakte/videoplayer-shared";var NA=5e3,Nb="one_video_throughput",Fb="one_video_rtt",Ni=window.navigator.connection,qb=()=>{let i=Ni?.downlink;if(fs(i)&&i!==10)return i*1e3},Ub=()=>{let i=Ni?.rtt;if(fs(i)&&i!==3e3)return i},Hb=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},vu=class i{constructor(e){this.subscription=new _b;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Nb)||(e.useBrowserEstimation?qb():void 0)||NA,r=i.load(Fb)??(e.useBrowserEstimation?Ub():void 0)??0;if(this.throughput$=new mu(t),this.rtt$=new mu(r),this.rttAdjustedThroughput$=new mu(Hb(t,r,e.rttPenaltyRequestSize)),this.throughput=Mt.getSmoothedValue(t,-1,e),this.rtt=Mt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=qb();n&&this.throughput.next(n);let o=Ub();fs(o)&&this.rtt.next(o)};Ni&&"onchange"in Ni&&this.subscription.add(hs(Ni,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{bu.set(Nb,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{bu.set(Fb,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(BA({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(VA(({throughput:a,rtt:s})=>Hb(a,s,e.rttPenaltyRequestSize)),_A(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=he(),a=new _b;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(hs(e,"progress").pipe(OA()).subscribe(s=>{t=s.loaded,r=he()}));break;case 1:case 0:a.add(hs(e,"loadstart").subscribe(()=>{t=0,r=he()}));break}a.add(hs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=he(),l=n-t,u=o-r;this.addRawSpeed(l,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=he(),n=0,o=he(),l=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,he()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(he()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let p=o-s;p&&this.addRawSpeed(n,p,1,t),n=d.byteLength,s=he()}o=he()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&he()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,he()-o,this.concurrentDownloads.size),n=0,o=he());await r?.read().then(u,l)}};this.concurrentDownloads.add(e),r?.read().then(u,l)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=bu.get(e);if(fs(t))return parseInt(t,10)??void 0}},jb=vu;import{fillWithDefault as FA,VideoQuality as Gb}from"@vkontakte/videoplayer-shared";var Yb={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Gb.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Gb.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Wb=i=>({...FA(i,Yb),configName:[...i.configName??[],...Yb.configName]});import{assertNonNullable as ms,combine as bs,ErrorCategory as vs,filter as Fi,filterChanged as ye,fromEvent as Su,isNonNullable as WA,isNullable as QA,Logger as zA,map as C,mapTo as Jb,merge as mt,now as gs,once as Ze,Subject as N,Subscription as Xb,tap as Zb,ValueSubject as P,isHigher as KA,isInvariantQuality as ev}from"@vkontakte/videoplayer-shared";import{merge as qA,map as UA,filter as Qb,isNonNullable as HA}from"@vkontakte/videoplayer-shared";var gu=({seekState:i,position$:e})=>qA(i.stateChangeEnded$.pipe(UA(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Qb(HA)),e.pipe(Qb(()=>i.getState().state==="none")));import{assertNonNullable as jA}from"@vkontakte/videoplayer-shared";var zb=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return jA(e,`Wrong container or containerId {${i.container}}`),e};import{filter as GA,once as YA}from"@vkontakte/videoplayer-shared";var Kb=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(GA(a=>a.length>0),YA()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var Ss=class{constructor(e={configName:[]}){this.subscription=new Xb;this.logger=new zA;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableQualities$:new P([]),availableQualitiesFps$:new P({}),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new N,ready$:new N,started$:new N,playing$:new N,paused$:new N,stopped$:new N,willStart$:new N,willResume$:new N,willPause$:new N,willStop$:new N,willDestruct$:new N,watchCoverageRecord$:new N,watchCoverageLive$:new N,managedError$:new N,fatalError$:new N,ended$:new N,looped$:new N,seeked$:new N,willSeek$:new N,firstBytes$:new N,firstFrame$:new N,canplay$:new N,log$:new N};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Mf};if(this.initLogs(),this.tuning=Wb(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Qi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new jb(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,a)=>{let s=Reflect.get(t,r,a);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let l=n.map(d=>JSON.stringify(d,(h,p)=>{let m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:vs.WTF,message:c,thrown:o}),o}}}})}initVideo(e){return this.config=e,this.domContainer=zb(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new _i({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!zr()?Su(document,"visibilitychange").pipe(Ze()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=r&&!a&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){ms(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Fi(r=>r.length>0),Ze()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){ms(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Kb(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(QA(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return WA(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(C(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Fi(({from:e})=>e==="stopped"),Ze()).subscribe(()=>{this.initedAt=gs(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:vs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(C(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(C(n=>n.destination),ye()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(C(n=>n.map(({quality:o})=>o).sort((o,l)=>ev(o)?1:ev(l)?-1:KA(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(ye()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ye()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ye()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(C(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(bs({hasLiveOffsetByPaused:mt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(C(n=>n.to),ye(),C(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(bs({atLiveEdge:bs({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:gu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(C(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),ye(),Zb(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(C(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(bs({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(C(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ye(),Zb(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(C(n=>n.muted),ye()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(C(n=>n.volume),ye()).subscribe(this.info.volume$)).add(gu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(mt(e.providerOutput.endedEvent$.pipe(Jb(!0)),e.providerOutput.seekedEvent$.pipe(Jb(!1))).pipe(ye()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(C(n=>({id:n?`No${n}`:"NoProviders",category:vs.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Ze(),C(n=>n??gs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ze(),C(()=>gs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ze(),C(()=>gs()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Fi(({to:n})=>n==="playing"),Ze()).subscribe(()=>r.next(!1)));let a=0,s=mt(e.providerOutput.isBuffering$,t,r).pipe(C(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),ye());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(mt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(mt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":l?u?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(C(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Xb;this.subscription.add(t),this.subscription.add(e.current$.pipe(ye((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Fi(r=>r.length>0),Ze()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t,r=this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=lt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(mt(this.desiredState.videoTrack.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(C(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(C(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(C(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;ms(this.providerContainer),ms(e),Df(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>Cf(t)),this.providerContainer.current$.subscribe(({type:t})=>jr("provider",t)),e.duration$.subscribe(t=>jr("duration",t)),e.availableVideoTracks$.pipe(Fi(t=>!!t.length),Ze()).subscribe(t=>jr("tracks",t)),this.events.fatalError$.subscribe(new J("fatalError")),this.events.managedError$.subscribe(new J("managedError")),e.position$.subscribe(new J("position")),e.currentVideoTrack$.pipe(C(t=>t?.quality)).subscribe(new J("quality")),this.info.currentBuffer$.subscribe(new J("buffer")),e.isBuffering$.subscribe(new J("isBuffering"))].forEach(t=>this.subscription.add(t)),jr("codecs",Rb())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:vs.DOM,message:String(a)})})};this.subscription.add(mt(Su(document,"visibilitychange"),Su(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as aH,Observable as sH,Subject as nH,ValueSubject as oH,VideoQuality as uH}from"@vkontakte/videoplayer-shared";var lH=`@vkontakte/videoplayer-core@${Iu}`;export{Yi as ChromecastState,ks as HttpConnectionType,sH as Observable,le as PlaybackState,Ss as Player,lH as SDK_VERSION,nH as Subject,aH as Subscription,ws as Surface,Iu as VERSION,oH as ValueSubject,vt as VideoFormat,uH as VideoQuality};