@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/es2018.esm.js CHANGED
@@ -1,15 +1,15 @@
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 ov=Object.create;var tl=Object.defineProperty;var uv=Object.getOwnPropertyDescriptor;var lv=Object.getOwnPropertyNames;var cv=Object.getPrototypeOf,dv=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var pv=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of lv(e))!dv.call(i,a)&&a!==t&&tl(i,a,{get:()=>e[a],enumerable:!(r=uv(e,a))||r.enumerable});return i};var Oe=(i,e,t)=>(t=i!=null?ov(cv(i)):{},pv(e||!i||!i.__esModule?tl(t,"default",{value:i,enumerable:!0}):t,i));var de=m((dL,ll)=>{"use strict";ll.exports=function(i){try{return!!i()}catch(e){return!0}}});var Lr=m((pL,cl)=>{"use strict";var yv=de();cl.exports=!yv(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var re=m((hL,hl)=>{"use strict";var dl=Lr(),pl=Function.prototype,Qs=pl.call,Tv=dl&&pl.bind.bind(Qs,Qs);hl.exports=dl?Tv:function(i){return function(){return Qs.apply(i,arguments)}}});var Jt=m((fL,ml)=>{"use strict";var fl=re(),Iv=fl({}.toString),Ev=fl("".slice);ml.exports=function(i){return Ev(Iv(i),8,-1)}});var gl=m((mL,bl)=>{"use strict";var xv=re(),Pv=de(),kv=Jt(),zs=Object,wv=xv("".split);bl.exports=Pv(function(){return!zs("z").propertyIsEnumerable(0)})?function(i){return kv(i)=="String"?wv(i,""):zs(i)}:zs});var Xt=m((bL,vl)=>{"use strict";vl.exports=function(i){return i==null}});var sa=m((gL,Sl)=>{"use strict";var Av=Xt(),Rv=TypeError;Sl.exports=function(i){if(Av(i))throw Rv("Can't call method on "+i);return i}});var Zt=m((vL,yl)=>{"use strict";var Lv=gl(),$v=sa();yl.exports=function(i){return Lv($v(i))}});var Ks=m((SL,Tl)=>{"use strict";Tl.exports=function(){}});var xt=m((yL,Il)=>{"use strict";Il.exports={}});var W=m((El,xl)=>{"use strict";var na=function(i){return i&&i.Math==Math&&i};xl.exports=na(typeof globalThis=="object"&&globalThis)||na(typeof window=="object"&&window)||na(typeof self=="object"&&self)||na(typeof global=="object"&&global)||function(){return this}()||El||Function("return this")()});var Xs=m((TL,Pl)=>{"use strict";var Js=typeof document=="object"&&document.all,Cv=typeof Js=="undefined"&&Js!==void 0;Pl.exports={all:Js,IS_HTMLDDA:Cv}});var q=m((IL,wl)=>{"use strict";var kl=Xs(),Dv=kl.all;wl.exports=kl.IS_HTMLDDA?function(i){return typeof i=="function"||i===Dv}:function(i){return typeof i=="function"}});var Ll=m((EL,Rl)=>{"use strict";var Mv=W(),Ov=q(),Al=Mv.WeakMap;Rl.exports=Ov(Al)&&/native code/.test(String(Al))});var Be=m((xL,Dl)=>{"use strict";var $l=q(),Cl=Xs(),Bv=Cl.all;Dl.exports=Cl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:$l(i)||i===Bv}:function(i){return typeof i=="object"?i!==null:$l(i)}});var Ve=m((PL,Ml)=>{"use strict";var Vv=de();Ml.exports=!Vv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var oa=m((kL,Bl)=>{"use strict";var _v=W(),Ol=Be(),Zs=_v.document,Nv=Ol(Zs)&&Ol(Zs.createElement);Bl.exports=function(i){return Nv?Zs.createElement(i):{}}});var en=m((wL,Vl)=>{"use strict";var Fv=Ve(),qv=de(),Uv=oa();Vl.exports=!Fv&&!qv(function(){return Object.defineProperty(Uv("div"),"a",{get:function(){return 7}}).a!=7})});var tn=m((AL,_l)=>{"use strict";var Hv=Ve(),jv=de();_l.exports=Hv&&jv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var ke=m((RL,Nl)=>{"use strict";var Gv=Be(),Yv=String,Wv=TypeError;Nl.exports=function(i){if(Gv(i))return i;throw Wv(Yv(i)+" is not an object")}});var ie=m((LL,Fl)=>{"use strict";var Qv=Lr(),ua=Function.prototype.call;Fl.exports=Qv?ua.bind(ua):function(){return ua.apply(ua,arguments)}});var la=m(($L,ql)=>{"use strict";ql.exports={}});var Ue=m((CL,Hl)=>{"use strict";var rn=la(),an=W(),zv=q(),Ul=function(i){return zv(i)?i:void 0};Hl.exports=function(i,e){return arguments.length<2?Ul(rn[i])||Ul(an[i]):rn[i]&&rn[i][e]||an[i]&&an[i][e]}});var $r=m((DL,jl)=>{"use strict";var Kv=re();jl.exports=Kv({}.isPrototypeOf)});var Cr=m((ML,Gl)=>{"use strict";Gl.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var nn=m((OL,Jl)=>{"use strict";var Kl=W(),sn=Cr(),Yl=Kl.process,Wl=Kl.Deno,Ql=Yl&&Yl.versions||Wl&&Wl.version,zl=Ql&&Ql.v8,we,ca;zl&&(we=zl.split("."),ca=we[0]>0&&we[0]<4?1:+(we[0]+we[1]));!ca&&sn&&(we=sn.match(/Edge\/(\d+)/),(!we||we[1]>=74)&&(we=sn.match(/Chrome\/(\d+)/),we&&(ca=+we[1])));Jl.exports=ca});var on=m((BL,Zl)=>{"use strict";var Xl=nn(),Jv=de(),Xv=W(),Zv=Xv.String;Zl.exports=!!Object.getOwnPropertySymbols&&!Jv(function(){var i=Symbol();return!Zv(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Xl&&Xl<41})});var un=m((VL,ec)=>{"use strict";var eS=on();ec.exports=eS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ln=m((_L,tc)=>{"use strict";var tS=Ue(),rS=q(),iS=$r(),aS=un(),sS=Object;tc.exports=aS?function(i){return typeof i=="symbol"}:function(i){var e=tS("Symbol");return rS(e)&&iS(e.prototype,sS(i))}});var Dr=m((NL,rc)=>{"use strict";var nS=String;rc.exports=function(i){try{return nS(i)}catch(e){return"Object"}}});var He=m((FL,ic)=>{"use strict";var oS=q(),uS=Dr(),lS=TypeError;ic.exports=function(i){if(oS(i))return i;throw lS(uS(i)+" is not a function")}});var Mr=m((qL,ac)=>{"use strict";var cS=He(),dS=Xt();ac.exports=function(i,e){var t=i[e];return dS(t)?void 0:cS(t)}});var nc=m((UL,sc)=>{"use strict";var cn=ie(),dn=q(),pn=Be(),pS=TypeError;sc.exports=function(i,e){var t,r;if(e==="string"&&dn(t=i.toString)&&!pn(r=cn(t,i))||dn(t=i.valueOf)&&!pn(r=cn(t,i))||e!=="string"&&dn(t=i.toString)&&!pn(r=cn(t,i)))return r;throw pS("Can't convert object to primitive value")}});var Ae=m((HL,oc)=>{"use strict";oc.exports=!0});var cc=m((jL,lc)=>{"use strict";var uc=W(),hS=Object.defineProperty;lc.exports=function(i,e){try{hS(uc,i,{value:e,configurable:!0,writable:!0})}catch(t){uc[i]=e}return e}});var da=m((GL,pc)=>{"use strict";var fS=W(),mS=cc(),dc="__core-js_shared__",bS=fS[dc]||mS(dc,{});pc.exports=bS});var hn=m((YL,fc)=>{"use strict";var gS=Ae(),hc=da();(fc.exports=function(i,e){return hc[i]||(hc[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:gS?"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 Or=m((WL,mc)=>{"use strict";var vS=sa(),SS=Object;mc.exports=function(i){return SS(vS(i))}});var Re=m((QL,bc)=>{"use strict";var yS=re(),TS=Or(),IS=yS({}.hasOwnProperty);bc.exports=Object.hasOwn||function(e,t){return IS(TS(e),t)}});var fn=m((zL,gc)=>{"use strict";var ES=re(),xS=0,PS=Math.random(),kS=ES(1 .toString);gc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+kS(++xS+PS,36)}});var K=m((KL,Sc)=>{"use strict";var wS=W(),AS=hn(),vc=Re(),RS=fn(),LS=on(),$S=un(),er=wS.Symbol,mn=AS("wks"),CS=$S?er.for||er:er&&er.withoutSetter||RS;Sc.exports=function(i){return vc(mn,i)||(mn[i]=LS&&vc(er,i)?er[i]:CS("Symbol."+i)),mn[i]}});var Ec=m((JL,Ic)=>{"use strict";var DS=ie(),yc=Be(),Tc=ln(),MS=Mr(),OS=nc(),BS=K(),VS=TypeError,_S=BS("toPrimitive");Ic.exports=function(i,e){if(!yc(i)||Tc(i))return i;var t=MS(i,_S),r;if(t){if(e===void 0&&(e="default"),r=DS(t,i,e),!yc(r)||Tc(r))return r;throw VS("Can't convert object to primitive value")}return e===void 0&&(e="number"),OS(i,e)}});var pa=m((XL,xc)=>{"use strict";var NS=Ec(),FS=ln();xc.exports=function(i){var e=NS(i,"string");return FS(e)?e:e+""}});var Pt=m(kc=>{"use strict";var qS=Ve(),US=en(),HS=tn(),ha=ke(),Pc=pa(),jS=TypeError,bn=Object.defineProperty,GS=Object.getOwnPropertyDescriptor,gn="enumerable",vn="configurable",Sn="writable";kc.f=qS?HS?function(e,t,r){if(ha(e),t=Pc(t),ha(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Sn in r&&!r[Sn]){var a=GS(e,t);a&&a[Sn]&&(e[t]=r.value,r={configurable:vn in r?r[vn]:a[vn],enumerable:gn in r?r[gn]:a[gn],writable:!1})}return bn(e,t,r)}:bn:function(e,t,r){if(ha(e),t=Pc(t),ha(r),US)try{return bn(e,t,r)}catch(a){}if("get"in r||"set"in r)throw jS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Br=m((e$,wc)=>{"use strict";wc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var kt=m((t$,Ac)=>{"use strict";var YS=Ve(),WS=Pt(),QS=Br();Ac.exports=YS?function(i,e,t){return WS.f(i,e,QS(1,t))}:function(i,e,t){return i[e]=t,i}});var fa=m((r$,Lc)=>{"use strict";var zS=hn(),KS=fn(),Rc=zS("keys");Lc.exports=function(i){return Rc[i]||(Rc[i]=KS(i))}});var ma=m((i$,$c)=>{"use strict";$c.exports={}});var En=m((a$,Mc)=>{"use strict";var JS=Ll(),Dc=W(),XS=Be(),ZS=kt(),yn=Re(),Tn=da(),ey=fa(),ty=ma(),Cc="Object already initialized",In=Dc.TypeError,ry=Dc.WeakMap,ba,Vr,ga,iy=function(i){return ga(i)?Vr(i):ba(i,{})},ay=function(i){return function(e){var t;if(!XS(e)||(t=Vr(e)).type!==i)throw In("Incompatible receiver, "+i+" required");return t}};JS||Tn.state?(Le=Tn.state||(Tn.state=new ry),Le.get=Le.get,Le.has=Le.has,Le.set=Le.set,ba=function(i,e){if(Le.has(i))throw In(Cc);return e.facade=i,Le.set(i,e),e},Vr=function(i){return Le.get(i)||{}},ga=function(i){return Le.has(i)}):(wt=ey("state"),ty[wt]=!0,ba=function(i,e){if(yn(i,wt))throw In(Cc);return e.facade=i,ZS(i,wt,e),e},Vr=function(i){return yn(i,wt)?i[wt]:{}},ga=function(i){return yn(i,wt)});var Le,wt;Mc.exports={set:ba,get:Vr,has:ga,enforce:iy,getterFor:ay}});var xn=m((s$,_c)=>{"use strict";var sy=Lr(),Vc=Function.prototype,Oc=Vc.apply,Bc=Vc.call;_c.exports=typeof Reflect=="object"&&Reflect.apply||(sy?Bc.bind(Oc):function(){return Bc.apply(Oc,arguments)})});var Pn=m((n$,Nc)=>{"use strict";var ny=Jt(),oy=re();Nc.exports=function(i){if(ny(i)==="Function")return oy(i)}});var Hc=m(Uc=>{"use strict";var Fc={}.propertyIsEnumerable,qc=Object.getOwnPropertyDescriptor,uy=qc&&!Fc.call({1:2},1);Uc.f=uy?function(e){var t=qc(this,e);return!!t&&t.enumerable}:Fc});var kn=m(Gc=>{"use strict";var ly=Ve(),cy=ie(),dy=Hc(),py=Br(),hy=Zt(),fy=pa(),my=Re(),by=en(),jc=Object.getOwnPropertyDescriptor;Gc.f=ly?jc:function(e,t){if(e=hy(e),t=fy(t),by)try{return jc(e,t)}catch(r){}if(my(e,t))return py(!cy(dy.f,e,t),e[t])}});var wn=m((l$,Yc)=>{"use strict";var gy=de(),vy=q(),Sy=/#|\.prototype\./,_r=function(i,e){var t=Ty[yy(i)];return t==Ey?!0:t==Iy?!1:vy(e)?gy(e):!!e},yy=_r.normalize=function(i){return String(i).replace(Sy,".").toLowerCase()},Ty=_r.data={},Iy=_r.NATIVE="N",Ey=_r.POLYFILL="P";Yc.exports=_r});var Nr=m((c$,Qc)=>{"use strict";var Wc=Pn(),xy=He(),Py=Lr(),ky=Wc(Wc.bind);Qc.exports=function(i,e){return xy(i),e===void 0?i:Py?ky(i,e):function(){return i.apply(e,arguments)}}});var ge=m((d$,Kc)=>{"use strict";var va=W(),wy=xn(),Ay=Pn(),Ry=q(),Ly=kn().f,$y=wn(),tr=la(),Cy=Nr(),rr=kt(),zc=Re(),Dy=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 wy(i,this,arguments)};return e.prototype=i.prototype,e};Kc.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?va:a?va[t]:(va[t]||{}).prototype,o=r?tr:tr[t]||rr(tr,t,{})[t],l=o.prototype,u,c,d,p,f,h,b,v,S;for(p in e)u=$y(r?p:t+(a?".":"#")+p,i.forced),c=!u&&n&&zc(n,p),h=o[p],c&&(i.dontCallGetSet?(S=Ly(n,p),b=S&&S.value):b=n[p]),f=c&&b?b:e[p],!(c&&typeof h==typeof f)&&(i.bind&&c?v=Cy(f,va):i.wrap&&c?v=Dy(f):s&&Ry(f)?v=Ay(f):v=f,(i.sham||f&&f.sham||h&&h.sham)&&rr(v,"sham",!0),rr(o,p,v),s&&(d=t+"Prototype",zc(tr,d)||rr(tr,d,{}),rr(tr[d],p,f),i.real&&l&&(u||!l[p])&&rr(l,p,f)))}});var Zc=m((p$,Xc)=>{"use strict";var An=Ve(),My=Re(),Jc=Function.prototype,Oy=An&&Object.getOwnPropertyDescriptor,Rn=My(Jc,"name"),By=Rn&&function(){}.name==="something",Vy=Rn&&(!An||An&&Oy(Jc,"name").configurable);Xc.exports={EXISTS:Rn,PROPER:By,CONFIGURABLE:Vy}});var td=m((h$,ed)=>{"use strict";var _y=Math.ceil,Ny=Math.floor;ed.exports=Math.trunc||function(e){var t=+e;return(t>0?Ny:_y)(t)}});var Sa=m((f$,rd)=>{"use strict";var Fy=td();rd.exports=function(i){var e=+i;return e!==e||e===0?0:Fy(e)}});var ad=m((m$,id)=>{"use strict";var qy=Sa(),Uy=Math.max,Hy=Math.min;id.exports=function(i,e){var t=qy(i);return t<0?Uy(t+e,0):Hy(t,e)}});var nd=m((b$,sd)=>{"use strict";var jy=Sa(),Gy=Math.min;sd.exports=function(i){return i>0?Gy(jy(i),9007199254740991):0}});var ya=m((g$,od)=>{"use strict";var Yy=nd();od.exports=function(i){return Yy(i.length)}});var cd=m((v$,ld)=>{"use strict";var Wy=Zt(),Qy=ad(),zy=ya(),ud=function(i){return function(e,t,r){var a=Wy(e),s=zy(a),n=Qy(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}};ld.exports={includes:ud(!0),indexOf:ud(!1)}});var hd=m((S$,pd)=>{"use strict";var Ky=re(),Ln=Re(),Jy=Zt(),Xy=cd().indexOf,Zy=ma(),dd=Ky([].push);pd.exports=function(i,e){var t=Jy(i),r=0,a=[],s;for(s in t)!Ln(Zy,s)&&Ln(t,s)&&dd(a,s);for(;e.length>r;)Ln(t,s=e[r++])&&(~Xy(a,s)||dd(a,s));return a}});var $n=m((y$,fd)=>{"use strict";fd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var bd=m((T$,md)=>{"use strict";var eT=hd(),tT=$n();md.exports=Object.keys||function(e){return eT(e,tT)}});var vd=m(gd=>{"use strict";var rT=Ve(),iT=tn(),aT=Pt(),sT=ke(),nT=Zt(),oT=bd();gd.f=rT&&!iT?Object.defineProperties:function(e,t){sT(e);for(var r=nT(t),a=oT(t),s=a.length,n=0,o;s>n;)aT.f(e,o=a[n++],r[o]);return e}});var Cn=m((E$,Sd)=>{"use strict";var uT=Ue();Sd.exports=uT("document","documentElement")});var Bn=m((x$,kd)=>{"use strict";var lT=ke(),cT=vd(),yd=$n(),dT=ma(),pT=Cn(),hT=oa(),fT=fa(),Td=">",Id="<",Mn="prototype",On="script",xd=fT("IE_PROTO"),Dn=function(){},Pd=function(i){return Id+On+Td+i+Id+"/"+On+Td},Ed=function(i){i.write(Pd("")),i.close();var e=i.parentWindow.Object;return i=null,e},mT=function(){var i=hT("iframe"),e="java"+On+":",t;return i.style.display="none",pT.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Pd("document.F=Object")),t.close(),t.F},Ta,Ia=function(){try{Ta=new ActiveXObject("htmlfile")}catch(e){}Ia=typeof document!="undefined"?document.domain&&Ta?Ed(Ta):mT():Ed(Ta);for(var i=yd.length;i--;)delete Ia[Mn][yd[i]];return Ia()};dT[xd]=!0;kd.exports=Object.create||function(e,t){var r;return e!==null?(Dn[Mn]=lT(e),r=new Dn,Dn[Mn]=null,r[xd]=e):r=Ia(),t===void 0?r:cT.f(r,t)}});var Ad=m((P$,wd)=>{"use strict";var bT=de();wd.exports=!bT(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var _n=m((k$,Ld)=>{"use strict";var gT=Re(),vT=q(),ST=Or(),yT=fa(),TT=Ad(),Rd=yT("IE_PROTO"),Vn=Object,IT=Vn.prototype;Ld.exports=TT?Vn.getPrototypeOf:function(i){var e=ST(i);if(gT(e,Rd))return e[Rd];var t=e.constructor;return vT(t)&&e instanceof t?t.prototype:e instanceof Vn?IT:null}});var ir=m((w$,$d)=>{"use strict";var ET=kt();$d.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:ET(i,e,t),i}});var Un=m((A$,Md)=>{"use strict";var xT=de(),PT=q(),kT=Be(),wT=Bn(),Cd=_n(),AT=ir(),RT=K(),LT=Ae(),qn=RT("iterator"),Dd=!1,je,Nn,Fn;[].keys&&(Fn=[].keys(),"next"in Fn?(Nn=Cd(Cd(Fn)),Nn!==Object.prototype&&(je=Nn)):Dd=!0);var $T=!kT(je)||xT(function(){var i={};return je[qn].call(i)!==i});$T?je={}:LT&&(je=wT(je));PT(je[qn])||AT(je,qn,function(){return this});Md.exports={IteratorPrototype:je,BUGGY_SAFARI_ITERATORS:Dd}});var Ea=m((R$,Bd)=>{"use strict";var CT=K(),DT=CT("toStringTag"),Od={};Od[DT]="z";Bd.exports=String(Od)==="[object z]"});var ar=m((L$,Vd)=>{"use strict";var MT=Ea(),OT=q(),xa=Jt(),BT=K(),VT=BT("toStringTag"),_T=Object,NT=xa(function(){return arguments}())=="Arguments",FT=function(i,e){try{return i[e]}catch(t){}};Vd.exports=MT?xa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=FT(e=_T(i),VT))=="string"?t:NT?xa(e):(r=xa(e))=="Object"&&OT(e.callee)?"Arguments":r}});var Nd=m(($$,_d)=>{"use strict";var qT=Ea(),UT=ar();_d.exports=qT?{}.toString:function(){return"[object "+UT(this)+"]"}});var Pa=m((C$,qd)=>{"use strict";var HT=Ea(),jT=Pt().f,GT=kt(),YT=Re(),WT=Nd(),QT=K(),Fd=QT("toStringTag");qd.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;YT(a,Fd)||jT(a,Fd,{configurable:!0,value:e}),r&&!HT&&GT(a,"toString",WT)}}});var Hd=m((D$,Ud)=>{"use strict";var zT=Un().IteratorPrototype,KT=Bn(),JT=Br(),XT=Pa(),ZT=xt(),eI=function(){return this};Ud.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=KT(zT,{next:JT(+!r,t)}),XT(i,a,!1,!0),ZT[a]=eI,i}});var Gd=m((M$,jd)=>{"use strict";var tI=re(),rI=He();jd.exports=function(i,e,t){try{return tI(rI(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var Wd=m((O$,Yd)=>{"use strict";var iI=q(),aI=String,sI=TypeError;Yd.exports=function(i){if(typeof i=="object"||iI(i))return i;throw sI("Can't set "+aI(i)+" as a prototype")}});var Hn=m((B$,Qd)=>{"use strict";var nI=Gd(),oI=ke(),uI=Wd();Qd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=nI(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return oI(a),uI(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var sp=m((V$,ap)=>{"use strict";var lI=ge(),cI=ie(),ka=Ae(),rp=Zc(),dI=q(),pI=Hd(),zd=_n(),Kd=Hn(),hI=Pa(),fI=kt(),jn=ir(),mI=K(),Jd=xt(),ip=Un(),bI=rp.PROPER,gI=rp.CONFIGURABLE,Xd=ip.IteratorPrototype,wa=ip.BUGGY_SAFARI_ITERATORS,Fr=mI("iterator"),Zd="keys",qr="values",ep="entries",tp=function(){return this};ap.exports=function(i,e,t,r,a,s,n){pI(t,e,r);var o=function(S){if(S===a&&p)return p;if(!wa&&S in c)return c[S];switch(S){case Zd:return function(){return new t(this,S)};case qr:return function(){return new t(this,S)};case ep:return function(){return new t(this,S)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[Fr]||c["@@iterator"]||a&&c[a],p=!wa&&d||o(a),f=e=="Array"&&c.entries||d,h,b,v;if(f&&(h=zd(f.call(new i)),h!==Object.prototype&&h.next&&(!ka&&zd(h)!==Xd&&(Kd?Kd(h,Xd):dI(h[Fr])||jn(h,Fr,tp)),hI(h,l,!0,!0),ka&&(Jd[l]=tp))),bI&&a==qr&&d&&d.name!==qr&&(!ka&&gI?fI(c,"name",qr):(u=!0,p=function(){return cI(d,this)})),a)if(b={values:o(qr),keys:s?p:o(Zd),entries:o(ep)},n)for(v in b)(wa||u||!(v in c))&&jn(c,v,b[v]);else lI({target:e,proto:!0,forced:wa||u},b);return(!ka||n)&&c[Fr]!==p&&jn(c,Fr,p,{name:a}),Jd[e]=p,b}});var op=m((_$,np)=>{"use strict";np.exports=function(i,e){return{value:i,done:e}}});var Yn=m((N$,pp)=>{"use strict";var vI=Zt(),Gn=Ks(),up=xt(),cp=En(),SI=Pt().f,yI=sp(),Aa=op(),TI=Ae(),II=Ve(),dp="Array Iterator",EI=cp.set,xI=cp.getterFor(dp);pp.exports=yI(Array,"Array",function(i,e){EI(this,{type:dp,target:vI(i),index:0,kind:e})},function(){var i=xI(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Aa(void 0,!0)):t=="keys"?Aa(r,!1):t=="values"?Aa(e[r],!1):Aa([r,e[r]],!1)},"values");var lp=up.Arguments=up.Array;Gn("keys");Gn("values");Gn("entries");if(!TI&&II&&lp.name!=="values")try{SI(lp,"name",{value:"values"})}catch(i){}});var fp=m((F$,hp)=>{"use strict";var PI=K(),kI=xt(),wI=PI("iterator"),AI=Array.prototype;hp.exports=function(i){return i!==void 0&&(kI.Array===i||AI[wI]===i)}});var Wn=m((q$,bp)=>{"use strict";var RI=ar(),mp=Mr(),LI=Xt(),$I=xt(),CI=K(),DI=CI("iterator");bp.exports=function(i){if(!LI(i))return mp(i,DI)||mp(i,"@@iterator")||$I[RI(i)]}});var vp=m((U$,gp)=>{"use strict";var MI=ie(),OI=He(),BI=ke(),VI=Dr(),_I=Wn(),NI=TypeError;gp.exports=function(i,e){var t=arguments.length<2?_I(i):e;if(OI(t))return BI(MI(t,i));throw NI(VI(i)+" is not iterable")}});var Tp=m((H$,yp)=>{"use strict";var FI=ie(),Sp=ke(),qI=Mr();yp.exports=function(i,e,t){var r,a;Sp(i);try{if(r=qI(i,"return"),!r){if(e==="throw")throw t;return t}r=FI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Sp(r),t}});var La=m((j$,Pp)=>{"use strict";var UI=Nr(),HI=ie(),jI=ke(),GI=Dr(),YI=fp(),WI=ya(),Ip=$r(),QI=vp(),zI=Wn(),Ep=Tp(),KI=TypeError,Ra=function(i,e){this.stopped=i,this.result=e},xp=Ra.prototype;Pp.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=UI(e,r),u,c,d,p,f,h,b,v=function(g){return u&&Ep(u,"normal",g),new Ra(!0,g)},S=function(g){return a?(jI(g),o?l(g[0],g[1],v):l(g[0],g[1])):o?l(g,v):l(g)};if(s)u=i.iterator;else if(n)u=i;else{if(c=zI(i),!c)throw KI(GI(i)+" is not iterable");if(YI(c)){for(d=0,p=WI(i);p>d;d++)if(f=S(i[d]),f&&Ip(xp,f))return f;return new Ra(!1)}u=QI(i,c)}for(h=s?i.next:u.next;!(b=HI(h,u)).done;){try{f=S(b.value)}catch(g){Ep(u,"throw",g)}if(typeof f=="object"&&f&&Ip(xp,f))return f}return new Ra(!1)}});var wp=m((G$,kp)=>{"use strict";var JI=pa(),XI=Pt(),ZI=Br();kp.exports=function(i,e,t){var r=JI(e);r in i?XI.f(i,r,ZI(0,t)):i[r]=t}});var Ap=m(()=>{"use strict";var eE=ge(),tE=La(),rE=wp();eE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return tE(e,function(r,a){rE(t,r,a)},{AS_ENTRIES:!0}),t}})});var Lp=m((Q$,Rp)=>{"use strict";Yn();Ap();var iE=la();Rp.exports=iE.Object.fromEntries});var Cp=m((z$,$p)=>{"use strict";$p.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 Op=m(()=>{"use strict";Yn();var aE=Cp(),sE=W(),nE=ar(),oE=kt(),Dp=xt(),uE=K(),Mp=uE("toStringTag");for($a in aE)Qn=sE[$a],Ca=Qn&&Qn.prototype,Ca&&nE(Ca)!==Mp&&oE(Ca,Mp,$a),Dp[$a]=Dp.Array;var Qn,Ca,$a});var Vp=m((X$,Bp)=>{"use strict";var lE=Lp();Op();Bp.exports=lE});var Da=m((Z$,_p)=>{"use strict";var cE=Vp();_p.exports=cE});var Np=m(()=>{"use strict"});var Ur=m((rC,Fp)=>{"use strict";var dE=Jt();Fp.exports=typeof process!="undefined"&&dE(process)=="process"});var Up=m((iC,qp)=>{"use strict";var pE=Pt();qp.exports=function(i,e,t){return pE.f(i,e,t)}});var Gp=m((aC,jp)=>{"use strict";var hE=Ue(),fE=Up(),mE=K(),bE=Ve(),Hp=mE("species");jp.exports=function(i){var e=hE(i);bE&&e&&!e[Hp]&&fE(e,Hp,{configurable:!0,get:function(){return this}})}});var Wp=m((sC,Yp)=>{"use strict";var gE=$r(),vE=TypeError;Yp.exports=function(i,e){if(gE(e,i))return i;throw vE("Incorrect invocation")}});var Kn=m((nC,Qp)=>{"use strict";var SE=re(),yE=q(),zn=da(),TE=SE(Function.toString);yE(zn.inspectSource)||(zn.inspectSource=function(i){return TE(i)});Qp.exports=zn.inspectSource});var eh=m((oC,Zp)=>{"use strict";var IE=re(),EE=de(),zp=q(),xE=ar(),PE=Ue(),kE=Kn(),Kp=function(){},wE=[],Jp=PE("Reflect","construct"),Jn=/^\s*(?:class|function)\b/,AE=IE(Jn.exec),RE=!Jn.exec(Kp),Hr=function(e){if(!zp(e))return!1;try{return Jp(Kp,wE,e),!0}catch(t){return!1}},Xp=function(e){if(!zp(e))return!1;switch(xE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return RE||!!AE(Jn,kE(e))}catch(t){return!0}};Xp.sham=!0;Zp.exports=!Jp||EE(function(){var i;return Hr(Hr.call)||!Hr(Object)||!Hr(function(){i=!0})||i})?Xp:Hr});var rh=m((uC,th)=>{"use strict";var LE=eh(),$E=Dr(),CE=TypeError;th.exports=function(i){if(LE(i))return i;throw CE($E(i)+" is not a constructor")}});var Xn=m((lC,ah)=>{"use strict";var ih=ke(),DE=rh(),ME=Xt(),OE=K(),BE=OE("species");ah.exports=function(i,e){var t=ih(i).constructor,r;return t===void 0||ME(r=ih(t)[BE])?e:DE(r)}});var nh=m((cC,sh)=>{"use strict";var VE=re();sh.exports=VE([].slice)});var uh=m((dC,oh)=>{"use strict";var _E=TypeError;oh.exports=function(i,e){if(i<e)throw _E("Not enough arguments");return i}});var Zn=m((pC,lh)=>{"use strict";var NE=Cr();lh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(NE)});var uo=m((hC,vh)=>{"use strict";var pe=W(),FE=xn(),qE=Nr(),ch=q(),UE=Re(),gh=de(),dh=Cn(),HE=nh(),ph=oa(),jE=uh(),GE=Zn(),YE=Ur(),so=pe.setImmediate,no=pe.clearImmediate,WE=pe.process,eo=pe.Dispatch,QE=pe.Function,hh=pe.MessageChannel,zE=pe.String,to=0,jr={},fh="onreadystatechange",Gr,At,ro,io;gh(function(){Gr=pe.location});var oo=function(i){if(UE(jr,i)){var e=jr[i];delete jr[i],e()}},ao=function(i){return function(){oo(i)}},mh=function(i){oo(i.data)},bh=function(i){pe.postMessage(zE(i),Gr.protocol+"//"+Gr.host)};(!so||!no)&&(so=function(e){jE(arguments.length,1);var t=ch(e)?e:QE(e),r=HE(arguments,1);return jr[++to]=function(){FE(t,void 0,r)},At(to),to},no=function(e){delete jr[e]},YE?At=function(i){WE.nextTick(ao(i))}:eo&&eo.now?At=function(i){eo.now(ao(i))}:hh&&!GE?(ro=new hh,io=ro.port2,ro.port1.onmessage=mh,At=qE(io.postMessage,io)):pe.addEventListener&&ch(pe.postMessage)&&!pe.importScripts&&Gr&&Gr.protocol!=="file:"&&!gh(bh)?(At=bh,pe.addEventListener("message",mh,!1)):fh in ph("script")?At=function(i){dh.appendChild(ph("script"))[fh]=function(){dh.removeChild(this),oo(i)}}:At=function(i){setTimeout(ao(i),0)});vh.exports={set:so,clear:no}});var lo=m((fC,yh)=>{"use strict";var Sh=function(){this.head=null,this.tail=null};Sh.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}}};yh.exports=Sh});var Ih=m((mC,Th)=>{"use strict";var KE=Cr();Th.exports=/ipad|iphone|ipod/i.test(KE)&&typeof Pebble!="undefined"});var xh=m((bC,Eh)=>{"use strict";var JE=Cr();Eh.exports=/web0s(?!.*chrome)/i.test(JE)});var Ch=m((gC,$h)=>{"use strict";var Rt=W(),Ph=Nr(),XE=kn().f,co=uo().set,ZE=lo(),ex=Zn(),tx=Ih(),rx=xh(),po=Ur(),kh=Rt.MutationObserver||Rt.WebKitMutationObserver,wh=Rt.document,Ah=Rt.process,Ma=Rt.Promise,Rh=XE(Rt,"queueMicrotask"),mo=Rh&&Rh.value,sr,ho,fo,Oa,Lh;mo||(Yr=new ZE,Wr=function(){var i,e;for(po&&(i=Ah.domain)&&i.exit();e=Yr.get();)try{e()}catch(t){throw Yr.head&&sr(),t}i&&i.enter()},!ex&&!po&&!rx&&kh&&wh?(ho=!0,fo=wh.createTextNode(""),new kh(Wr).observe(fo,{characterData:!0}),sr=function(){fo.data=ho=!ho}):!tx&&Ma&&Ma.resolve?(Oa=Ma.resolve(void 0),Oa.constructor=Ma,Lh=Ph(Oa.then,Oa),sr=function(){Lh(Wr)}):po?sr=function(){Ah.nextTick(Wr)}:(co=Ph(co,Rt),sr=function(){co(Wr)}),mo=function(i){Yr.head||sr(),Yr.add(i)});var Yr,Wr;$h.exports=mo});var Mh=m((vC,Dh)=>{"use strict";Dh.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var Ba=m((SC,Oh)=>{"use strict";Oh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Lt=m((yC,Bh)=>{"use strict";var ix=W();Bh.exports=ix.Promise});var bo=m((TC,Vh)=>{"use strict";Vh.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var Nh=m((IC,_h)=>{"use strict";var ax=bo(),sx=Ur();_h.exports=!ax&&!sx&&typeof window=="object"&&typeof document=="object"});var nr=m((EC,Uh)=>{"use strict";var nx=W(),Qr=Lt(),ox=q(),ux=wn(),lx=Kn(),cx=K(),dx=Nh(),px=bo(),hx=Ae(),go=nn(),Fh=Qr&&Qr.prototype,fx=cx("species"),vo=!1,qh=ox(nx.PromiseRejectionEvent),mx=ux("Promise",function(){var i=lx(Qr),e=i!==String(Qr);if(!e&&go===66||hx&&!(Fh.catch&&Fh.finally))return!0;if(!go||go<51||!/native code/.test(i)){var t=new Qr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[fx]=r,vo=t.then(function(){})instanceof r,!vo)return!0}return!e&&(dx||px)&&!qh});Uh.exports={CONSTRUCTOR:mx,REJECTION_EVENT:qh,SUBCLASSING:vo}});var or=m((xC,jh)=>{"use strict";var Hh=He(),bx=TypeError,gx=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw bx("Bad Promise constructor");e=r,t=a}),this.resolve=Hh(e),this.reject=Hh(t)};jh.exports.f=function(i){return new gx(i)}});var cf=m(()=>{"use strict";var vx=ge(),Sx=Ae(),Fa=Ur(),st=W(),dr=ie(),Gh=ir(),Yh=Hn(),yx=Pa(),Tx=Gp(),Ix=He(),Na=q(),Ex=Be(),xx=Wp(),Px=Xn(),Jh=uo().set,Eo=Ch(),kx=Mh(),wx=Ba(),Ax=lo(),Xh=En(),qa=Lt(),xo=nr(),Zh=or(),Ua="Promise",ef=xo.CONSTRUCTOR,Rx=xo.REJECTION_EVENT,Lx=xo.SUBCLASSING,So=Xh.getterFor(Ua),$x=Xh.set,ur=qa&&qa.prototype,$t=qa,Va=ur,tf=st.TypeError,yo=st.document,Po=st.process,To=Zh.f,Cx=To,Dx=!!(yo&&yo.createEvent&&st.dispatchEvent),rf="unhandledrejection",Mx="rejectionhandled",Wh=0,af=1,Ox=2,ko=1,sf=2,_a,Qh,Bx,zh,nf=function(i){var e;return Ex(i)&&Na(e=i.then)?e:!1},of=function(i,e){var t=e.value,r=e.state==af,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===sf&&_x(e),e.rejection=ko),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(tf("Promise-chain cycle")):(u=nf(l))?dr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},uf=function(i,e){i.notified||(i.notified=!0,Eo(function(){for(var t=i.reactions,r;r=t.get();)of(r,i);i.notified=!1,e&&!i.rejection&&Vx(i)}))},lf=function(i,e,t){var r,a;Dx?(r=yo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),st.dispatchEvent(r)):r={promise:e,reason:t},!Rx&&(a=st["on"+i])?a(r):i===rf&&kx("Unhandled promise rejection",t)},Vx=function(i){dr(Jh,st,function(){var e=i.facade,t=i.value,r=Kh(i),a;if(r&&(a=wx(function(){Fa?Po.emit("unhandledRejection",t,e):lf(rf,e,t)}),i.rejection=Fa||Kh(i)?sf:ko,a.error))throw a.value})},Kh=function(i){return i.rejection!==ko&&!i.parent},_x=function(i){dr(Jh,st,function(){var e=i.facade;Fa?Po.emit("rejectionHandled",e):lf(Mx,e,i.value)})},lr=function(i,e,t){return function(r){i(e,r,t)}},cr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Ox,uf(i,!0))},Io=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw tf("Promise can't be resolved itself");var r=nf(e);r?Eo(function(){var a={done:!1};try{dr(r,e,lr(Io,a,i),lr(cr,a,i))}catch(s){cr(a,s,i)}}):(i.value=e,i.state=af,uf(i,!1))}catch(a){cr({done:!1},a,i)}}};if(ef&&($t=function(e){xx(this,Va),Ix(e),dr(_a,this);var t=So(this);try{e(lr(Io,t),lr(cr,t))}catch(r){cr(t,r)}},Va=$t.prototype,_a=function(e){$x(this,{type:Ua,done:!1,notified:!1,parent:!1,reactions:new Ax,rejection:!1,state:Wh,value:void 0})},_a.prototype=Gh(Va,"then",function(e,t){var r=So(this),a=To(Px(this,$t));return r.parent=!0,a.ok=Na(e)?e:!0,a.fail=Na(t)&&t,a.domain=Fa?Po.domain:void 0,r.state==Wh?r.reactions.add(a):Eo(function(){of(a,r)}),a.promise}),Qh=function(){var i=new _a,e=So(i);this.promise=i,this.resolve=lr(Io,e),this.reject=lr(cr,e)},Zh.f=To=function(i){return i===$t||i===Bx?new Qh(i):Cx(i)},!Sx&&Na(qa)&&ur!==Object.prototype)){zh=ur.then,Lx||Gh(ur,"then",function(e,t){var r=this;return new $t(function(a,s){dr(zh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete ur.constructor}catch(i){}Yh&&Yh(ur,Va)}vx({global:!0,constructor:!0,wrap:!0,forced:ef},{Promise:$t});yx($t,Ua,!1,!0);Tx(Ua)});var mf=m((wC,ff)=>{"use strict";var Nx=K(),pf=Nx("iterator"),hf=!1;try{df=0,wo={next:function(){return{done:!!df++}},return:function(){hf=!0}},wo[pf]=function(){return this},Array.from(wo,function(){throw 2})}catch(i){}var df,wo;ff.exports=function(i,e){if(!e&&!hf)return!1;var t=!1;try{var r={};r[pf]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var Ao=m((AC,bf)=>{"use strict";var Fx=Lt(),qx=mf(),Ux=nr().CONSTRUCTOR;bf.exports=Ux||!qx(function(i){Fx.all(i).then(void 0,function(){})})});var gf=m(()=>{"use strict";var Hx=ge(),jx=ie(),Gx=He(),Yx=or(),Wx=Ba(),Qx=La(),zx=Ao();Hx({target:"Promise",stat:!0,forced:zx},{all:function(e){var t=this,r=Yx.f(t),a=r.resolve,s=r.reject,n=Wx(function(){var o=Gx(t.resolve),l=[],u=0,c=1;Qx(e,function(d){var p=u++,f=!1;c++,jx(o,t,d).then(function(h){f||(f=!0,l[p]=h,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var Sf=m(()=>{"use strict";var Kx=ge(),Jx=Ae(),Xx=nr().CONSTRUCTOR,Lo=Lt(),Zx=Ue(),eP=q(),tP=ir(),vf=Lo&&Lo.prototype;Kx({target:"Promise",proto:!0,forced:Xx,real:!0},{catch:function(i){return this.then(void 0,i)}});!Jx&&eP(Lo)&&(Ro=Zx("Promise").prototype.catch,vf.catch!==Ro&&tP(vf,"catch",Ro,{unsafe:!0}));var Ro});var yf=m(()=>{"use strict";var rP=ge(),iP=ie(),aP=He(),sP=or(),nP=Ba(),oP=La(),uP=Ao();rP({target:"Promise",stat:!0,forced:uP},{race:function(e){var t=this,r=sP.f(t),a=r.reject,s=nP(function(){var n=aP(t.resolve);oP(e,function(o){iP(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Tf=m(()=>{"use strict";var lP=ge(),cP=ie(),dP=or(),pP=nr().CONSTRUCTOR;lP({target:"Promise",stat:!0,forced:pP},{reject:function(e){var t=dP.f(this);return cP(t.reject,void 0,e),t.promise}})});var $o=m((VC,If)=>{"use strict";var hP=ke(),fP=Be(),mP=or();If.exports=function(i,e){if(hP(i),fP(e)&&e.constructor===i)return e;var t=mP.f(i),r=t.resolve;return r(e),t.promise}});var Pf=m(()=>{"use strict";var bP=ge(),gP=Ue(),Ef=Ae(),vP=Lt(),xf=nr().CONSTRUCTOR,SP=$o(),yP=gP("Promise"),TP=Ef&&!xf;bP({target:"Promise",stat:!0,forced:Ef||xf},{resolve:function(e){return SP(TP&&this===yP?vP:this,e)}})});var kf=m(()=>{"use strict";cf();gf();Sf();yf();Tf();Pf()});var Lf=m(()=>{"use strict";var IP=ge(),EP=Ae(),Ha=Lt(),xP=de(),Af=Ue(),Rf=q(),PP=Xn(),wf=$o(),kP=ir(),Do=Ha&&Ha.prototype,wP=!!Ha&&xP(function(){Do.finally.call({then:function(){}},function(){})});IP({target:"Promise",proto:!0,real:!0,forced:wP},{finally:function(i){var e=PP(this,Af("Promise")),t=Rf(i);return this.then(t?function(r){return wf(e,i()).then(function(){return r})}:i,t?function(r){return wf(e,i()).then(function(){throw r})}:i)}});!EP&&Rf(Ha)&&(Co=Af("Promise").prototype.finally,Do.finally!==Co&&kP(Do,"finally",Co,{unsafe:!0}));var Co});var ja=m((jC,$f)=>{"use strict";var AP=Ue();$f.exports=AP});var Df=m((GC,Cf)=>{"use strict";Np();kf();Lf();var RP=ja();Cf.exports=RP("Promise","finally")});var Of=m((YC,Mf)=>{"use strict";var LP=Df();Mf.exports=LP});var Ga=m((WC,Bf)=>{"use strict";var $P=Of();Bf.exports=$P});var nm=m(()=>{"use strict";var ik=ge(),ak=Or(),sk=ya(),nk=Sa(),ok=Ks();ik({target:"Array",proto:!0},{at:function(e){var t=ak(this),r=sk(t),a=nk(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});ok("at")});var um=m((rM,om)=>{"use strict";nm();var uk=ja();om.exports=uk("Array","at")});var cm=m((iM,lm)=>{"use strict";var lk=um();lm.exports=lk});var Qa=m((aM,dm)=>{"use strict";var ck=cm();dm.exports=ck});var Hm=m(()=>{"use strict"});var jm=m(()=>{"use strict"});var Ym=m((jB,Gm)=>{"use strict";var mw=Be(),bw=Jt(),gw=K(),vw=gw("match");Gm.exports=function(i){var e;return mw(i)&&((e=i[vw])!==void 0?!!e:bw(i)=="RegExp")}});var Qm=m((GB,Wm)=>{"use strict";var Sw=ar(),yw=String;Wm.exports=function(i){if(Sw(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return yw(i)}});var Km=m((YB,zm)=>{"use strict";var Tw=ke();zm.exports=function(){var i=Tw(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 Zm=m((WB,Xm)=>{"use strict";var Iw=ie(),Ew=Re(),xw=$r(),Pw=Km(),Jm=RegExp.prototype;Xm.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Jm)&&!Ew(i,"flags")&&xw(Jm,i)?Iw(Pw,i):e}});var tb=m((QB,eb)=>{"use strict";var nu=re(),kw=Or(),ww=Math.floor,au=nu("".charAt),Aw=nu("".replace),su=nu("".slice),Rw=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Lw=/\$([$&'`]|\d{1,2})/g;eb.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=Lw;return a!==void 0&&(a=kw(a),l=Rw),Aw(s,l,function(u,c){var d;switch(au(c,0)){case"$":return"$";case"&":return i;case"`":return su(e,0,t);case"'":return su(e,n);case"<":d=a[su(c,1,-1)];break;default:var p=+c;if(p===0)return u;if(p>o){var f=ww(p/10);return f===0?u:f<=o?r[f-1]===void 0?au(c,1):r[f-1]+au(c,1):u}d=r[p-1]}return d===void 0?"":d})}});var nb=m(()=>{"use strict";var $w=ge(),Cw=ie(),ou=re(),rb=sa(),Dw=q(),Mw=Xt(),Ow=Ym(),vr=Qm(),Bw=Mr(),Vw=Zm(),_w=tb(),Nw=K(),Fw=Ae(),qw=Nw("replace"),Uw=TypeError,sb=ou("".indexOf),Hw=ou("".replace),ib=ou("".slice),jw=Math.max,ab=function(i,e,t){return t>i.length?-1:e===""?t:sb(i,e,t)};$w({target:"String",proto:!0},{replaceAll:function(e,t){var r=rb(this),a,s,n,o,l,u,c,d,p,f=0,h=0,b="";if(!Mw(e)){if(a=Ow(e),a&&(s=vr(rb(Vw(e))),!~sb(s,"g")))throw Uw("`.replaceAll` does not allow non-global regexes");if(n=Bw(e,qw),n)return Cw(n,e,r,t);if(Fw&&a)return Hw(vr(r),e,t)}for(o=vr(r),l=vr(e),u=Dw(t),u||(t=vr(t)),c=l.length,d=jw(1,c),f=ab(o,l,0);f!==-1;)p=u?vr(t(l,f,o)):_w(l,o,f,[],void 0,t),b+=ib(o,h,f)+p,h=f+c,f=ab(o,l,f+d);return h<o.length&&(b+=ib(o,h)),b}})});var ub=m((JB,ob)=>{"use strict";Hm();jm();nb();var Gw=ja();ob.exports=Gw("String","replaceAll")});var cb=m((XB,lb)=>{"use strict";var Yw=ub();lb.exports=Yw});var pb=m((ZB,db)=>{"use strict";var Ww=cb();db.exports=Ww});var rl="__VERSION__";var ce=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ce||{}),Et=(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))(Et||{});var ra=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(ra||{}),js=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(js||{});var Gs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Gs||{});import{assertNever as ul,assertNonNullable as hv,isNonNullable as ia,ValueSubject as Ys,Subject as fv,Subscription as mv,merge as bv,observableFrom as gv,fromEvent as al,map as sl,tap as nl,filterChanged as vv,isNullable as Ws,ErrorCategory as ol}from"@vkontakte/videoplayer-shared";var il=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 aa=class{constructor(e){this.connection$=new Ys(void 0);this.castState$=new Ys("NOT_AVAILABLE");this.errorEvent$=new fv;this.realCastState$=new Ys("NOT_AVAILABLE");this.subscription=new mv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=ia((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||il("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ol.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,a,s;(s=(a=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:a.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ia(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ws(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ws(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(al(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var s,n;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.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 ul(a.sessionState)}})).add(bv(al(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(nl(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),sl(a=>a.castState)),gv([r.getCastState()])).pipe(vv(),sl(Sv),nl(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=ia(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();hv(l);let u=l.getCastDevice(),c=(o=l.getMediaSession())==null?void 0:o.media.contentId;(Ws(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?ia(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){var a;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(a=this.params.receiverApplicationId)!=null?a:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:ol.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Sv=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 ul(i)}};var Rg=Oe(Da(),1);var Yf=Oe(Ga(),1);import{assertNever as Vf}from"@vkontakte/videoplayer-shared";var J=(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:Vf(t)}return i},Mo=(i,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Vf(e)}};var T=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as CP,Subject as Ya,merge as _f}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Ya;this.transitionEnded$=new Ya;this.transitionUpdated$=new Ya;this.forceChanged$=new Ya;this.stateChangeStarted$=_f(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_f(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||CP(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 DP}from"@vkontakte/videoplayer-shared";var Nf=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 DP(i)}};import{assertNever as pr,assertNonNullable as Ct,debounce as Ff,ErrorCategory as qf,fromEvent as Dt,isNonNullable as Uf,map as Hf,merge as jf,observableFrom as MP,Subject as OP,Subscription as Oo,timeout as BP,getHighestQuality as VP}from"@vkontakte/videoplayer-shared";var _P=5,NP=5,FP=500,Gf=7e3,zr=class{constructor(e){this.subscription=new Oo;this.loadMediaTimeoutSubscription=new Oo;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==null?void 0: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:pr(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:pr(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:pr(e)}break}default:pr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Nf(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 Oo;this.subscription.add(e),this.subscription.add(jf(this.videoState.stateChangeStarted$.pipe(Hf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Hf(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 OP;e.add(a.pipe(Ff(FP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Dt(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)>_P)&&a.next(o),s=o})),e.add(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Dt(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<NP&&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:pr(n)}}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=jf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,MP(["init"])).pipe(Ff(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(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&T(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var a,s;let t=this.params.output.volume$.getValue(),r={volume:(a=e.volume)!=null?a:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var u;let t=this.params.source,r,a,s;switch(e){case"MPEG":{let c=t[e];Ct(c);let d=VP(Object.keys(c));Ct(d);let p=c[d];Ct(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Ct(c),r=c.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 c=t[e];Ct(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Ct(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Ct(c),r=J(c.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:qf.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return pr(e)}let n=new chrome.cast.media.MediaInfo((u=this.params.meta.videoId)!=null?u: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(BP(Gf).subscribe(()=>s(`timeout(${Gf})`)))});(0,Yf.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:qf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Kr=i=>{i.removeAttribute("src"),i.load()};var Wf=i=>{try{i.pause(),i.playbackRate=0,Kr(i),i.remove()}catch(e){console.error(e)}};var Bo=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)}},Vo=window.WeakMap?new WeakMap:new Bo,ae=i=>{let e=i.querySelector("video"),t=!!e;return e?Kr(e):(e=document.createElement("video"),i.appendChild(e)),Vo.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},se=i=>{let e=Vo.get(i);Vo.delete(i),e?Kr(i):Wf(i)};import{assertNonNullable as Jr,isNonNullable as Ne,isNullable as HP,fromEvent as hr,merge as Qf,observableFrom as zf,filterChanged as Kf,map as Xr,Subject as Jf,Subscription as jP,ValueSubject as GP,ErrorCategory as YP}from"@vkontakte/videoplayer-shared";import{isNonNullable as _o,isNullable as qP,Subscription as UP}from"@vkontakte/videoplayer-shared";var Wa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=qP(a),u=new UP;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)=>Wa(e,()=>i.loop,r=>{_o(r)&&(i.loop=r)},{onError:t}),ne=(i,e,t,r)=>Wa(e,()=>({muted:i.muted,volume:i.volume}),a=>{_o(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||(a==null?void 0:a.muted)===(s==null?void 0:s.muted)&&(a==null?void 0:a.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),ve=(i,e,t,r)=>Wa(e,()=>i.playbackRate,a=>{_o(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),nt=Wa;var WP=i=>["__",i.language,i.label].join("|"),QP=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},No=class i{constructor(){this.available$=new Jf;this.current$=new GP(void 0);this.error$=new Jf;this.subscription=new jP;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:YP.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(nt(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(Xr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(nt(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(Xr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(nt(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(nt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Jr(this.video);let{textTracks:e}=this.video;this.subscription.add(hr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Qf(hr(e,"addtrack"),hr(e,"removetrack"),zf(["init"])).pipe(Xr(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Kf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Qf(hr(e,"change"),zf(["init"])).pipe(Xr(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Xr(r=>r&&this.htmlTextTrackToITextTrack(r).id),Kf()).subscribe(this.current$));let t=r=>{var a,s;return this.applyCueSettings((s=(a=r.target)==null?void 0:a.activeCues)!=null?s:null)};this.subscription.add(hr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let a=o=>{var u,c,d,p,f;let l=(c=(u=o.target)==null?void 0:u.cues)!=null?c:null;l&&l.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(f=o.target)==null||f.removeEventListener("cuechange",a))};(n=r.track)==null||n.addEventListener("cuechange",a)})),this.subscription.add(hr(e,"removetrack").subscribe(r=>{var a;(a=r.track)==null||a.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){Jr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,l;let{language:t,label:r}=e,a=e.id?e.id:WP(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(a))==null?void 0:o.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:(l=this.internalTracks.get(a))==null?void 0:l.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){Jr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(HP(e)||!QP(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){Jr(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){Jr(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)}},Se=No;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 Xf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Fo=i=>{let e=Xf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Zf=i=>{let e=Xf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as ye,map as ot,merge as tm,filterChanged as KP,isNonNullable as rm,Subject as JP,filter as im,mapTo as am,combine as XP,once as ZP,ErrorCategory as ek,ValueSubject as sm,getCurrentBrowser as tk,CurrentClientBrowser as rk}from"@vkontakte/videoplayer-shared";var zP=3,em=(i,e,t=zP)=>{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 oe=i=>{let e=I=>ye(i,I).pipe(am(void 0)),r=tm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>ye(i,I))).pipe(ot(I=>I.type==="ended"?i.readyState<2:i.readyState<3),KP()),a=tm(ye(i,"progress"),ye(i,"timeupdate")).pipe(ot(()=>em(i.buffered,i.currentTime))),n=tk().browser===rk.Safari?XP({play:e("play").pipe(ZP()),playing:e("playing")}).pipe(am(void 0)):e("playing"),o=ye(i,"volumechange").pipe(ot(()=>({muted:i.muted,volume:i.volume}))),l=ye(i,"ratechange").pipe(ot(()=>i.playbackRate)),u=ye(i,"error").pipe(im(()=>!!(i.error||i.played.length)),ot(()=>{var y;let I=i.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:ek.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(y=i.error)!=null?y:void 0}})),c=ye(i,"timeupdate").pipe(ot(()=>i.currentTime)),d=new JP,p=.3,f;c.subscribe(I=>{i.loop&&rm(f)&&rm(I)&&f>=i.duration-p&&I<=p&&d.next(f),f=I});let h=ye(i,"enterpictureinpicture"),b=ye(i,"leavepictureinpicture"),v=new sm(Zf(i));h.subscribe(()=>v.next(!0)),b.subscribe(()=>v.next(!1));let S=new sm(Fo(i));return ye(i,"fullscreenchange").pipe(ot(()=>Fo(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(im(()=>!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$:ye(i,"durationchange").pipe(ot(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:v,inFullscreen$:S}};import{VideoQuality as ut}from"@vkontakte/videoplayer-shared";var lt=i=>{switch(i){case"mobile":return ut.Q_144P;case"lowest":return ut.Q_240P;case"low":return ut.Q_360P;case"sd":case"medium":return ut.Q_480P;case"hd":case"high":return ut.Q_720P;case"fullhd":case"full":return ut.Q_1080P;case"quadhd":case"quad":return ut.Q_1440P;case"ultrahd":case"ultra":return ut.Q_2160P}};var Go=Oe(Qa(),1);import{isNonNullable as ct,isNullable as Uo,now as gm,isHigher as Ho,isHigherOrEqual as mm,isInvariantQuality as bm,isLower as jo,isLowerOrEqual as dk,videoSizeToQuality as pk,assertNotEmptyArray as hk}from"@vkontakte/videoplayer-shared";var qo=!1,We={},pm=i=>{qo=i},hm=()=>{We={}},fm=i=>{i(We)},Zr=(i,e)=>{var t;qo&&(We.meta=(t=We.meta)!=null?t:{},We.meta[i]=e)},Z=class{constructor(e){this.name=e}next(e){var r,a;if(!qo)return;We.series=(r=We.series)!=null?r:{};let t=(a=We.series[this.name])!=null?a:[];t.push([Date.now(),e]),We.series[this.name]=t}};var fk=new Z("best_bitrate"),mk=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,za=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=gm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},bk='Assertion "ABR Tracks is empty array" failed',gk=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var $,C,k,U,ee;hk(i,bk);let p=r.usePixelRatio&&($=window.devicePixelRatio)!=null?$:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},h=f&&pk(f),b=r.considerPlaybackRate&&ct(o)?o:1,v=i.filter(w=>!bm(w.quality)).sort((w,x)=>Ho(w.quality,x.quality)?-1:1),S=(C=(0,Go.default)(v,-1))==null?void 0:C.quality,g=(k=(0,Go.default)(v,0))==null?void 0:k.quality,I=Uo(a)||ct(a.min)&&ct(a.max)&&jo(a.max,a.min)||ct(a.min)&&g&&Ho(a.min,g)||ct(a.max)&&S&&jo(a.max,S),y=b*mk(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),E={},R=v.filter(w=>(h?jo(w.quality,h):!0)?(ct(t)&&isFinite(t)&&ct(w.bitrate)?t-s>=w.bitrate*y:!0)?r.lazyQualitySwitch&&ct(r.minBufferToSwitchUp)&&l&&!bm(l.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Ho(w.quality,l.quality)?(E[w.quality]="Buffer",!1):!!c&&mm(w.quality,c)?(E[w.quality]="DroppedFramesLimit",!1):I||(Uo(a.max)||dk(w.quality,a.max))&&(Uo(a.min)||mm(w.quality,a.min))?!0:(E[w.quality]="FitsQualityLimits",!1):(E[w.quality]="FitsThroughput",!1):(E[w.quality]="FitsContainer",!1))[0];R&&R.bitrate&&fk.next(R.bitrate);let A=(U=R!=null?R:v[Math.ceil((v.length-1)/2)])!=null?U:i[0];A.quality!==((ee=u==null?void 0:u.last)==null?void 0:ee.quality)&&d({message:`
6
+ var dv=Object.create;var sl=Object.defineProperty;var pv=Object.getOwnPropertyDescriptor;var hv=Object.getOwnPropertyNames;var fv=Object.getPrototypeOf,mv=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var bv=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of hv(e))!mv.call(i,a)&&a!==t&&sl(i,a,{get:()=>e[a],enumerable:!(r=pv(e,a))||r.enumerable});return i};var Oe=(i,e,t)=>(t=i!=null?dv(fv(i)):{},bv(e||!i||!i.__esModule?sl(t,"default",{value:i,enumerable:!0}):t,i));var de=m((gL,hl)=>{"use strict";hl.exports=function(i){try{return!!i()}catch(e){return!0}}});var $r=m((vL,fl)=>{"use strict";var xv=de();fl.exports=!xv(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var re=m((SL,gl)=>{"use strict";var ml=$r(),bl=Function.prototype,Js=bl.call,Pv=ml&&bl.bind.bind(Js,Js);gl.exports=ml?Pv:function(i){return function(){return Js.apply(i,arguments)}}});var Jt=m((yL,Sl)=>{"use strict";var vl=re(),wv=vl({}.toString),Av=vl("".slice);Sl.exports=function(i){return Av(wv(i),8,-1)}});var Tl=m((TL,yl)=>{"use strict";var kv=re(),Rv=de(),Lv=Jt(),Xs=Object,$v=kv("".split);yl.exports=Rv(function(){return!Xs("z").propertyIsEnumerable(0)})?function(i){return Lv(i)=="String"?$v(i,""):Xs(i)}:Xs});var Xt=m((IL,Il)=>{"use strict";Il.exports=function(i){return i==null}});var oa=m((EL,El)=>{"use strict";var Cv=Xt(),Dv=TypeError;El.exports=function(i){if(Cv(i))throw Dv("Can't call method on "+i);return i}});var Zt=m((xL,xl)=>{"use strict";var Mv=Tl(),Ov=oa();xl.exports=function(i){return Mv(Ov(i))}});var Zs=m((PL,Pl)=>{"use strict";Pl.exports=function(){}});var xt=m((wL,wl)=>{"use strict";wl.exports={}});var W=m((Al,kl)=>{"use strict";var ua=function(i){return i&&i.Math==Math&&i};kl.exports=ua(typeof globalThis=="object"&&globalThis)||ua(typeof window=="object"&&window)||ua(typeof self=="object"&&self)||ua(typeof global=="object"&&global)||function(){return this}()||Al||Function("return this")()});var tn=m((AL,Rl)=>{"use strict";var en=typeof document=="object"&&document.all,Bv=typeof en=="undefined"&&en!==void 0;Rl.exports={all:en,IS_HTMLDDA:Bv}});var q=m((kL,$l)=>{"use strict";var Ll=tn(),Vv=Ll.all;$l.exports=Ll.IS_HTMLDDA?function(i){return typeof i=="function"||i===Vv}:function(i){return typeof i=="function"}});var Ml=m((RL,Dl)=>{"use strict";var _v=W(),Nv=q(),Cl=_v.WeakMap;Dl.exports=Nv(Cl)&&/native code/.test(String(Cl))});var Be=m((LL,Vl)=>{"use strict";var Ol=q(),Bl=tn(),Fv=Bl.all;Vl.exports=Bl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Ol(i)||i===Fv}:function(i){return typeof i=="object"?i!==null:Ol(i)}});var Ve=m(($L,_l)=>{"use strict";var qv=de();_l.exports=!qv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var la=m((CL,Fl)=>{"use strict";var Uv=W(),Nl=Be(),rn=Uv.document,Hv=Nl(rn)&&Nl(rn.createElement);Fl.exports=function(i){return Hv?rn.createElement(i):{}}});var an=m((DL,ql)=>{"use strict";var jv=Ve(),Gv=de(),Yv=la();ql.exports=!jv&&!Gv(function(){return Object.defineProperty(Yv("div"),"a",{get:function(){return 7}}).a!=7})});var sn=m((ML,Ul)=>{"use strict";var Wv=Ve(),Qv=de();Ul.exports=Wv&&Qv(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var we=m((OL,Hl)=>{"use strict";var zv=Be(),Kv=String,Jv=TypeError;Hl.exports=function(i){if(zv(i))return i;throw Jv(Kv(i)+" is not an object")}});var ie=m((BL,jl)=>{"use strict";var Xv=$r(),ca=Function.prototype.call;jl.exports=Xv?ca.bind(ca):function(){return ca.apply(ca,arguments)}});var da=m((VL,Gl)=>{"use strict";Gl.exports={}});var Ue=m((_L,Wl)=>{"use strict";var nn=da(),on=W(),Zv=q(),Yl=function(i){return Zv(i)?i:void 0};Wl.exports=function(i,e){return arguments.length<2?Yl(nn[i])||Yl(on[i]):nn[i]&&nn[i][e]||on[i]&&on[i][e]}});var Cr=m((NL,Ql)=>{"use strict";var eS=re();Ql.exports=eS({}.isPrototypeOf)});var Dr=m((FL,zl)=>{"use strict";zl.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var ln=m((qL,tc)=>{"use strict";var ec=W(),un=Dr(),Kl=ec.process,Jl=ec.Deno,Xl=Kl&&Kl.versions||Jl&&Jl.version,Zl=Xl&&Xl.v8,Ae,pa;Zl&&(Ae=Zl.split("."),pa=Ae[0]>0&&Ae[0]<4?1:+(Ae[0]+Ae[1]));!pa&&un&&(Ae=un.match(/Edge\/(\d+)/),(!Ae||Ae[1]>=74)&&(Ae=un.match(/Chrome\/(\d+)/),Ae&&(pa=+Ae[1])));tc.exports=pa});var cn=m((UL,ic)=>{"use strict";var rc=ln(),tS=de(),rS=W(),iS=rS.String;ic.exports=!!Object.getOwnPropertySymbols&&!tS(function(){var i=Symbol();return!iS(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&rc&&rc<41})});var dn=m((HL,ac)=>{"use strict";var aS=cn();ac.exports=aS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var pn=m((jL,sc)=>{"use strict";var sS=Ue(),nS=q(),oS=Cr(),uS=dn(),lS=Object;sc.exports=uS?function(i){return typeof i=="symbol"}:function(i){var e=sS("Symbol");return nS(e)&&oS(e.prototype,lS(i))}});var Mr=m((GL,nc)=>{"use strict";var cS=String;nc.exports=function(i){try{return cS(i)}catch(e){return"Object"}}});var He=m((YL,oc)=>{"use strict";var dS=q(),pS=Mr(),hS=TypeError;oc.exports=function(i){if(dS(i))return i;throw hS(pS(i)+" is not a function")}});var Or=m((WL,uc)=>{"use strict";var fS=He(),mS=Xt();uc.exports=function(i,e){var t=i[e];return mS(t)?void 0:fS(t)}});var cc=m((QL,lc)=>{"use strict";var hn=ie(),fn=q(),mn=Be(),bS=TypeError;lc.exports=function(i,e){var t,r;if(e==="string"&&fn(t=i.toString)&&!mn(r=hn(t,i))||fn(t=i.valueOf)&&!mn(r=hn(t,i))||e!=="string"&&fn(t=i.toString)&&!mn(r=hn(t,i)))return r;throw bS("Can't convert object to primitive value")}});var ke=m((zL,dc)=>{"use strict";dc.exports=!0});var fc=m((KL,hc)=>{"use strict";var pc=W(),gS=Object.defineProperty;hc.exports=function(i,e){try{gS(pc,i,{value:e,configurable:!0,writable:!0})}catch(t){pc[i]=e}return e}});var ha=m((JL,bc)=>{"use strict";var vS=W(),SS=fc(),mc="__core-js_shared__",yS=vS[mc]||SS(mc,{});bc.exports=yS});var bn=m((XL,vc)=>{"use strict";var TS=ke(),gc=ha();(vc.exports=function(i,e){return gc[i]||(gc[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:TS?"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 Br=m((ZL,Sc)=>{"use strict";var IS=oa(),ES=Object;Sc.exports=function(i){return ES(IS(i))}});var Re=m((e$,yc)=>{"use strict";var xS=re(),PS=Br(),wS=xS({}.hasOwnProperty);yc.exports=Object.hasOwn||function(e,t){return wS(PS(e),t)}});var gn=m((t$,Tc)=>{"use strict";var AS=re(),kS=0,RS=Math.random(),LS=AS(1 .toString);Tc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+LS(++kS+RS,36)}});var K=m((r$,Ec)=>{"use strict";var $S=W(),CS=bn(),Ic=Re(),DS=gn(),MS=cn(),OS=dn(),er=$S.Symbol,vn=CS("wks"),BS=OS?er.for||er:er&&er.withoutSetter||DS;Ec.exports=function(i){return Ic(vn,i)||(vn[i]=MS&&Ic(er,i)?er[i]:BS("Symbol."+i)),vn[i]}});var Ac=m((i$,wc)=>{"use strict";var VS=ie(),xc=Be(),Pc=pn(),_S=Or(),NS=cc(),FS=K(),qS=TypeError,US=FS("toPrimitive");wc.exports=function(i,e){if(!xc(i)||Pc(i))return i;var t=_S(i,US),r;if(t){if(e===void 0&&(e="default"),r=VS(t,i,e),!xc(r)||Pc(r))return r;throw qS("Can't convert object to primitive value")}return e===void 0&&(e="number"),NS(i,e)}});var fa=m((a$,kc)=>{"use strict";var HS=Ac(),jS=pn();kc.exports=function(i){var e=HS(i,"string");return jS(e)?e:e+""}});var Pt=m(Lc=>{"use strict";var GS=Ve(),YS=an(),WS=sn(),ma=we(),Rc=fa(),QS=TypeError,Sn=Object.defineProperty,zS=Object.getOwnPropertyDescriptor,yn="enumerable",Tn="configurable",In="writable";Lc.f=GS?WS?function(e,t,r){if(ma(e),t=Rc(t),ma(r),typeof e=="function"&&t==="prototype"&&"value"in r&&In in r&&!r[In]){var a=zS(e,t);a&&a[In]&&(e[t]=r.value,r={configurable:Tn in r?r[Tn]:a[Tn],enumerable:yn in r?r[yn]:a[yn],writable:!1})}return Sn(e,t,r)}:Sn:function(e,t,r){if(ma(e),t=Rc(t),ma(r),YS)try{return Sn(e,t,r)}catch(a){}if("get"in r||"set"in r)throw QS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Vr=m((n$,$c)=>{"use strict";$c.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var wt=m((o$,Cc)=>{"use strict";var KS=Ve(),JS=Pt(),XS=Vr();Cc.exports=KS?function(i,e,t){return JS.f(i,e,XS(1,t))}:function(i,e,t){return i[e]=t,i}});var ba=m((u$,Mc)=>{"use strict";var ZS=bn(),ey=gn(),Dc=ZS("keys");Mc.exports=function(i){return Dc[i]||(Dc[i]=ey(i))}});var ga=m((l$,Oc)=>{"use strict";Oc.exports={}});var wn=m((c$,_c)=>{"use strict";var ty=Ml(),Vc=W(),ry=Be(),iy=wt(),En=Re(),xn=ha(),ay=ba(),sy=ga(),Bc="Object already initialized",Pn=Vc.TypeError,ny=Vc.WeakMap,va,_r,Sa,oy=function(i){return Sa(i)?_r(i):va(i,{})},uy=function(i){return function(e){var t;if(!ry(e)||(t=_r(e)).type!==i)throw Pn("Incompatible receiver, "+i+" required");return t}};ty||xn.state?(Le=xn.state||(xn.state=new ny),Le.get=Le.get,Le.has=Le.has,Le.set=Le.set,va=function(i,e){if(Le.has(i))throw Pn(Bc);return e.facade=i,Le.set(i,e),e},_r=function(i){return Le.get(i)||{}},Sa=function(i){return Le.has(i)}):(At=ay("state"),sy[At]=!0,va=function(i,e){if(En(i,At))throw Pn(Bc);return e.facade=i,iy(i,At,e),e},_r=function(i){return En(i,At)?i[At]:{}},Sa=function(i){return En(i,At)});var Le,At;_c.exports={set:va,get:_r,has:Sa,enforce:oy,getterFor:uy}});var An=m((d$,Uc)=>{"use strict";var ly=$r(),qc=Function.prototype,Nc=qc.apply,Fc=qc.call;Uc.exports=typeof Reflect=="object"&&Reflect.apply||(ly?Fc.bind(Nc):function(){return Fc.apply(Nc,arguments)})});var kn=m((p$,Hc)=>{"use strict";var cy=Jt(),dy=re();Hc.exports=function(i){if(cy(i)==="Function")return dy(i)}});var Wc=m(Yc=>{"use strict";var jc={}.propertyIsEnumerable,Gc=Object.getOwnPropertyDescriptor,py=Gc&&!jc.call({1:2},1);Yc.f=py?function(e){var t=Gc(this,e);return!!t&&t.enumerable}:jc});var Rn=m(zc=>{"use strict";var hy=Ve(),fy=ie(),my=Wc(),by=Vr(),gy=Zt(),vy=fa(),Sy=Re(),yy=an(),Qc=Object.getOwnPropertyDescriptor;zc.f=hy?Qc:function(e,t){if(e=gy(e),t=vy(t),yy)try{return Qc(e,t)}catch(r){}if(Sy(e,t))return by(!fy(my.f,e,t),e[t])}});var Ln=m((m$,Kc)=>{"use strict";var Ty=de(),Iy=q(),Ey=/#|\.prototype\./,Nr=function(i,e){var t=Py[xy(i)];return t==Ay?!0:t==wy?!1:Iy(e)?Ty(e):!!e},xy=Nr.normalize=function(i){return String(i).replace(Ey,".").toLowerCase()},Py=Nr.data={},wy=Nr.NATIVE="N",Ay=Nr.POLYFILL="P";Kc.exports=Nr});var Fr=m((b$,Xc)=>{"use strict";var Jc=kn(),ky=He(),Ry=$r(),Ly=Jc(Jc.bind);Xc.exports=function(i,e){return ky(i),e===void 0?i:Ry?Ly(i,e):function(){return i.apply(e,arguments)}}});var ge=m((g$,ed)=>{"use strict";var ya=W(),$y=An(),Cy=kn(),Dy=q(),My=Rn().f,Oy=Ln(),tr=da(),By=Fr(),rr=wt(),Zc=Re(),Vy=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 $y(i,this,arguments)};return e.prototype=i.prototype,e};ed.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?ya:a?ya[t]:(ya[t]||{}).prototype,o=r?tr:tr[t]||rr(tr,t,{})[t],u=o.prototype,l,c,d,p,f,h,b,v,S;for(p in e)l=Oy(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&Zc(n,p),h=o[p],c&&(i.dontCallGetSet?(S=My(n,p),b=S&&S.value):b=n[p]),f=c&&b?b:e[p],!(c&&typeof h==typeof f)&&(i.bind&&c?v=By(f,ya):i.wrap&&c?v=Vy(f):s&&Dy(f)?v=Cy(f):v=f,(i.sham||f&&f.sham||h&&h.sham)&&rr(v,"sham",!0),rr(o,p,v),s&&(d=t+"Prototype",Zc(tr,d)||rr(tr,d,{}),rr(tr[d],p,f),i.real&&u&&(l||!u[p])&&rr(u,p,f)))}});var id=m((v$,rd)=>{"use strict";var $n=Ve(),_y=Re(),td=Function.prototype,Ny=$n&&Object.getOwnPropertyDescriptor,Cn=_y(td,"name"),Fy=Cn&&function(){}.name==="something",qy=Cn&&(!$n||$n&&Ny(td,"name").configurable);rd.exports={EXISTS:Cn,PROPER:Fy,CONFIGURABLE:qy}});var sd=m((S$,ad)=>{"use strict";var Uy=Math.ceil,Hy=Math.floor;ad.exports=Math.trunc||function(e){var t=+e;return(t>0?Hy:Uy)(t)}});var Ta=m((y$,nd)=>{"use strict";var jy=sd();nd.exports=function(i){var e=+i;return e!==e||e===0?0:jy(e)}});var ud=m((T$,od)=>{"use strict";var Gy=Ta(),Yy=Math.max,Wy=Math.min;od.exports=function(i,e){var t=Gy(i);return t<0?Yy(t+e,0):Wy(t,e)}});var cd=m((I$,ld)=>{"use strict";var Qy=Ta(),zy=Math.min;ld.exports=function(i){return i>0?zy(Qy(i),9007199254740991):0}});var Ia=m((E$,dd)=>{"use strict";var Ky=cd();dd.exports=function(i){return Ky(i.length)}});var fd=m((x$,hd)=>{"use strict";var Jy=Zt(),Xy=ud(),Zy=Ia(),pd=function(i){return function(e,t,r){var a=Jy(e),s=Zy(a),n=Xy(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}};hd.exports={includes:pd(!0),indexOf:pd(!1)}});var gd=m((P$,bd)=>{"use strict";var eT=re(),Dn=Re(),tT=Zt(),rT=fd().indexOf,iT=ga(),md=eT([].push);bd.exports=function(i,e){var t=tT(i),r=0,a=[],s;for(s in t)!Dn(iT,s)&&Dn(t,s)&&md(a,s);for(;e.length>r;)Dn(t,s=e[r++])&&(~rT(a,s)||md(a,s));return a}});var Mn=m((w$,vd)=>{"use strict";vd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var yd=m((A$,Sd)=>{"use strict";var aT=gd(),sT=Mn();Sd.exports=Object.keys||function(e){return aT(e,sT)}});var Id=m(Td=>{"use strict";var nT=Ve(),oT=sn(),uT=Pt(),lT=we(),cT=Zt(),dT=yd();Td.f=nT&&!oT?Object.defineProperties:function(e,t){lT(e);for(var r=cT(t),a=dT(t),s=a.length,n=0,o;s>n;)uT.f(e,o=a[n++],r[o]);return e}});var On=m((R$,Ed)=>{"use strict";var pT=Ue();Ed.exports=pT("document","documentElement")});var Nn=m((L$,Ld)=>{"use strict";var hT=we(),fT=Id(),xd=Mn(),mT=ga(),bT=On(),gT=la(),vT=ba(),Pd=">",wd="<",Vn="prototype",_n="script",kd=vT("IE_PROTO"),Bn=function(){},Rd=function(i){return wd+_n+Pd+i+wd+"/"+_n+Pd},Ad=function(i){i.write(Rd("")),i.close();var e=i.parentWindow.Object;return i=null,e},ST=function(){var i=gT("iframe"),e="java"+_n+":",t;return i.style.display="none",bT.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Rd("document.F=Object")),t.close(),t.F},Ea,xa=function(){try{Ea=new ActiveXObject("htmlfile")}catch(e){}xa=typeof document!="undefined"?document.domain&&Ea?Ad(Ea):ST():Ad(Ea);for(var i=xd.length;i--;)delete xa[Vn][xd[i]];return xa()};mT[kd]=!0;Ld.exports=Object.create||function(e,t){var r;return e!==null?(Bn[Vn]=hT(e),r=new Bn,Bn[Vn]=null,r[kd]=e):r=xa(),t===void 0?r:fT.f(r,t)}});var Cd=m(($$,$d)=>{"use strict";var yT=de();$d.exports=!yT(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var qn=m((C$,Md)=>{"use strict";var TT=Re(),IT=q(),ET=Br(),xT=ba(),PT=Cd(),Dd=xT("IE_PROTO"),Fn=Object,wT=Fn.prototype;Md.exports=PT?Fn.getPrototypeOf:function(i){var e=ET(i);if(TT(e,Dd))return e[Dd];var t=e.constructor;return IT(t)&&e instanceof t?t.prototype:e instanceof Fn?wT:null}});var ir=m((D$,Od)=>{"use strict";var AT=wt();Od.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:AT(i,e,t),i}});var Gn=m((M$,_d)=>{"use strict";var kT=de(),RT=q(),LT=Be(),$T=Nn(),Bd=qn(),CT=ir(),DT=K(),MT=ke(),jn=DT("iterator"),Vd=!1,je,Un,Hn;[].keys&&(Hn=[].keys(),"next"in Hn?(Un=Bd(Bd(Hn)),Un!==Object.prototype&&(je=Un)):Vd=!0);var OT=!LT(je)||kT(function(){var i={};return je[jn].call(i)!==i});OT?je={}:MT&&(je=$T(je));RT(je[jn])||CT(je,jn,function(){return this});_d.exports={IteratorPrototype:je,BUGGY_SAFARI_ITERATORS:Vd}});var Pa=m((O$,Fd)=>{"use strict";var BT=K(),VT=BT("toStringTag"),Nd={};Nd[VT]="z";Fd.exports=String(Nd)==="[object z]"});var ar=m((B$,qd)=>{"use strict";var _T=Pa(),NT=q(),wa=Jt(),FT=K(),qT=FT("toStringTag"),UT=Object,HT=wa(function(){return arguments}())=="Arguments",jT=function(i,e){try{return i[e]}catch(t){}};qd.exports=_T?wa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=jT(e=UT(i),qT))=="string"?t:HT?wa(e):(r=wa(e))=="Object"&&NT(e.callee)?"Arguments":r}});var Hd=m((V$,Ud)=>{"use strict";var GT=Pa(),YT=ar();Ud.exports=GT?{}.toString:function(){return"[object "+YT(this)+"]"}});var Aa=m((_$,Gd)=>{"use strict";var WT=Pa(),QT=Pt().f,zT=wt(),KT=Re(),JT=Hd(),XT=K(),jd=XT("toStringTag");Gd.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;KT(a,jd)||QT(a,jd,{configurable:!0,value:e}),r&&!WT&&zT(a,"toString",JT)}}});var Wd=m((N$,Yd)=>{"use strict";var ZT=Gn().IteratorPrototype,eI=Nn(),tI=Vr(),rI=Aa(),iI=xt(),aI=function(){return this};Yd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=eI(ZT,{next:tI(+!r,t)}),rI(i,a,!1,!0),iI[a]=aI,i}});var zd=m((F$,Qd)=>{"use strict";var sI=re(),nI=He();Qd.exports=function(i,e,t){try{return sI(nI(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var Jd=m((q$,Kd)=>{"use strict";var oI=q(),uI=String,lI=TypeError;Kd.exports=function(i){if(typeof i=="object"||oI(i))return i;throw lI("Can't set "+uI(i)+" as a prototype")}});var Yn=m((U$,Xd)=>{"use strict";var cI=zd(),dI=we(),pI=Jd();Xd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=cI(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return dI(a),pI(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var lp=m((H$,up)=>{"use strict";var hI=ge(),fI=ie(),ka=ke(),np=id(),mI=q(),bI=Wd(),Zd=qn(),ep=Yn(),gI=Aa(),vI=wt(),Wn=ir(),SI=K(),tp=xt(),op=Gn(),yI=np.PROPER,TI=np.CONFIGURABLE,rp=op.IteratorPrototype,Ra=op.BUGGY_SAFARI_ITERATORS,qr=SI("iterator"),ip="keys",Ur="values",ap="entries",sp=function(){return this};up.exports=function(i,e,t,r,a,s,n){bI(t,e,r);var o=function(S){if(S===a&&p)return p;if(!Ra&&S in c)return c[S];switch(S){case ip:return function(){return new t(this,S)};case Ur:return function(){return new t(this,S)};case ap:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[qr]||c["@@iterator"]||a&&c[a],p=!Ra&&d||o(a),f=e=="Array"&&c.entries||d,h,b,v;if(f&&(h=Zd(f.call(new i)),h!==Object.prototype&&h.next&&(!ka&&Zd(h)!==rp&&(ep?ep(h,rp):mI(h[qr])||Wn(h,qr,sp)),gI(h,u,!0,!0),ka&&(tp[u]=sp))),yI&&a==Ur&&d&&d.name!==Ur&&(!ka&&TI?vI(c,"name",Ur):(l=!0,p=function(){return fI(d,this)})),a)if(b={values:o(Ur),keys:s?p:o(ip),entries:o(ap)},n)for(v in b)(Ra||l||!(v in c))&&Wn(c,v,b[v]);else hI({target:e,proto:!0,forced:Ra||l},b);return(!ka||n)&&c[qr]!==p&&Wn(c,qr,p,{name:a}),tp[e]=p,b}});var dp=m((j$,cp)=>{"use strict";cp.exports=function(i,e){return{value:i,done:e}}});var zn=m((G$,bp)=>{"use strict";var II=Zt(),Qn=Zs(),pp=xt(),fp=wn(),EI=Pt().f,xI=lp(),La=dp(),PI=ke(),wI=Ve(),mp="Array Iterator",AI=fp.set,kI=fp.getterFor(mp);bp.exports=xI(Array,"Array",function(i,e){AI(this,{type:mp,target:II(i),index:0,kind:e})},function(){var i=kI(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,La(void 0,!0)):t=="keys"?La(r,!1):t=="values"?La(e[r],!1):La([r,e[r]],!1)},"values");var hp=pp.Arguments=pp.Array;Qn("keys");Qn("values");Qn("entries");if(!PI&&wI&&hp.name!=="values")try{EI(hp,"name",{value:"values"})}catch(i){}});var vp=m((Y$,gp)=>{"use strict";var RI=K(),LI=xt(),$I=RI("iterator"),CI=Array.prototype;gp.exports=function(i){return i!==void 0&&(LI.Array===i||CI[$I]===i)}});var Kn=m((W$,yp)=>{"use strict";var DI=ar(),Sp=Or(),MI=Xt(),OI=xt(),BI=K(),VI=BI("iterator");yp.exports=function(i){if(!MI(i))return Sp(i,VI)||Sp(i,"@@iterator")||OI[DI(i)]}});var Ip=m((Q$,Tp)=>{"use strict";var _I=ie(),NI=He(),FI=we(),qI=Mr(),UI=Kn(),HI=TypeError;Tp.exports=function(i,e){var t=arguments.length<2?UI(i):e;if(NI(t))return FI(_I(t,i));throw HI(qI(i)+" is not iterable")}});var Pp=m((z$,xp)=>{"use strict";var jI=ie(),Ep=we(),GI=Or();xp.exports=function(i,e,t){var r,a;Ep(i);try{if(r=GI(i,"return"),!r){if(e==="throw")throw t;return t}r=jI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return Ep(r),t}});var Ca=m((K$,Rp)=>{"use strict";var YI=Fr(),WI=ie(),QI=we(),zI=Mr(),KI=vp(),JI=Ia(),wp=Cr(),XI=Ip(),ZI=Kn(),Ap=Pp(),eE=TypeError,$a=function(i,e){this.stopped=i,this.result=e},kp=$a.prototype;Rp.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),u=YI(e,r),l,c,d,p,f,h,b,v=function(g){return l&&Ap(l,"normal",g),new $a(!0,g)},S=function(g){return a?(QI(g),o?u(g[0],g[1],v):u(g[0],g[1])):o?u(g,v):u(g)};if(s)l=i.iterator;else if(n)l=i;else{if(c=ZI(i),!c)throw eE(zI(i)+" is not iterable");if(KI(c)){for(d=0,p=JI(i);p>d;d++)if(f=S(i[d]),f&&wp(kp,f))return f;return new $a(!1)}l=XI(i,c)}for(h=s?i.next:l.next;!(b=WI(h,l)).done;){try{f=S(b.value)}catch(g){Ap(l,"throw",g)}if(typeof f=="object"&&f&&wp(kp,f))return f}return new $a(!1)}});var $p=m((J$,Lp)=>{"use strict";var tE=fa(),rE=Pt(),iE=Vr();Lp.exports=function(i,e,t){var r=tE(e);r in i?rE.f(i,r,iE(0,t)):i[r]=t}});var Cp=m(()=>{"use strict";var aE=ge(),sE=Ca(),nE=$p();aE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return sE(e,function(r,a){nE(t,r,a)},{AS_ENTRIES:!0}),t}})});var Mp=m((eC,Dp)=>{"use strict";zn();Cp();var oE=da();Dp.exports=oE.Object.fromEntries});var Bp=m((tC,Op)=>{"use strict";Op.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 Np=m(()=>{"use strict";zn();var uE=Bp(),lE=W(),cE=ar(),dE=wt(),Vp=xt(),pE=K(),_p=pE("toStringTag");for(Da in uE)Jn=lE[Da],Ma=Jn&&Jn.prototype,Ma&&cE(Ma)!==_p&&dE(Ma,_p,Da),Vp[Da]=Vp.Array;var Jn,Ma,Da});var qp=m((aC,Fp)=>{"use strict";var hE=Mp();Np();Fp.exports=hE});var Oa=m((sC,Up)=>{"use strict";var fE=qp();Up.exports=fE});var Hp=m(()=>{"use strict"});var Hr=m((uC,jp)=>{"use strict";var mE=Jt();jp.exports=typeof process!="undefined"&&mE(process)=="process"});var Yp=m((lC,Gp)=>{"use strict";var bE=Pt();Gp.exports=function(i,e,t){return bE.f(i,e,t)}});var zp=m((cC,Qp)=>{"use strict";var gE=Ue(),vE=Yp(),SE=K(),yE=Ve(),Wp=SE("species");Qp.exports=function(i){var e=gE(i);yE&&e&&!e[Wp]&&vE(e,Wp,{configurable:!0,get:function(){return this}})}});var Jp=m((dC,Kp)=>{"use strict";var TE=Cr(),IE=TypeError;Kp.exports=function(i,e){if(TE(e,i))return i;throw IE("Incorrect invocation")}});var Zn=m((pC,Xp)=>{"use strict";var EE=re(),xE=q(),Xn=ha(),PE=EE(Function.toString);xE(Xn.inspectSource)||(Xn.inspectSource=function(i){return PE(i)});Xp.exports=Xn.inspectSource});var ah=m((hC,ih)=>{"use strict";var wE=re(),AE=de(),Zp=q(),kE=ar(),RE=Ue(),LE=Zn(),eh=function(){},$E=[],th=RE("Reflect","construct"),eo=/^\s*(?:class|function)\b/,CE=wE(eo.exec),DE=!eo.exec(eh),jr=function(e){if(!Zp(e))return!1;try{return th(eh,$E,e),!0}catch(t){return!1}},rh=function(e){if(!Zp(e))return!1;switch(kE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return DE||!!CE(eo,LE(e))}catch(t){return!0}};rh.sham=!0;ih.exports=!th||AE(function(){var i;return jr(jr.call)||!jr(Object)||!jr(function(){i=!0})||i})?rh:jr});var nh=m((fC,sh)=>{"use strict";var ME=ah(),OE=Mr(),BE=TypeError;sh.exports=function(i){if(ME(i))return i;throw BE(OE(i)+" is not a constructor")}});var to=m((mC,uh)=>{"use strict";var oh=we(),VE=nh(),_E=Xt(),NE=K(),FE=NE("species");uh.exports=function(i,e){var t=oh(i).constructor,r;return t===void 0||_E(r=oh(t)[FE])?e:VE(r)}});var ch=m((bC,lh)=>{"use strict";var qE=re();lh.exports=qE([].slice)});var ph=m((gC,dh)=>{"use strict";var UE=TypeError;dh.exports=function(i,e){if(i<e)throw UE("Not enough arguments");return i}});var ro=m((vC,hh)=>{"use strict";var HE=Dr();hh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(HE)});var po=m((SC,Ih)=>{"use strict";var pe=W(),jE=An(),GE=Fr(),fh=q(),YE=Re(),Th=de(),mh=On(),WE=ch(),bh=la(),QE=ph(),zE=ro(),KE=Hr(),uo=pe.setImmediate,lo=pe.clearImmediate,JE=pe.process,io=pe.Dispatch,XE=pe.Function,gh=pe.MessageChannel,ZE=pe.String,ao=0,Gr={},vh="onreadystatechange",Yr,kt,so,no;Th(function(){Yr=pe.location});var co=function(i){if(YE(Gr,i)){var e=Gr[i];delete Gr[i],e()}},oo=function(i){return function(){co(i)}},Sh=function(i){co(i.data)},yh=function(i){pe.postMessage(ZE(i),Yr.protocol+"//"+Yr.host)};(!uo||!lo)&&(uo=function(e){QE(arguments.length,1);var t=fh(e)?e:XE(e),r=WE(arguments,1);return Gr[++ao]=function(){jE(t,void 0,r)},kt(ao),ao},lo=function(e){delete Gr[e]},KE?kt=function(i){JE.nextTick(oo(i))}:io&&io.now?kt=function(i){io.now(oo(i))}:gh&&!zE?(so=new gh,no=so.port2,so.port1.onmessage=Sh,kt=GE(no.postMessage,no)):pe.addEventListener&&fh(pe.postMessage)&&!pe.importScripts&&Yr&&Yr.protocol!=="file:"&&!Th(yh)?(kt=yh,pe.addEventListener("message",Sh,!1)):vh in bh("script")?kt=function(i){mh.appendChild(bh("script"))[vh]=function(){mh.removeChild(this),co(i)}}:kt=function(i){setTimeout(oo(i),0)});Ih.exports={set:uo,clear:lo}});var ho=m((yC,xh)=>{"use strict";var Eh=function(){this.head=null,this.tail=null};Eh.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}}};xh.exports=Eh});var wh=m((TC,Ph)=>{"use strict";var ex=Dr();Ph.exports=/ipad|iphone|ipod/i.test(ex)&&typeof Pebble!="undefined"});var kh=m((IC,Ah)=>{"use strict";var tx=Dr();Ah.exports=/web0s(?!.*chrome)/i.test(tx)});var Bh=m((EC,Oh)=>{"use strict";var Rt=W(),Rh=Fr(),rx=Rn().f,fo=po().set,ix=ho(),ax=ro(),sx=wh(),nx=kh(),mo=Hr(),Lh=Rt.MutationObserver||Rt.WebKitMutationObserver,$h=Rt.document,Ch=Rt.process,Ba=Rt.Promise,Dh=rx(Rt,"queueMicrotask"),vo=Dh&&Dh.value,sr,bo,go,Va,Mh;vo||(Wr=new ix,Qr=function(){var i,e;for(mo&&(i=Ch.domain)&&i.exit();e=Wr.get();)try{e()}catch(t){throw Wr.head&&sr(),t}i&&i.enter()},!ax&&!mo&&!nx&&Lh&&$h?(bo=!0,go=$h.createTextNode(""),new Lh(Qr).observe(go,{characterData:!0}),sr=function(){go.data=bo=!bo}):!sx&&Ba&&Ba.resolve?(Va=Ba.resolve(void 0),Va.constructor=Ba,Mh=Rh(Va.then,Va),sr=function(){Mh(Qr)}):mo?sr=function(){Ch.nextTick(Qr)}:(fo=Rh(fo,Rt),sr=function(){fo(Qr)}),vo=function(i){Wr.head||sr(),Wr.add(i)});var Wr,Qr;Oh.exports=vo});var _h=m((xC,Vh)=>{"use strict";Vh.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var _a=m((PC,Nh)=>{"use strict";Nh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Lt=m((wC,Fh)=>{"use strict";var ox=W();Fh.exports=ox.Promise});var So=m((AC,qh)=>{"use strict";qh.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var Hh=m((kC,Uh)=>{"use strict";var ux=So(),lx=Hr();Uh.exports=!ux&&!lx&&typeof window=="object"&&typeof document=="object"});var nr=m((RC,Yh)=>{"use strict";var cx=W(),zr=Lt(),dx=q(),px=Ln(),hx=Zn(),fx=K(),mx=Hh(),bx=So(),gx=ke(),yo=ln(),jh=zr&&zr.prototype,vx=fx("species"),To=!1,Gh=dx(cx.PromiseRejectionEvent),Sx=px("Promise",function(){var i=hx(zr),e=i!==String(zr);if(!e&&yo===66||gx&&!(jh.catch&&jh.finally))return!0;if(!yo||yo<51||!/native code/.test(i)){var t=new zr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[vx]=r,To=t.then(function(){})instanceof r,!To)return!0}return!e&&(mx||bx)&&!Gh});Yh.exports={CONSTRUCTOR:Sx,REJECTION_EVENT:Gh,SUBCLASSING:To}});var or=m((LC,Qh)=>{"use strict";var Wh=He(),yx=TypeError,Tx=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw yx("Bad Promise constructor");e=r,t=a}),this.resolve=Wh(e),this.reject=Wh(t)};Qh.exports.f=function(i){return new Tx(i)}});var ff=m(()=>{"use strict";var Ix=ge(),Ex=ke(),Ua=Hr(),st=W(),dr=ie(),zh=ir(),Kh=Yn(),xx=Aa(),Px=zp(),wx=He(),qa=q(),Ax=Be(),kx=Jp(),Rx=to(),tf=po().set,wo=Bh(),Lx=_h(),$x=_a(),Cx=ho(),rf=wn(),Ha=Lt(),Ao=nr(),af=or(),ja="Promise",sf=Ao.CONSTRUCTOR,Dx=Ao.REJECTION_EVENT,Mx=Ao.SUBCLASSING,Io=rf.getterFor(ja),Ox=rf.set,ur=Ha&&Ha.prototype,$t=Ha,Na=ur,nf=st.TypeError,Eo=st.document,ko=st.process,xo=af.f,Bx=xo,Vx=!!(Eo&&Eo.createEvent&&st.dispatchEvent),of="unhandledrejection",_x="rejectionhandled",Jh=0,uf=1,Nx=2,Ro=1,lf=2,Fa,Xh,Fx,Zh,cf=function(i){var e;return Ax(i)&&qa(e=i.then)?e:!1},df=function(i,e){var t=e.value,r=e.state==uf,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===lf&&Ux(e),e.rejection=Ro),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(nf("Promise-chain cycle")):(l=cf(u))?dr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},pf=function(i,e){i.notified||(i.notified=!0,wo(function(){for(var t=i.reactions,r;r=t.get();)df(r,i);i.notified=!1,e&&!i.rejection&&qx(i)}))},hf=function(i,e,t){var r,a;Vx?(r=Eo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),st.dispatchEvent(r)):r={promise:e,reason:t},!Dx&&(a=st["on"+i])?a(r):i===of&&Lx("Unhandled promise rejection",t)},qx=function(i){dr(tf,st,function(){var e=i.facade,t=i.value,r=ef(i),a;if(r&&(a=$x(function(){Ua?ko.emit("unhandledRejection",t,e):hf(of,e,t)}),i.rejection=Ua||ef(i)?lf:Ro,a.error))throw a.value})},ef=function(i){return i.rejection!==Ro&&!i.parent},Ux=function(i){dr(tf,st,function(){var e=i.facade;Ua?ko.emit("rejectionHandled",e):hf(_x,e,i.value)})},lr=function(i,e,t){return function(r){i(e,r,t)}},cr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Nx,pf(i,!0))},Po=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw nf("Promise can't be resolved itself");var r=cf(e);r?wo(function(){var a={done:!1};try{dr(r,e,lr(Po,a,i),lr(cr,a,i))}catch(s){cr(a,s,i)}}):(i.value=e,i.state=uf,pf(i,!1))}catch(a){cr({done:!1},a,i)}}};if(sf&&($t=function(e){kx(this,Na),wx(e),dr(Fa,this);var t=Io(this);try{e(lr(Po,t),lr(cr,t))}catch(r){cr(t,r)}},Na=$t.prototype,Fa=function(e){Ox(this,{type:ja,done:!1,notified:!1,parent:!1,reactions:new Cx,rejection:!1,state:Jh,value:void 0})},Fa.prototype=zh(Na,"then",function(e,t){var r=Io(this),a=xo(Rx(this,$t));return r.parent=!0,a.ok=qa(e)?e:!0,a.fail=qa(t)&&t,a.domain=Ua?ko.domain:void 0,r.state==Jh?r.reactions.add(a):wo(function(){df(a,r)}),a.promise}),Xh=function(){var i=new Fa,e=Io(i);this.promise=i,this.resolve=lr(Po,e),this.reject=lr(cr,e)},af.f=xo=function(i){return i===$t||i===Fx?new Xh(i):Bx(i)},!Ex&&qa(Ha)&&ur!==Object.prototype)){Zh=ur.then,Mx||zh(ur,"then",function(e,t){var r=this;return new $t(function(a,s){dr(Zh,r,a,s)}).then(e,t)},{unsafe:!0});try{delete ur.constructor}catch(i){}Kh&&Kh(ur,Na)}Ix({global:!0,constructor:!0,wrap:!0,forced:sf},{Promise:$t});xx($t,ja,!1,!0);Px(ja)});var Sf=m((DC,vf)=>{"use strict";var Hx=K(),bf=Hx("iterator"),gf=!1;try{mf=0,Lo={next:function(){return{done:!!mf++}},return:function(){gf=!0}},Lo[bf]=function(){return this},Array.from(Lo,function(){throw 2})}catch(i){}var mf,Lo;vf.exports=function(i,e){if(!e&&!gf)return!1;var t=!1;try{var r={};r[bf]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var $o=m((MC,yf)=>{"use strict";var jx=Lt(),Gx=Sf(),Yx=nr().CONSTRUCTOR;yf.exports=Yx||!Gx(function(i){jx.all(i).then(void 0,function(){})})});var Tf=m(()=>{"use strict";var Wx=ge(),Qx=ie(),zx=He(),Kx=or(),Jx=_a(),Xx=Ca(),Zx=$o();Wx({target:"Promise",stat:!0,forced:Zx},{all:function(e){var t=this,r=Kx.f(t),a=r.resolve,s=r.reject,n=Jx(function(){var o=zx(t.resolve),u=[],l=0,c=1;Xx(e,function(d){var p=l++,f=!1;c++,Qx(o,t,d).then(function(h){f||(f=!0,u[p]=h,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var Ef=m(()=>{"use strict";var eP=ge(),tP=ke(),rP=nr().CONSTRUCTOR,Do=Lt(),iP=Ue(),aP=q(),sP=ir(),If=Do&&Do.prototype;eP({target:"Promise",proto:!0,forced:rP,real:!0},{catch:function(i){return this.then(void 0,i)}});!tP&&aP(Do)&&(Co=iP("Promise").prototype.catch,If.catch!==Co&&sP(If,"catch",Co,{unsafe:!0}));var Co});var xf=m(()=>{"use strict";var nP=ge(),oP=ie(),uP=He(),lP=or(),cP=_a(),dP=Ca(),pP=$o();nP({target:"Promise",stat:!0,forced:pP},{race:function(e){var t=this,r=lP.f(t),a=r.reject,s=cP(function(){var n=uP(t.resolve);dP(e,function(o){oP(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Pf=m(()=>{"use strict";var hP=ge(),fP=ie(),mP=or(),bP=nr().CONSTRUCTOR;hP({target:"Promise",stat:!0,forced:bP},{reject:function(e){var t=mP.f(this);return fP(t.reject,void 0,e),t.promise}})});var Mo=m((HC,wf)=>{"use strict";var gP=we(),vP=Be(),SP=or();wf.exports=function(i,e){if(gP(i),vP(e)&&e.constructor===i)return e;var t=SP.f(i),r=t.resolve;return r(e),t.promise}});var Rf=m(()=>{"use strict";var yP=ge(),TP=Ue(),Af=ke(),IP=Lt(),kf=nr().CONSTRUCTOR,EP=Mo(),xP=TP("Promise"),PP=Af&&!kf;yP({target:"Promise",stat:!0,forced:Af||kf},{resolve:function(e){return EP(PP&&this===xP?IP:this,e)}})});var Lf=m(()=>{"use strict";ff();Tf();Ef();xf();Pf();Rf()});var Mf=m(()=>{"use strict";var wP=ge(),AP=ke(),Ga=Lt(),kP=de(),Cf=Ue(),Df=q(),RP=to(),$f=Mo(),LP=ir(),Bo=Ga&&Ga.prototype,$P=!!Ga&&kP(function(){Bo.finally.call({then:function(){}},function(){})});wP({target:"Promise",proto:!0,real:!0,forced:$P},{finally:function(i){var e=RP(this,Cf("Promise")),t=Df(i);return this.then(t?function(r){return $f(e,i()).then(function(){return r})}:i,t?function(r){return $f(e,i()).then(function(){throw r})}:i)}});!AP&&Df(Ga)&&(Oo=Cf("Promise").prototype.finally,Bo.finally!==Oo&&LP(Bo,"finally",Oo,{unsafe:!0}));var Oo});var Ya=m((KC,Of)=>{"use strict";var CP=Ue();Of.exports=CP});var Vf=m((JC,Bf)=>{"use strict";Hp();Lf();Mf();var DP=Ya();Bf.exports=DP("Promise","finally")});var Nf=m((XC,_f)=>{"use strict";var MP=Vf();_f.exports=MP});var Wa=m((ZC,Ff)=>{"use strict";var OP=Nf();Ff.exports=OP});var cm=m(()=>{"use strict";var ow=ge(),uw=Br(),lw=Ia(),cw=Ta(),dw=Zs();ow({target:"Array",proto:!0},{at:function(e){var t=uw(this),r=lw(t),a=cw(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});dw("at")});var pm=m((uM,dm)=>{"use strict";cm();var pw=Ya();dm.exports=pw("Array","at")});var fm=m((lM,hm)=>{"use strict";var hw=pm();hm.exports=hw});var Ka=m((cM,mm)=>{"use strict";var fw=fm();mm.exports=fw});var Wm=m(()=>{"use strict"});var Qm=m(()=>{"use strict"});var Km=m((KB,zm)=>{"use strict";var SA=Be(),yA=Jt(),TA=K(),IA=TA("match");zm.exports=function(i){var e;return SA(i)&&((e=i[IA])!==void 0?!!e:yA(i)=="RegExp")}});var Xm=m((JB,Jm)=>{"use strict";var EA=ar(),xA=String;Jm.exports=function(i){if(EA(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return xA(i)}});var eb=m((XB,Zm)=>{"use strict";var PA=we();Zm.exports=function(){var i=PA(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 ib=m((ZB,rb)=>{"use strict";var wA=ie(),AA=Re(),kA=Cr(),RA=eb(),tb=RegExp.prototype;rb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in tb)&&!AA(i,"flags")&&kA(tb,i)?wA(RA,i):e}});var sb=m((eV,ab)=>{"use strict";var lu=re(),LA=Br(),$A=Math.floor,ou=lu("".charAt),CA=lu("".replace),uu=lu("".slice),DA=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,MA=/\$([$&'`]|\d{1,2})/g;ab.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=MA;return a!==void 0&&(a=LA(a),u=DA),CA(s,u,function(l,c){var d;switch(ou(c,0)){case"$":return"$";case"&":return i;case"`":return uu(e,0,t);case"'":return uu(e,n);case"<":d=a[uu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var f=$A(p/10);return f===0?l:f<=o?r[f-1]===void 0?ou(c,1):r[f-1]+ou(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var cb=m(()=>{"use strict";var OA=ge(),BA=ie(),cu=re(),nb=oa(),VA=q(),_A=Xt(),NA=Km(),vr=Xm(),FA=Or(),qA=ib(),UA=sb(),HA=K(),jA=ke(),GA=HA("replace"),YA=TypeError,lb=cu("".indexOf),WA=cu("".replace),ob=cu("".slice),QA=Math.max,ub=function(i,e,t){return t>i.length?-1:e===""?t:lb(i,e,t)};OA({target:"String",proto:!0},{replaceAll:function(e,t){var r=nb(this),a,s,n,o,u,l,c,d,p,f=0,h=0,b="";if(!_A(e)){if(a=NA(e),a&&(s=vr(nb(qA(e))),!~lb(s,"g")))throw YA("`.replaceAll` does not allow non-global regexes");if(n=FA(e,GA),n)return BA(n,e,r,t);if(jA&&a)return WA(vr(r),e,t)}for(o=vr(r),u=vr(e),l=VA(t),l||(t=vr(t)),c=u.length,d=QA(1,c),f=ub(o,u,0);f!==-1;)p=l?vr(t(u,f,o)):UA(u,o,f,[],void 0,t),b+=ob(o,h,f)+p,h=f+c,f=ub(o,u,f+d);return h<o.length&&(b+=ob(o,h)),b}})});var pb=m((iV,db)=>{"use strict";Wm();Qm();cb();var zA=Ya();db.exports=zA("String","replaceAll")});var fb=m((aV,hb)=>{"use strict";var KA=pb();hb.exports=KA});var bb=m((sV,mb)=>{"use strict";var JA=fb();mb.exports=JA});var nl="__VERSION__";var ce=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ce||{}),Et=(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))(Et||{});var aa=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(aa||{}),Ws=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ws||{});var Qs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Qs||{});import{assertNever as pl,assertNonNullable as gv,isNonNullable as sa,ValueSubject as zs,Subject as vv,Subscription as Sv,merge as yv,observableFrom as Tv,fromEvent as ul,map as ll,tap as cl,filterChanged as Iv,isNullable as Ks,ErrorCategory as dl}from"@vkontakte/videoplayer-shared";var ol=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 na=class{constructor(e){this.connection$=new zs(void 0);this.castState$=new zs("NOT_AVAILABLE");this.errorEvent$=new vv;this.realCastState$=new zs("NOT_AVAILABLE");this.subscription=new Sv;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=sa((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||ol("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:dl.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,a,s;(s=(a=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:a.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){sa(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(ul(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var s,n;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.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 pl(a.sessionState)}})).add(yv(ul(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(cl(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),ll(a=>a.castState)),Tv([r.getCastState()])).pipe(Iv(),ll(Ev),cl(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=sa(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();gv(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(Ks(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?sa(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){var a;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(a=this.params.receiverApplicationId)!=null?a:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:dl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Ev=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 pl(i)}};var Dg=Oe(Oa(),1);var Kf=Oe(Wa(),1);import{assertNever as qf}from"@vkontakte/videoplayer-shared";var J=(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:qf(t)}return i},Vo=(i,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:qf(e)}};var T=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as BP,Subject as Qa,merge as Uf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Qa;this.transitionEnded$=new Qa;this.transitionUpdated$=new Qa;this.forceChanged$=new Qa;this.stateChangeStarted$=Uf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Uf(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||BP(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 VP}from"@vkontakte/videoplayer-shared";var Hf=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 VP(i)}};import{assertNever as pr,assertNonNullable as Ct,debounce as jf,ErrorCategory as Gf,fromEvent as Dt,isNonNullable as Yf,map as Wf,merge as Qf,observableFrom as _P,Subject as NP,Subscription as _o,timeout as FP,getHighestQuality as qP}from"@vkontakte/videoplayer-shared";var UP=5,HP=5,jP=500,zf=7e3,Kr=class{constructor(e){this.subscription=new _o;this.loadMediaTimeoutSubscription=new _o;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==null?void 0: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:pr(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:pr(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:pr(e)}break}default:pr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Hf(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 _o;this.subscription.add(e),this.subscription.add(Qf(this.videoState.stateChangeStarted$.pipe(Wf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Wf(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 NP;e.add(a.pipe(jf(jP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Dt(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)>UP)&&a.next(o),s=o})),e.add(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Dt(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(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<HP&&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:pr(n)}}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Dt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Qf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_P(["init"])).pipe(jf(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(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&T(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var a,s;let t=this.params.output.volume$.getValue(),r={volume:(a=e.volume)!=null?a:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,a,s;switch(e){case"MPEG":{let c=t[e];Ct(c);let d=qP(Object.keys(c));Ct(d);let p=c[d];Ct(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Ct(c),r=c.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 c=t[e];Ct(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Ct(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Ct(c),r=J(c.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Gf.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return pr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Yf(o)&&(n.metadata.title=o),Yf(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(FP(zf).subscribe(()=>s(`timeout(${zf})`)))});(0,Kf.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:Gf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Jr=i=>{i.removeAttribute("src"),i.load()};var Jf=i=>{try{i.pause(),i.playbackRate=0,Jr(i),i.remove()}catch(e){console.error(e)}};var No=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)}},Fo=window.WeakMap?new WeakMap:new No,ae=i=>{let e=i.querySelector("video"),t=!!e;return e?Jr(e):(e=document.createElement("video"),i.appendChild(e)),Fo.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},se=i=>{let e=Fo.get(i);Fo.delete(i),e?Jr(i):Jf(i)};import{assertNonNullable as Xr,isNonNullable as Ne,isNullable as WP,fromEvent as hr,merge as Xf,observableFrom as Zf,filterChanged as em,map as Zr,Subject as tm,Subscription as QP,ValueSubject as zP,ErrorCategory as KP}from"@vkontakte/videoplayer-shared";import{isNonNullable as qo,isNullable as GP,Subscription as YP}from"@vkontakte/videoplayer-shared";var za=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=GP(a),l=new YP;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},_e=(i,e,t)=>za(e,()=>i.loop,r=>{qo(r)&&(i.loop=r)},{onError:t}),ne=(i,e,t,r)=>za(e,()=>({muted:i.muted,volume:i.volume}),a=>{qo(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||(a==null?void 0:a.muted)===(s==null?void 0:s.muted)&&(a==null?void 0:a.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),ve=(i,e,t,r)=>za(e,()=>i.playbackRate,a=>{qo(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),nt=za;var JP=i=>["__",i.language,i.label].join("|"),XP=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Uo=class i{constructor(){this.available$=new tm;this.current$=new zP(void 0);this.error$=new tm;this.subscription=new QP;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:KP.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(nt(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},u)=>o===n[u].id),changed$:this.available$.pipe(Zr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(nt(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},u)=>o===n[u].id),changed$:this.available$.pipe(Zr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(nt(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(nt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Xr(this.video);let{textTracks:e}=this.video;this.subscription.add(hr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Xf(hr(e,"addtrack"),hr(e,"removetrack"),Zf(["init"])).pipe(Zr(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),em((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Xf(hr(e,"change"),Zf(["init"])).pipe(Zr(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Zr(r=>r&&this.htmlTextTrackToITextTrack(r).id),em()).subscribe(this.current$));let t=r=>{var a,s;return this.applyCueSettings((s=(a=r.target)==null?void 0:a.activeCues)!=null?s:null)};this.subscription.add(hr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let a=o=>{var l,c,d,p,f;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(f=o.target)==null||f.removeEventListener("cuechange",a))};(n=r.track)==null||n.addEventListener("cuechange",a)})),this.subscription.add(hr(e,"removetrack").subscribe(r=>{var a;(a=r.track)==null||a.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){Xr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,a=e.id?e.id:JP(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(a))==null?void 0:o.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(a))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language: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){Xr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(WP(e)||!XP(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){Xr(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){Xr(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)}},Se=Uo;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 rm=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Ho=i=>{let e=rm(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},im=i=>{let e=rm(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as ye,map as ot,merge as sm,filterChanged as ew,isNonNullable as nm,Subject as tw,filter as om,mapTo as um,combine as rw,once as iw,ErrorCategory as aw,ValueSubject as lm,getCurrentBrowser as sw,CurrentClientBrowser as nw}from"@vkontakte/videoplayer-shared";var ZP=3,am=(i,e,t=ZP)=>{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 u=s-1;u>=0;u--)i.end(u)+t>=r&&(r=i.start(u));for(let u=s+1;u<i.length;u++)i.start(u)-t<=a&&(a=i.end(u))}}return{from:r,to:a}};var oe=i=>{let e=I=>ye(i,I).pipe(um(void 0)),r=sm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>ye(i,I))).pipe(ot(I=>I.type==="ended"?i.readyState<2:i.readyState<3),ew()),a=sm(ye(i,"progress"),ye(i,"timeupdate")).pipe(ot(()=>am(i.buffered,i.currentTime))),n=sw().browser===nw.Safari?rw({play:e("play").pipe(iw()),playing:e("playing")}).pipe(um(void 0)):e("playing"),o=ye(i,"volumechange").pipe(ot(()=>({muted:i.muted,volume:i.volume}))),u=ye(i,"ratechange").pipe(ot(()=>i.playbackRate)),l=ye(i,"error").pipe(om(()=>!!(i.error||i.played.length)),ot(()=>{var y;let I=i.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:aw.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(y=i.error)!=null?y:void 0}})),c=ye(i,"timeupdate").pipe(ot(()=>i.currentTime)),d=new tw,p=.3,f;c.subscribe(I=>{i.loop&&nm(f)&&nm(I)&&f>=i.duration-p&&I<=p&&d.next(f),f=I});let h=ye(i,"enterpictureinpicture"),b=ye(i,"leavepictureinpicture"),v=new lm(im(i));h.subscribe(()=>v.next(!0)),b.subscribe(()=>v.next(!1));let S=new lm(Ho(i));return ye(i,"fullscreenchange").pipe(ot(()=>Ho(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(om(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:ye(i,"durationchange").pipe(ot(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:u,inPiP$:v,inFullscreen$:S}};import{VideoQuality as ut}from"@vkontakte/videoplayer-shared";var lt=i=>{switch(i){case"mobile":return ut.Q_144P;case"lowest":return ut.Q_240P;case"low":return ut.Q_360P;case"sd":case"medium":return ut.Q_480P;case"hd":case"high":return ut.Q_720P;case"fullhd":case"full":return ut.Q_1080P;case"quadhd":case"quad":return ut.Q_1440P;case"ultrahd":case"ultra":return ut.Q_2160P}};var Qo=Oe(Ka(),1);import{isNonNullable as ct,isNullable as Go,now as Tm,isHigher as Yo,isHigherOrEqual as Sm,isInvariantQuality as ym,isLower as Wo,isLowerOrEqual as mw,videoSizeToQuality as bw,assertNotEmptyArray as gw}from"@vkontakte/videoplayer-shared";var jo=!1,We={},bm=i=>{jo=i},gm=()=>{We={}},vm=i=>{i(We)},ei=(i,e)=>{var t;jo&&(We.meta=(t=We.meta)!=null?t:{},We.meta[i]=e)},Z=class{constructor(e){this.name=e}next(e){var r,a;if(!jo)return;We.series=(r=We.series)!=null?r:{};let t=(a=We.series[this.name])!=null?a:[];t.push([Date.now(),e]),We.series[this.name]=t}};var vw=new Z("best_bitrate"),Sw=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Ja=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Tm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},yw='Assertion "ABR Tracks is empty array" failed',Tw=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var $,C,w,U,ee;gw(i,yw);let p=r.usePixelRatio&&($=window.devicePixelRatio)!=null?$:1,f=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},h=f&&bw(f),b=r.considerPlaybackRate&&ct(o)?o:1,v=i.filter(A=>!ym(A.quality)).sort((A,x)=>Yo(A.quality,x.quality)?-1:1),S=(C=(0,Qo.default)(v,-1))==null?void 0:C.quality,g=(w=(0,Qo.default)(v,0))==null?void 0:w.quality,I=Go(a)||ct(a.min)&&ct(a.max)&&Wo(a.max,a.min)||ct(a.min)&&g&&Yo(a.min,g)||ct(a.max)&&S&&Wo(a.max,S),y=b*Sw(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),E={},R=v.filter(A=>(h?Wo(A.quality,h):!0)?(ct(t)&&isFinite(t)&&ct(A.bitrate)?t-s>=A.bitrate*y:!0)?r.lazyQualitySwitch&&ct(r.minBufferToSwitchUp)&&u&&!ym(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Yo(A.quality,u.quality)?(E[A.quality]="Buffer",!1):!!c&&Sm(A.quality,c)?(E[A.quality]="DroppedFramesLimit",!1):I||(Go(a.max)||mw(A.quality,a.max))&&(Go(a.min)||Sm(A.quality,a.min))?!0:(E[A.quality]="FitsQualityLimits",!1):(E[A.quality]="FitsThroughput",!1):(E[A.quality]="FitsContainer",!1))[0];R&&R.bitrate&&vw.next(R.bitrate);let k=(U=R!=null?R:v[Math.ceil((v.length-1)/2)])!=null?U:i[0];k.quality!==((ee=l==null?void 0:l.last)==null?void 0:ee.quality)&&d({message:`
7
7
  [available tracks]
8
- ${i.map(w=>`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate} }`).join(`
8
+ ${i.map(A=>`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate} }`).join(`
9
9
  `)}
10
10
 
11
11
  [tuning]
12
- ${Object.entries(r!=null?r:{}).map(([w,x])=>`${w}: ${x}`).join(`
12
+ ${Object.entries(r!=null?r:{}).map(([A,x])=>`${A}: ${x}`).join(`
13
13
  `)}
14
14
 
15
15
  [limit params]
@@ -27,14 +27,14 @@ var ov=Object.create;var tl=Object.defineProperty;var uv=Object.getOwnPropertyDe
27
27
  minQualityLimit: ${a==null?void 0:a.min},
28
28
 
29
29
  [limited tracks]
30
- ${Object.entries(E).map(([w,x])=>`${w}: ${x}`).join(`
30
+ ${Object.entries(E).map(([A,x])=>`${A}: ${x}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
33
  [best track] ${R==null?void 0:R.quality}
34
- [selected track] ${A==null?void 0:A.quality}
35
- `});let N=A&&u&&u.history[A.id]&&gm()-u.history[A.id]<=r.trackCooldown&&(!u.last||A.id!==u.last.id);if(A!=null&&A.id&&u&&!N&&u.recordSelection(A),N&&(u!=null&&u.last)){let w=u.last;return u==null||u.recordSwitch(w),d({message:`
36
- [last selected] ${w==null?void 0:w.quality}
37
- `}),w}return u==null||u.recordSwitch(A),A},dt=gk;var Q=i=>new URL(i).hostname;import{assertNever as Em,assertNonNullable as xm,combine as Vk,debounce as _k,ErrorCategory as Pm,filter as Nk,filterChanged as Fk,isNonNullable as Ko,map as es,merge as km,observableFrom as qk,Subscription as Uk,ValueSubject as Jo,videoQualityToHeight as Hk,videoSizeToQuality as jk}from"@vkontakte/videoplayer-shared";var vm=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"))},ue=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!vm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return vm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Ja,isNullable as yk,assertNonNullable as ri}from"@vkontakte/videoplayer-shared";import{isNonNullable as Sm,assertNonNullable as Ka,now as vk}from"@vkontakte/videoplayer-shared";function z(){return vk()}function Yo(i){return z()-i}function Wo(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 ym(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function fr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,p=!1,f="arraybuffer",h=7e3,b=2e3,v=()=>{if(l)return;Ka(c);let k=Yo(c),U;if(k<b){U=b-k,setTimeout(v,U);return}b*=2,b>h&&(b=h),n&&n.abort(),n=new a,M()},S=k=>(s=k,C),g=k=>(d=k,C),I=()=>(f="json",C),y=()=>{if(!l){if(--u>=0){v(),r&&r();return}l=!0,d&&d(),t&&t()}},E=k=>(p=k,C),M=()=>{c=z(),n=new a,n.open("get",i);let k=0,U,ee=0,w=()=>(Ka(c),Math.max(c,Math.max(U||0,ee||0)));if(s&&n.addEventListener("progress",x=>{let _=z();s.updateChunk&&x.loaded>k&&(s.updateChunk(w(),x.loaded-k),k=x.loaded,U=_)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(l)return;Ka(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let _=n.response.byteLength-k;_&&s.updateChunk&&s.updateChunk(w(),_)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{Ka(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ee=z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=f,n.send(),C},C={withBitrateReporting:S,withParallel:E,withJSONResponse:I,withRetryCount:k=>(u=k,C),withRetryInterval:(k,U)=>(Sm(k)&&(b=k),Sm(U)&&(h=U),C),withTimeout:k=>(o=k,C),withFinally:g,send:M,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return C}var ei=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 ti=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=z(),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=z()-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=fr(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=z()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=z();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,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 Xa=1e4,Qo=3;var Tk=6e4,Ik=10,Ek=1,xk=500,ii=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 ei(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Wo(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=Wo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(a=e.error)==null?void 0:a.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||Ja(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=()=>{ym(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 ti(Qo,Xa,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},p=(y,E,M)=>{l&&l.abort(),l=fr(this.urlResolver.resolve(y,!1),E,M,()=>this._retryCallback()).withTimeout(Xa).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Qo).withFinally(()=>{l=null}).send()},f=(y,E,M)=>{ri(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),E,M,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=y=>{let E=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${E}=>${y}`),r.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let M=z()-1e4,R=0;for(let N=0;N<this.bufferStates.length;N++){let $=this.bufferStates[N];y=Math.min(y,$.buf),$.ts<M&&R++}this.bufferStates.splice(0,R),t(`update playback rate; minBuffer=${y} drop=${R} jitter=${this.sourceJitter}`);let A=y-Ek;this.sourceJitter>=0?A-=this.sourceJitter/2:this.sourceJitter-=1,A>3?h(1.15):A>1?h(1.1):A>.3?h(1.05):h(1)}},S=y=>{let E,M=()=>E&&E.start?E.start.length:0,R=x=>E.start[x]/1e3,A=x=>E.dur[x]/1e3,N=x=>E.fragIndex+x,$=(x,_)=>({chunkIdx:N(x),startTS:R(x),dur:A(x),discontinuity:_}),C=()=>{let x=0;if(E&&E.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=_;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let X=E.dur.length-1;for(;X>=0&&(Y-=E.dur[X],!(Y<=0));--X);x=Math.min(X,E.dur.length-1-H),x=Math.max(x,0)}return $(x,!0)},k=x=>{let _=M();if(!(_<=0)){if(Ja(x)){for(let H=0;H<_;H++)if(R(H)>x)return $(H)}return C()}},U=x=>{let _=M(),H=x?x.chunkIdx+1:0,Y=H-E.fragIndex;if(!(_<=0)){if(!x||Y<0||Y-_>Ik)return t(`Resync: offset=${Y} bChunks=${_} chunk=`+JSON.stringify(x)),C();if(!(Y>=_))return $(H-E.fragIndex,!1)}},ee=(x,_,H)=>{u&&u.abort(),u=fr(this.urlResolver.resolve(x,!0,this.lowLatency),_,H,()=>this._retryCallback()).withTimeout(Xa).withRetryCount(Qo).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(x,_)=>{ee(y,H=>{if(!d())return;E=H;let Y=!!E.lowLatency;Y!==this.lowLatency&&b(Y);let X=0;for(let qe=0;qe<E.dur.length;++qe)X+=E.dur[qe];X>0&&(ri(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(X/E.dur.length)),a({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,x(k(_))},()=>this._handleNetworkError())},nextChunk:U}},g=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),ri(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:E,logger:M}=this.params,R=S(e.jidxUrl),A,N,$,C,k=0,U,ee,w,x=()=>{U&&(clearTimeout(U),U=void 0);let B=Math.max(xk,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),te=k+B,le=z(),me=Math.min(1e4,te-le);k=le;let tt=()=>{u||d()&&R.seek(()=>{d()&&(k=z(),_(),x())})};me>0?U=window.setTimeout(()=>{this.paused?x():tt()},me):tt()},_=()=>{let B;for(;B=R.nextChunk(C);)C=B,Qi(B);let te=R.nextChunk($);if(te){if($&&te.discontinuity){M("Detected discontinuity; restarting playback"),this.paused?x():(g(),this._initPlayerWith(e));return}qe(te)}else x()},H=(B,te)=>{if(!d()||!this.sourceBuffer)return;let le,me,tt,Yt=rt=>{window.setTimeout(()=>{d()&&H(B,te)},rt)};if(this.sourceBuffer.updating)M("Source buffer is updating; delaying appendBuffer"),Yt(100);else{let rt=z(),vt=E.currentTime;!this.paused&&E.buffered.length>1&&ee===vt&&rt-w>500&&(M("Stall suspected; trying to fix"),this._fixupStall()),ee!==vt&&(ee=vt,w=rt);let Wt=this._getBufferSizeSec();if(Wt>30)M(`Buffered ${Wt} seconds; delaying appendBuffer`),Yt(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:rt,buf:Wt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),te&&te()}catch(wr){if(wr.name==="QuotaExceededError")M("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(le=this.sourceBuffer.buffered.start(0),me=vt,me-le>4&&this.sourceBuffer.remove(le,me-3)),Yt(1e3);else throw wr}}},Y=()=>{N&&A&&(M([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify($)]),H(N,function(){N=null,_()}))},X=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),qe=B=>{d()&&f(X(B),(te,le)=>{if(d()){if(le/=1e3,N=te,$=B,n=B.startTS,le){let me=Math.min(10,B.dur/le);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}Y()}},()=>this._handleNetworkError())},Qi=B=>{d()&&(ri(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(X(B),!1)))},kr=B=>{d()&&(e.cachedHeader=B,H(B,()=>{A=!0,Y()}))};s=!0,R.seek(B=>{if(d()){if(k=z(),!B){x();return}C=B,!yk(y)||B.startTS>y?qe(B):($=B,_())}},y),e.cachedHeader?kr(e.cachedHeader):p(e.headerUrl,kr,()=>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(),Ja(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,ri(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ja(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,f,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(f=this._getBufferSizeSec(),h=d/this.bitrate,f>10&&h>.8||f>15&&h>.5||f>20&&h>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(p,f)=>{let h=z();if(this.chunkRateEstimator.addInterval(p,h,f)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:h-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&Yo(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,p)=>{let f=s.updateChunk(d,p);return f&&u(),f},notifySwitch:d=>{let p=z();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=fr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Xa).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;ue(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!=null&&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))},Tk))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Pk,filter as Tm,fromEvent as kk,interval as wk,isHigher as Ak,isInvariantQuality as Rk,isLower as Lk,merge as $k,Subject as Im,Subscription as Ck}from"@vkontakte/videoplayer-shared";var zo=class{constructor(){this.onDroopedVideoFramesLimit$=new Im;this.subscription=new Ck;this.playing=!1;this.tracks=[];this.forceChecker$=new Im;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Rk(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;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&&Ak(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.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(kk(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=wk(this.droppedFramesChecker.checkTime).pipe(Tm(()=>this.playing),Tm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Pk(this.droppedFramesChecker.checkTime)),r=$k(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,a;let t=(a=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>Lk(s,n)?-1:1))==null?void 0:r[0])==null?void 0:a[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Za=zo;import{map as Dk,Observable as Mk}from"@vkontakte/videoplayer-shared";import{fromEvent as Ok}from"@vkontakte/videoplayer-shared";var ai=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var Bk=(i,e)=>new Mk(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||ai()))},{...r,...e});a.observe(i);let s=Ok(document,"visibilitychange").pipe(Dk(n=>!document.hidden||ai())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Te=Bk;var Gk=["paused","playing","ready"],Yk=["paused","playing","ready"],si=class{constructor(e){this.subscription=new Uk;this.videoState=new L("stopped");this.representations$=new Jo([]);this.textTracksManager=new Se;this.droppedFramesManager=new Za;this.maxSeekBackTime$=new Jo(1/0);this.zeroTime$=new Jo(void 0);this.liveOffset=new Ye;this._dashCb=e=>{var t,r,a,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Pm.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let l of n){let u=(t=l.name)!=null?t:l.index.toString(10),c=(r=lt(l.name))!=null?r:jk(l.video),d=l.bitrate/1e3,p={...l.video};if(!c)continue;let f={id:u,quality:c,bitrate:d,size:p};o.push({track:f,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),((a=this.videoState.getTransition())==null?void 0:a.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:l})=>l===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Ko(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),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(Yk.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&Gk.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(J(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==null?void 0: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(J(this.params.source.url,l))}return;default:return Em(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Pm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};km(this.videoState.stateChangeStarted$.pipe(es(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(es(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ae(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(Q(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=oe(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(es(a=>a.map(({track:s})=>s)))}),this.subscription.add(r.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())==null?void 0:a.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(Fk(),es(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(Vk({zeroTime:this.zeroTime$.pipe(Nk(Ko)),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(ne(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ve(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(Te(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&Hk(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var s;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":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Em(a.to)}},t)).add(km(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,qk(["init"])).pipe(_k(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),se(this.video)}createLiveDashPlayer(){let e=new ii({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var u,c,d,p,f,h;let e=this.representations$.getValue(),t=(c=(u=this.params.desiredState.videoTrack.getTransition())==null?void 0:u.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Ko(t)?t:dt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a==null?void 0:a.id,n=this.params.desiredState.videoTrack.getTransition(),o=(f=this.params.desiredState.videoTrack.getState())==null?void 0:f.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let b=(h=e.find(({track:v})=>v.id===s))==null?void 0:h.representation;xm(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:a})=>a.id===e.id))==null?void 0:r.representation;xm(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(J(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var wm=si;var pt=(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 dA,assertNonNullable as qb,debounce as pA,ErrorCategory as yu,filter as hA,filterChanged as Ub,fromEvent as fA,isLowerOrEqual as Hb,isNonNullable as mA,videoSizeToQuality as jb,map as Tu,merge as hs,observableFrom as bA,observeElementSize as gA,once as vA,Subscription as SA,ValueSubject as Gb}from"@vkontakte/videoplayer-shared";var ts=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}},mr=class extends ts{constructor(){super(),this.listeners||ts.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)}},ni=class{constructor(){Object.defineProperty(this,"signal",{value:new mr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(a){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ni.prototype[Symbol.toStringTag]="AbortController",mr.prototype[Symbol.toStringTag]="AbortSignal");function rs(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 Xo(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!rs({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 p=new t(u,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},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(f){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((f,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var oi=rs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Am=oi?Xo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Qe=oi?Am.fetch:window.fetch,k0=oi?Am.Request:window.Request,ze=oi?ni:window.AbortController,w0=oi?mr:window.AbortSignal;var _b=Oe(Da(),1);var ui=(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 gu,assertNonNullable as qt,combine as Db,ErrorCategory as ft,filter as us,filterChanged as aA,fromEvent as Ir,interval as vu,isNonNullable as Mb,map as Su,merge as Er,Subject as Ob,Subscription as Bb,tap as sA,throttle as nA,ValueSubject as he}from"@vkontakte/videoplayer-shared";var Tr=Oe(Qa(),1);var Wk=(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)},Qk=i=>window.clearTimeout(i),Rm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Zo=Rm?Wk:window.requestIdleCallback,L0=Rm?Qk:window.cancelIdleCallback;var xb=Oe(Ga(),1);import{assertNever as zk,CurrentClientBrowser as Kk,ErrorCategory as Lm,getCurrentBrowser as Jk,Subject as $m}from"@vkontakte/videoplayer-shared";var Xk=16,Mm=!1,Cm,Dm;try{Mm=Jk().browser===Kk.Safari&&parseInt((Dm=(Cm=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:Cm[1])!=null?Dm:"",10)<=Xk}catch(i){console.error(i)}var eu=class{constructor(e){this.bufferFull$=new $m;this.error$=new $m;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Lm.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let 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;Mm&&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(){var a;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((a=e.signal)!=null&&a.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Lm.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:zk(t)}}},Om=eu;var tu=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 Sr,assertNever as Kw,assertNonNullable as Ke,ErrorCategory as yr,fromEvent as pu,getExponentialDelay as hu,once as Jw,isNonNullable as Eb,isNullable as Je,Subject as Xw,Subscription as Zw,ValueSubject as Li}from"@vkontakte/videoplayer-shared";var V=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 br=class extends V{};var li=class extends V{};var ci=class extends V{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 di=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends V{constructor(t,r){super(t,r);this.data=this.content}};var j=class extends V{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Mt=class extends j{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 fi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var mi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var bi=class extends j{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 gi=class extends j{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var vi=class extends j{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Si=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends j{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 Ti=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ii=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends j{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var xi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends j{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 ki=class extends j{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var wi=class extends j{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let 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 ew={ftyp:ci,moov:di,moof:pi,mdat:hi,sidx:Mt,trak:fi,mdia:Si,mfhd:Ei,tkhd:yi,traf:xi,tfhd:Pi,tfdt:ki,trun:wi,minf:Ti,sv3d:mi,st3d:bi,prhd:gi,proj:Ii,equi:vi,uuid:li,unknown:br},Ot=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(a){break}return t}createBox(e,t){let r=ew[e];return r?new r(t,new i):new br(t,new i)}};var gr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,a,s;(s=(r=this.index)[a=t.type])!=null||(r[a]=[]),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 rw=new TextDecoder("ascii"),iw=i=>rw.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",aw=i=>{let e=new Mt(i,new Ot),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})},sw=(i,e)=>{let r=new Ot().parse(i),a=new gr(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)},nw=(i,e)=>{let r=new Ot().parse(i),s=new gr(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,p)=>d+p,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},ow=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 Ot().parse(i),a=new gr(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},Bm={validateData:iw,parseInit:ow,getIndexRange:()=>{},parseSegments:aw,parseFeedableSegmentChunk:sw,getSegmentEndTime:nw};import{assertNonNullable as iu,isNonNullable as Fm,isNullable as lw}from"@vkontakte/videoplayer-shared";import{assertNever as uw}from"@vkontakte/videoplayer-shared";var Vm={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"}},_m=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=Ai(i,t),a=r in Vm,s=a?Vm[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=Ai(l),d=u*2**((o-1)*8)+c,p=t+o,f;return p+d>i.byteLength?f=new DataView(i.buffer,i.byteOffset+p):f=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:f,valueSize:d}},Ai=(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},$e=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Ai(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:uw(e)}},Bt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=_m(r);if(!e(a))return;a.type==="master"&&Bt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Nm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=_m(i);return Bt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=$e(o,n):s===17026?t=$e(o,n):s===17029&&(r=$e(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var qm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],cw=[231,22612,22743,167,171,163,160,175],dw=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Bt(i,({tag:p,type:f,value:h,valueSize:b})=>{if(p===21419){let v=$e(h,f);u=Ai(v)}else p!==21420&&(u=void 0);return p===408125543?(e=h.byteOffset,t=h.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=$e(h,f):p===17545?a=$e(h,f):p===21420&&u===475249515?l=$e(h,f):p===374648427?Bt(h,({tag:v,type:S,value:g})=>v===30321?(c=$e(g,S)===1,!1):!0):s&&n&&qm.includes(p)&&(o=!0),!o}),iu(e,"Failed to parse webm Segment start"),iu(t,"Failed to parse webm Segment end"),iu(a,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(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}}}},pw=i=>{if(lw(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hw=(i,e)=>{let t=!1,r=!1,a=o=>Fm(o.time)&&Fm(o.position),s=[],n;return Bt(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=$e(u,l));break;case 183:break;case 241:n&&(n.position=$e(u,l));break;default:t&&qm.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}}})},fw=i=>{let e=0,t=!1;try{Bt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):cw.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Um={validateData:Nm,parseInit:dw,getIndexRange:pw,parseSegments:hw,parseFeedableSegmentChunk:fw};var uu=Oe(pb(),1);import{isNonNullable as fb,isNullable as mb}from"@vkontakte/videoplayer-shared";var hb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var bb=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==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],a),hours:e(r==null?void 0:r[6],a),minutes:e(r==null?void 0:r[7],a),seconds:e(r==null?void 0:r[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Vt=(i,e)=>{let t=i;t=(0,uu.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,uu.default)(t,n,(o,l)=>mb(s)?o:mb(l)?s:s.padStart(parseInt(l,10),"0"))}return t},vb=(i,e)=>{var y,E,M,R,A,N,$,C,k,U,ee,w,x,_,H,Y,X,qe,Qi,kr,B,te,le,me,tt,Yt,rt,vt,Wt,wr,Vu,_u,Nu,Fu,qu,Uu,Hu,ju,Gu,Yu,Wu,Qu;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(M=(E=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:E.trim())!=null?M:"",l=n.children,u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),h=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],v=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=bb(f);else if(h){let be=bb(h);fb(be)&&(p=be)}else v&&(p=parseInt(v,10));let S=0,g=(A=(R=s.getAttribute("profiles"))==null?void 0:R.split(","))!=null?A:[],I=g.includes("urn:webm:dash:profile:webm-on-demand:2012")||g.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let be of l){let zi=be.getAttribute("mimeType"),Wg=be.getAttribute("codecs"),zu=(N=be.getAttribute("contentType"))!=null?N:zi==null?void 0:zi.split("/")[0],Qg=(C=($=be.getAttribute("profiles"))==null?void 0:$.split(","))!=null?C:[],Ku=be.querySelectorAll("Representation"),zg=be.querySelector("SegmentTemplate");if(zu==="text"){for(let G of Ku){let it=G.getAttribute("id")||"",Ki=be.getAttribute("lang"),Qt=be.getAttribute("label"),Ms=(ee=(U=(k=G.querySelector("BaseURL"))==null?void 0:k.textContent)==null?void 0:U.trim())!=null?ee:"",Os=new URL(Ms||o,e).toString(),Ji=it.includes("_auto");a.text.push({id:it,lang:Ki,label:Qt,isAuto:Ji,kind:"text",url:Os})}continue}for(let G of Ku){let it=(w=G.getAttribute("mimeType"))!=null?w:zi,Ki=(_=(x=G.getAttribute("codecs"))!=null?x:Wg)!=null?_:"",Qt=(Y=(H=G.getAttribute("contentType"))!=null?H:it==null?void 0:it.split("/")[0])!=null?Y:zu,Ms=(qe=(X=be.getAttribute("profiles"))==null?void 0:X.split(","))!=null?qe:[],Os=parseInt((Qi=G.getAttribute("width"))!=null?Qi:"",10),Ji=parseInt((kr=G.getAttribute("height"))!=null?kr:"",10),Ju=parseInt((B=G.getAttribute("bandwidth"))!=null?B:"",10)/1e3,Xu=(te=G.getAttribute("frameRate"))!=null?te:"",Kg=(le=G.getAttribute("quality"))!=null?le:void 0,Jg=Xu?hb(Xu):void 0,Xg=(me=G.getAttribute("id"))!=null?me:(S++).toString(10),Zg=Qt==="video"?`${Ji}p`:Qt==="audio"?`${Ju}Kbps`:Ki,ev=`${Xg}@${Zg}`,tv=(rt=(Yt=(tt=G.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:Yt.trim())!=null?rt:"",Zu=new URL(tv||o,e).toString(),rv=[...g,...Qg,...Ms],Bs,iv=G.querySelector("SegmentBase"),St=(vt=G.querySelector("SegmentTemplate"))!=null?vt:zg;if(iv){let yt=(wr=(Wt=G.querySelector("SegmentBase Initialization"))==null?void 0:Wt.getAttribute("range"))!=null?wr:"",[Tt,_s]=yt.split("-").map(zt=>parseInt(zt,10)),at={from:Tt,to:_s},Ar=(Vu=G.querySelector("SegmentBase"))==null?void 0:Vu.getAttribute("indexRange"),[Ns,Xi]=Ar?Ar.split("-").map(zt=>parseInt(zt,10)):[],Rr=Ar?{from:Ns,to:Xi}:void 0;Bs={type:"byteRange",url:Zu,initRange:at,indexRange:Rr}}else if(St){let yt={representationId:(_u=G.getAttribute("id"))!=null?_u:void 0,bandwidth:(Nu=G.getAttribute("bandwidth"))!=null?Nu:void 0},Tt=parseInt((Fu=St.getAttribute("timescale"))!=null?Fu:"",10),_s=(qu=St.getAttribute("initialization"))!=null?qu:"",at=St.getAttribute("media"),Ar=(Hu=parseInt((Uu=St.getAttribute("startNumber"))!=null?Uu:"",10))!=null?Hu:1,Ns=Vt(_s,yt);if(!at)throw new ReferenceError("No media attribute in SegmentTemplate");let Xi=(ju=St.querySelectorAll("SegmentTimeline S"))!=null?ju:[],Rr=[],zt=0,Fs="",qs=0;if(Xi.length){let Zi=Ar,Pe=0;for(let Kt of Xi){let Me=parseInt((Gu=Kt.getAttribute("d"))!=null?Gu:"",10),It=parseInt((Yu=Kt.getAttribute("r"))!=null?Yu:"",10)||0,ea=parseInt((Wu=Kt.getAttribute("t"))!=null?Wu:"",10);Pe=Number.isFinite(ea)?ea:Pe;let Us=Me/Tt*1e3,Hs=Pe/Tt*1e3;for(let ta=0;ta<It+1;ta++){let sv=Vt(at,{...yt,segmentNumber:Zi.toString(10),segmentTime:(Pe+ta*Me).toString(10)}),el=(Hs!=null?Hs:0)+ta*Us,nv=el+Us;Zi++,Rr.push({time:{from:el,to:nv},url:sv})}Pe+=(It+1)*Me,zt+=(It+1)*Us}qs=Pe/Tt*1e3,Fs=Vt(at,{...yt,segmentNumber:Zi.toString(10),segmentTime:Pe.toString(10)})}else if(fb(p)){let Pe=parseInt((Qu=St.getAttribute("duration"))!=null?Qu:"",10)/Tt*1e3,Kt=Math.ceil(p/Pe),Me=0;for(let It=1;It<Kt;It++){let ea=Vt(at,{...yt,segmentNumber:It.toString(10),segmentTime:Me.toString(10)});Rr.push({time:{from:Me,to:Me+Pe},url:ea}),Me+=Pe}qs=Me,Fs=Vt(at,{...yt,segmentNumber:Kt.toString(10),segmentTime:Me.toString(10)})}let av={time:{from:qs,to:1/0},url:Fs};Bs={type:"template",baseUrl:Zu,segmentTemplateUrl:at,initUrl:Ns,totalSegmentsDurationMs:zt,segments:Rr,nextSegmentBeyondManifest:av,timescale:Tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qt||!it)continue;let Vs={video:"video",audio:"audio",text:"text"}[Qt];Vs&&a[Vs].push({id:ev,kind:Vs,segmentReference:Bs,profiles:rv,duration:p,bitrate:Ju,mime:it,codecs:Ki,width:Os,height:Ji,fps:Jg,quality:Kg})}}return{dynamic:u,liveAvailabilityStartTime:d,duration:p,container:I,representations:a}};var cu=Oe(Qa(),1);import{videoSizeToQuality as zw}from"@vkontakte/videoplayer-shared";var Sb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?lt(s):void 0)!=null?o:zw({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},yb=({id:i,bitrate:e})=>({id:i,bitrate:e}),Tb=(i,e,t)=>{var a;let r=e.indexOf(t);return(a=(0,cu.default)(i,Math.round(i.length*r/e.length)))!=null?a:(0,cu.default)(i,-1)},Ib=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),du=i=>"url"in i,_t=i=>i.type==="template",Ri=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var $i=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new Li(0);this.onLastSegment$=new Li(!1);this.fullyBuffered$=new Li(!1);this.playingRepresentation$=new Li(void 0);this.playingRepresentationInit$=new Li(void 0);this.error$=new Xw;this.gaps=[];this.subscription=new Zw;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=Sr(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 Om(this.sourceBuffer),this.subscription.add(pu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:yr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(pu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:yr.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,tu(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=Sr(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();Eb(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=Sr(this.destroyAbortController.signal,async function*(e){var o;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let l of this.representations.keys()){let u=e.find(p=>p.id===l);u&&this.representations.set(l,u);let c=this.representations.get(l);if(!c||!_t(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let t=(o=this.switchingToRepresentationId)!=null?o: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!=null&&c.dynamic),this.container=r,r){case"mp4":this.containerParser=Bm;break;case"webm":this.containerParser=Um;break;default:Kw(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()){var u,c;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(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((u=a==null?void 0:a.time.to)!=null?u:0)-((c=a==null?void 0:a.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=pt(this.sourceBuffer.buffered,e),f=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=a.time.to-e+100&&(s=f)}if(isFinite(this.bufferLimit)&&tu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=pt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))d="high";else{let p=(0,Tr.default)(o,0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&pt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Tr.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;Eb(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==null?void 0:e.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var t,r,a,s;for(let n of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!n||!_t(n.segmentReference))return;let o=n.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),l=(r=this.segments.get(n.id))!=null?r:[],u=(s=(a=(0,Tr.default)(l,-1))==null?void 0:a.time.to)!=null?s:0,c=o==null?void 0:o.findIndex(d=>Math.floor(u)>=Math.floor(d.time.from)&&Math.floor(u)<=Math.floor(d.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,d)}else{let d=o.slice(c+1);this.segments.set(n.id,[...l,...d])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let r of this.representations.values()){let a=r.segmentReference;if(!_t(a))return;let s=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),n=Vt(a.segmentTemplateUrl,{segmentTime:s}),o=(t=this.segments.get(r.id))!=null?t:[],l=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));l&&(l.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let a=r.find(l=>l.time.from<=e&&l.time.to>=e);return(o=a==null?void 0:a.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(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:p,to:f}},h)=>{let b=p<=r&&f>=r,v=p>r||b||h===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&p<=r+S||f<=r+S;return(d==="none"||d==="partially_ejected"&&v&&g&&this.sourceBuffer&&!ui(this.sourceBuffer.buffered,r))&&v&&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 p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);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 Sr(o,async function*(){let c=hu(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 p=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,p)}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]),Ri(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 Sr(n,async function*(){let l=hu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),pu(window,"online").pipe(Jw()).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),Ri(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(_t(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Tr.default)(e,0).byte.from,to:(0,Tr.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:yr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!_t(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:yr.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!=null&&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,p=l==="byteRange",f=p?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,v=p?d.byte.to-r:e.byteLength,S=b<a,g=v<=a;if(d.status==="downloading"&&S&&g){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+b,f);this.sourceBufferTaskQueue.append(I,s).then(y=>y&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(f,a-b),c.loadedBytes>c.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===f?I:this.containerParser.parseFeedableSegmentChunk(I);y!=null&&y.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(E=>{if(s.aborted)n();else if(E)c.fedBytes+=y.byteLength,c.fedBytes===f&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",du(e.segment)&&(e.segment.size=e.fedBytes);for(let a of this.representations.values())if(a.id!==t)for(let s of(r=this.segments.get(a.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.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||(t=n),s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Zo(()=>(0,xb.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?Sr(this.destroyAbortController.signal,async function*(){let o=hu(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 p=c;this.isLive&&_t(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),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:yr.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=>{var d;s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let c=du(u)?(d=u.size)!=null?d: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 p of this.segments.values())for(let f of p)if(f.status==="none"&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.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=Zo(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:yr.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 Ci=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Pb=i=>{var s;let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,a=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:a}};import{abortable as Di,assertNever as kb,fromEvent as wb,merge as eA,now as fu,Subscription as tA,ValueSubject as mu}from"@vkontakte/videoplayer-shared";var is=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new mu(void 0);this.lastConnectionReused$=new mu(void 0);this.lastRequestFirstBytes$=new mu(void 0);this.abortAllController=new ze;this.subscription=new tA;this.fetchManifest=Di(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ci(t));let r=yield Qe(t,{signal:this.abortAllController.signal}).catch(Mi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Di(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}={}){var A,N;let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let $=new URL(u,location.href);$.searchParams.append("bytes",`${r.from}-${r.to}`),u=$.toString();break}default:kb(t)}this.requestQuic&&(u=Ci(u));let d=this.abortAllController.signal,p;if(n){let $=new ze;if(p=eA(wb(this.abortAllController.signal,"abort"),wb(n,"abort")).subscribe(()=>{try{$.abort()}catch(C){Mi(C)}}),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(C){Mi(C)}d=$.signal}let f=fu(),h=yield Qe(u,{priority:s,headers:c,signal:d}).catch(Mi),b=fu();if(!h)return p==null||p.unsubscribe(),null;if((A=this.throughputEstimator)==null||A.addRawRtt(b-f),!h.ok||!h.body)return p==null||p.unsubscribe(),Promise.reject(new Error(`Fetch error ${h.status}: ${h.statusText}`));if(this.onHeadersReceived(h.headers),!a&&!o)return p==null||p.unsubscribe(),h.arrayBuffer();let[v,S]=h.body.tee(),g=v.getReader();o&&((N=this.throughputEstimator)==null||N.trackStream(S,l));let I=0,y=new Uint8Array(0),E=!1,M=$=>{p==null||p.unsubscribe(),E=!0,Mi($)},R=Di(d,async function*({done:$,value:C}){if(I===0&&this.lastRequestFirstBytes$.next(fu()-f),d.aborted){p==null||p.unsubscribe();return}if(!$&&C){let k=new Uint8Array(y.length+C.length);k.set(y),k.set(C,y.length),y=k,I+=C.byteLength,a==null||a(new DataView(y.buffer),I),yield g==null?void 0:g.read().then(R,M)}}.bind(this));return yield g==null?void 0:g.read().then(R,M),p==null||p.unsubscribe(),E?null:y.buffer}.bind(this));this.fetchByteRangeRepresentation=Di(this.abortAllController.signal,async function*(e,t,r){var S;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 p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let f=t.parseInit(p),h=(S=e.indexRange)!=null?S:t.getIndexRange(f);if(!h)throw new ReferenceError("No way to load representation index");let b;if(l)b=new DataView(d,h.from-n,h.to-h.from+1);else{let g=yield this.fetch(e.url,{range:h,priority:r,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let v=t.parseSegments(b,f,h);return{init:f,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=Di(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}=Pb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:a}=e;switch(a){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:kb(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Mi=i=>{if(!Ri(i))throw i};var Nt=(i,e,t)=>t*e+(1-t)*i,bu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Ab=(i,e,t,r)=>{let a=0,s=t,n=bu(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 rA,ValueSubject as Rb}from"@vkontakte/videoplayer-shared";var ht=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Rb(e.initial),this.debounced$=new Rb(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Z(`raw_${t}`),this.smoothedSeries$=new Z(`smoothed_${t}`),this.reportedSeries$=new Z(`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)&&(rA(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 as=class extends ht{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Nt(this.slow,t,this.params.emaAlphaSlow),this.fast=Nt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var ss=class extends ht{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=bu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Nt(this.emaSmoothed,t,this.params.emaAlpha);let a=Ab(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var ns=class extends ht{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?Nt(this.smoothed,t,this.params.emaAlpha):t}};var Ft=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new as({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ss({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 ns({initial:e,label:"liveEdgeDelay",...t})}};var Lb=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Xe=()=>window.ManagedMediaSource||window.MediaSource,os=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},$b=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Cb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Vb=["timeupdate","progress","play","seeked","stalled","waiting"];var ls=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Bb;this.representationSubscription=new Bb;this.state$=new L("none");this.currentVideoRepresentation$=new he(void 0);this.currentVideoRepresentationInit$=new he(void 0);this.currentVideoSegmentLength$=new he(0);this.currentAudioSegmentLength$=new he(0);this.error$=new Ob;this.lastConnectionType$=new he(void 0);this.lastConnectionReused$=new he(void 0);this.lastRequestFirstBytes$=new he(void 0);this.isLive$=new he(!1);this.liveDuration$=new he(0);this.liveAvailabilityStartTime$=new he(void 0);this.bufferLength$=new he(0);this.liveLoadBufferLength$=new he(0);this.livePositionFromPlayer$=new he(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Ob;this.gapWatchdogActive=!1;this.destroyController=new ze;this.initManifest=gu(this.destroyController.signal,async function*(e,t,r){var a;this.element=e,this.manifestUrlString=J(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(a=this.manifest)!=null&&a.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ft.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=gu(this.destroyController.signal,async function*(){var a;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ft.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=vb(e!=null?e:"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:ft.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;let r=({kind:s,mime:n,codecs:o})=>{var l,u,c,d;return!!((u=(l=this.element)==null?void 0:l.canPlayType)!=null&&u.call(l,n)&&((d=(c=Xe())==null?void 0:c.isTypeSupported)!=null&&d.call(c,`${n}; codecs="${o}"`))||s==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((a=t.duration)!=null?a:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:(0,_b.default)(Object.entries(t.representations).map(([s,n])=>[s,n.filter(r)]))}}.bind(this));this.initRepresentations=gu(this.destroyController.signal,async function*(e,t,r){var f;qt(this.manifest),qt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=h=>{this.representationSubscription.add(Ir(h,"error").pipe(us(b=>{var v;return!!((v=this.element)!=null&&v.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:ft.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?Cb():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&os())if(r){let h=document.createElement("source");a(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}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 $i("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],Mb(t)&&(this.audioBufferManager=new $i("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(vu(1e3).subscribe(h=>{var b;if((b=this.element)!=null&&b.paused){let v=Mo(this.manifestUrlString,2);this.manifestUrlString=J(this.manifestUrlString,v+1e3,2)}})),this.representationSubscription.add(Er(...Vb.filter(h=>h!=="waiting").map(h=>Ir(this.element,h))).pipe(Su(h=>this.element?pt(this.element.buffered,this.element.currentTime*1e3):0),aA(),us(h=>!!h),sA(h=>{var b;(b=this.stallWatchdogSubscription)==null||b.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(us(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=b-v,y=1+Math.sign(I)*g;Math.abs(I)<S?y=1:Math.abs(I)>S*2&&(y=1+Math.sign(I)*g*2),Lb(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var S,g;let v=0;if(b){let I=((g=(S=this.element)==null?void 0:S.currentTime)!=null?g:0)*1e3;v=Math.min(...this.bufferManagers.map(E=>{var M,R;return(R=(M=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:M.to)!=null?R:I}))-I}this.liveLoadBufferLength$.getValue()!==v&&this.liveLoadBufferLength$.next(v)}));let h=0;this.representationSubscription.add(Db({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(nA(1e3)).subscribe(async({liveLoadBufferLength:b,bufferLength:v})=>{if(qt(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,g=Mo(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,M=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,R=this.isActiveLowLatency?v:b,A=3;if(this.isActiveLowLatency?A=0:R<y+M&&R>=y?A=1:g!==0&&R<y&&(A=2),isFinite(b)&&(h=b>h?b:h),A===2||A===1){let N=h-(y+E),$=this.normolizeLiveOffset(Math.trunc(g+N/S)),C=Math.abs($-g),k;!b||C<=this.tuning.dashCmafLive.offsetCalculationError?k=g:$>0&&C>this.tuning.dashCmafLive.offsetCalculationError?k=$:k=0,this.manifestUrlString=J(this.manifestUrlString,k,2)}A!==3&&A!==0&&(h=0,this.updateLive())}))}let o=Er(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(Su(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),l=Er(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(Su(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add(Er(this.forceEnded$,Db({allBuffersFull:o,someBufferEnded:l}).pipe(us(({allBuffersFull:h,someBufferEnded:b})=>h&&b))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(h=this.source)==null||h.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:ft.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add(Er(...this.bufferManagers.map(h=>h.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(h=>{var b;return(b=this.source)==null?void 0:b.addEventListener("sourceopen",h)}));let u=(f=this.manifest.duration)!=null?f:0,c=(h,b)=>{var v;return Math.max(h,(v=b.duration)!=null?v:0)},d=this.manifest.representations.audio.reduce(c,u),p=this.manifest.representations.video.reduce(c,u);(d||p)&&(this.source.duration=Math.max(d,p)/1e3),this.audioBufferManager&&Mb(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=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=vu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:ft.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new is({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ft.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var r,a,s,n;qt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=J(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((a=this.videoBufferManager)==null?void 0:a.seekLive((r=this.manifest)==null?void 0:r.representations.video)),await((n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.representations.audio)))}initBuffer(){qt(this.element),this.state$.setState("running"),this.subscription.add(Er(...Vb.map(e=>Ir(this.element,e)),Ir(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ft.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ir(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ir(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&ui(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)}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=vu(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:ft.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t)}seek(e,t){var a,s,n,o,l;qt(this.element),qt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((a=this.videoBufferManager.findSegmentStartTime(e))!=null?a:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),ui(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(a=>a.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)==null?void 0:e.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;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 cs=class{constructor(e,t){this.fov=e,this.orientation=t}};var ds=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let 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!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let 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 Nb=`attribute vec2 a_vertex;
34
+ [selected track] ${k==null?void 0:k.quality}
35
+ `});let N=k&&l&&l.history[k.id]&&Tm()-l.history[k.id]<=r.trackCooldown&&(!l.last||k.id!==l.last.id);if(k!=null&&k.id&&l&&!N&&l.recordSelection(k),N&&(l!=null&&l.last)){let A=l.last;return l==null||l.recordSwitch(A),d({message:`
36
+ [last selected] ${A==null?void 0:A.quality}
37
+ `}),A}return l==null||l.recordSwitch(k),k},dt=Tw;var Q=i=>new URL(i).hostname;import{assertNever as Am,assertNonNullable as km,combine as qw,debounce as Uw,ErrorCategory as Rm,filter as Hw,filterChanged as jw,isNonNullable as Zo,map as rs,merge as Lm,observableFrom as Gw,Subscription as Yw,ValueSubject as eu,videoQualityToHeight as Ww,videoSizeToQuality as Qw}from"@vkontakte/videoplayer-shared";var Im=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"))},ue=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Im(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Im(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Za,isNullable as xw,assertNonNullable as ii}from"@vkontakte/videoplayer-shared";import{isNonNullable as Em,assertNonNullable as Xa,now as Iw}from"@vkontakte/videoplayer-shared";function z(){return Iw()}function zo(i){return z()-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,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function xm(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function fr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,f="arraybuffer",h=7e3,b=2e3,v=()=>{if(u)return;Xa(c);let w=zo(c),U;if(w<b){U=b-w,setTimeout(v,U);return}b*=2,b>h&&(b=h),n&&n.abort(),n=new a,M()},S=w=>(s=w,C),g=w=>(d=w,C),I=()=>(f="json",C),y=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},E=w=>(p=w,C),M=()=>{c=z(),n=new a,n.open("get",i);let w=0,U,ee=0,A=()=>(Xa(c),Math.max(c,Math.max(U||0,ee||0)));if(s&&n.addEventListener("progress",x=>{let _=z();s.updateChunk&&x.loaded>w&&(s.updateChunk(A(),x.loaded-w),w=x.loaded,U=_)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;Xa(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let _=n.response.byteLength-w;_&&s.updateChunk&&s.updateChunk(A(),_)}n.responseType==="json"&&!Object.values(n.response).length?y():(d&&d(),e(n.response))}else y()}),n.addEventListener("error",()=>{y()}),p){let x=()=>{Xa(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ee=z(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=f,n.send(),C},C={withBitrateReporting:S,withParallel:E,withJSONResponse:I,withRetryCount:w=>(l=w,C),withRetryInterval:(w,U)=>(Em(w)&&(b=w),Em(U)&&(h=U),C),withTimeout:w=>(o=w,C),withFinally:g,send:M,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return C}var ti=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 u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}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 ri=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=z(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=z()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=fr(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=z()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=z();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,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 es=1e4,Jo=3;var Pw=6e4,ww=10,Aw=1,kw=500,ai=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 ti(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",()=>{var a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(a=e.error)==null?void 0:a.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||Za(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=()=>{xm(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 ri(Jo,es,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,u=null,l=null,c=!1,d=()=>{let y=s&&(!c||c===this.rep);return y||t("Not running!"),y},p=(y,E,M)=>{u&&u.abort(),u=fr(this.urlResolver.resolve(y,!1),E,M,()=>this._retryCallback()).withTimeout(es).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Jo).withFinally(()=>{u=null}).send()},f=(y,E,M)=>{ii(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),E,M,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=y=>{let E=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${E}=>${y}`),r.playbackRate=y)},b=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let M=z()-1e4,R=0;for(let N=0;N<this.bufferStates.length;N++){let $=this.bufferStates[N];y=Math.min(y,$.buf),$.ts<M&&R++}this.bufferStates.splice(0,R),t(`update playback rate; minBuffer=${y} drop=${R} jitter=${this.sourceJitter}`);let k=y-Aw;this.sourceJitter>=0?k-=this.sourceJitter/2:this.sourceJitter-=1,k>3?h(1.15):k>1?h(1.1):k>.3?h(1.05):h(1)}},S=y=>{let E,M=()=>E&&E.start?E.start.length:0,R=x=>E.start[x]/1e3,k=x=>E.dur[x]/1e3,N=x=>E.fragIndex+x,$=(x,_)=>({chunkIdx:N(x),startTS:R(x),dur:k(x),discontinuity:_}),C=()=>{let x=0;if(E&&E.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=_;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let X=E.dur.length-1;for(;X>=0&&(Y-=E.dur[X],!(Y<=0));--X);x=Math.min(X,E.dur.length-1-H),x=Math.max(x,0)}return $(x,!0)},w=x=>{let _=M();if(!(_<=0)){if(Za(x)){for(let H=0;H<_;H++)if(R(H)>x)return $(H)}return C()}},U=x=>{let _=M(),H=x?x.chunkIdx+1:0,Y=H-E.fragIndex;if(!(_<=0)){if(!x||Y<0||Y-_>ww)return t(`Resync: offset=${Y} bChunks=${_} chunk=`+JSON.stringify(x)),C();if(!(Y>=_))return $(H-E.fragIndex,!1)}},ee=(x,_,H)=>{l&&l.abort(),l=fr(this.urlResolver.resolve(x,!0,this.lowLatency),_,H,()=>this._retryCallback()).withTimeout(es).withRetryCount(Jo).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,_)=>{ee(y,H=>{if(!d())return;E=H;let Y=!!E.lowLatency;Y!==this.lowLatency&&b(Y);let X=0;for(let qe=0;qe<E.dur.length;++qe)X+=E.dur[qe];X>0&&(ii(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(X/E.dur.length)),a({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,x(w(_))},()=>this._handleNetworkError())},nextChunk:U}},g=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ii(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{let{videoElement:E,logger:M}=this.params,R=S(e.jidxUrl),k,N,$,C,w=0,U,ee,A,x=()=>{U&&(clearTimeout(U),U=void 0);let B=Math.max(kw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),te=w+B,le=z(),me=Math.min(1e4,te-le);w=le;let tt=()=>{l||d()&&R.seek(()=>{d()&&(w=z(),_(),x())})};me>0?U=window.setTimeout(()=>{this.paused?x():tt()},me):tt()},_=()=>{let B;for(;B=R.nextChunk(C);)C=B,Ki(B);let te=R.nextChunk($);if(te){if($&&te.discontinuity){M("Detected discontinuity; restarting playback"),this.paused?x():(g(),this._initPlayerWith(e));return}qe(te)}else x()},H=(B,te)=>{if(!d()||!this.sourceBuffer)return;let le,me,tt,Yt=rt=>{window.setTimeout(()=>{d()&&H(B,te)},rt)};if(this.sourceBuffer.updating)M("Source buffer is updating; delaying appendBuffer"),Yt(100);else{let rt=z(),vt=E.currentTime;!this.paused&&E.buffered.length>1&&ee===vt&&rt-A>500&&(M("Stall suspected; trying to fix"),this._fixupStall()),ee!==vt&&(ee=vt,A=rt);let Wt=this._getBufferSizeSec();if(Wt>30)M(`Buffered ${Wt} seconds; delaying appendBuffer`),Yt(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:rt,buf:Wt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),te&&te()}catch(kr){if(kr.name==="QuotaExceededError")M("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(le=this.sourceBuffer.buffered.start(0),me=vt,me-le>4&&this.sourceBuffer.remove(le,me-3)),Yt(1e3);else throw kr}}},Y=()=>{N&&k&&(M([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify($)]),H(N,function(){N=null,_()}))},X=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),qe=B=>{d()&&f(X(B),(te,le)=>{if(d()){if(le/=1e3,N=te,$=B,n=B.startTS,le){let me=Math.min(10,B.dur/le);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}Y()}},()=>this._handleNetworkError())},Ki=B=>{d()&&(ii(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(X(B),!1)))},Ar=B=>{d()&&(e.cachedHeader=B,H(B,()=>{k=!0,Y()}))};s=!0,R.seek(B=>{if(d()){if(w=z(),!B){x();return}C=B,!xw(y)||B.startTS>y?qe(B):($=B,_())}},y),e.cachedHeader?Ar(e.cachedHeader):p(e.headerUrl,Ar,()=>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(),Za(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,ii(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Za(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,f,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(f=this._getBufferSizeSec(),h=d/this.bitrate,f>10&&h>.8||f>15&&h>.5||f>20&&h>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(p,f)=>{let h=z();if(this.chunkRateEstimator.addInterval(p,h,f)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:h-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&zo(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let f=s.updateChunk(d,p);return f&&l(),f},notifySwitch:d=>{let p=z();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=fr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(es).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;ue(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!=null&&n.length?(n.forEach((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Pw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Rw,filter as Pm,fromEvent as Lw,interval as $w,isHigher as Cw,isInvariantQuality as Dw,isLower as Mw,merge as Ow,Subject as wm,Subscription as Bw}from"@vkontakte/videoplayer-shared";var Xo=class{constructor(){this.onDroopedVideoFramesLimit$=new wm;this.subscription=new Bw;this.playing=!1;this.tracks=[];this.forceChecker$=new wm;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Dw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;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&&Cw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.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(Lw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=$w(this.droppedFramesChecker.checkTime).pipe(Pm(()=>this.playing),Pm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Rw(this.droppedFramesChecker.checkTime)),r=Ow(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,a;let t=(a=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>Mw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:a[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ts=Xo;import{map as Vw,Observable as _w}from"@vkontakte/videoplayer-shared";import{fromEvent as Nw}from"@vkontakte/videoplayer-shared";var si=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var Fw=(i,e)=>new _w(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||si()))},{...r,...e});a.observe(i);let s=Nw(document,"visibilitychange").pipe(Vw(n=>!document.hidden||si())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Te=Fw;var zw=["paused","playing","ready"],Kw=["paused","playing","ready"],ni=class{constructor(e){this.subscription=new Yw;this.videoState=new L("stopped");this.representations$=new eu([]);this.textTracksManager=new Se;this.droppedFramesManager=new ts;this.maxSeekBackTime$=new eu(1/0);this.zeroTime$=new eu(void 0);this.liveOffset=new Ye;this._dashCb=e=>{var t,r,a,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Rm.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=lt(u.name))!=null?r:Qw(u.video),d=u.bitrate/1e3,p={...u.video};if(!c)continue;let f={id:l,quality:c,bitrate:d,size:p};o.push({track:f,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((a=this.videoState.getTransition())==null?void 0:a.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Zo(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),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(Kw.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&zw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(J(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a==null?void 0:a.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(J(this.params.source.url,u))}return;default:return Am(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Rm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Lm(this.videoState.stateChangeStarted$.pipe(rs(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(rs(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ae(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(Q(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=oe(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(rs(a=>a.map(({track:s})=>s)))}),this.subscription.add(r.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())==null?void 0:a.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(jw(),rs(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(qw({zeroTime:this.zeroTime$.pipe(Hw(Zo)),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(ne(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ve(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(Te(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&Ww(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var s;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":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Am(a.to)}},t)).add(Lm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Gw(["init"])).pipe(Uw(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),se(this.video)}createLiveDashPlayer(){let e=new ai({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,f,h;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Zo(t)?t:dt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a==null?void 0:a.id,n=this.params.desiredState.videoTrack.getTransition(),o=(f=this.params.desiredState.videoTrack.getState())==null?void 0:f.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let b=(h=e.find(({track:v})=>v.id===s))==null?void 0:h.representation;km(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:a})=>a.id===e.id))==null?void 0:r.representation;km(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(J(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var $m=ni;var pt=(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 mk,assertNonNullable as Gb,debounce as bk,ErrorCategory as Eu,filter as gk,filterChanged as Yb,fromEvent as vk,isLowerOrEqual as Wb,isNonNullable as Sk,videoSizeToQuality as Qb,map as xu,merge as ms,observableFrom as yk,observeElementSize as Tk,once as Ik,Subscription as Ek,ValueSubject as zb}from"@vkontakte/videoplayer-shared";var is=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}},mr=class extends is{constructor(){super(),this.listeners||is.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)}},oi=class{constructor(){Object.defineProperty(this,"signal",{value:new mr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(a){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(oi.prototype[Symbol.toStringTag]="AbortController",mr.prototype[Symbol.toStringTag]="AbortSignal");function as(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 tu(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!as({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(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(f){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((f,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ui=as({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Cm=ui?tu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Qe=ui?Cm.fetch:window.fetch,C0=ui?Cm.Request:window.Request,ze=ui?oi:window.AbortController,D0=ui?mr:window.AbortSignal;var Ub=Oe(Oa(),1);var li=(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 yu,assertNonNullable as qt,combine as Vb,ErrorCategory as ft,filter as cs,filterChanged as uk,fromEvent as Ir,interval as Tu,isNonNullable as _b,map as Iu,merge as Er,Subject as Nb,Subscription as Fb,tap as lk,throttle as ck,ValueSubject as he}from"@vkontakte/videoplayer-shared";var Tr=Oe(Ka(),1);var Jw=(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)},Xw=i=>window.clearTimeout(i),Dm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ru=Dm?Jw:window.requestIdleCallback,B0=Dm?Xw:window.cancelIdleCallback;var kb=Oe(Wa(),1);import{assertNever as Zw,CurrentClientBrowser as eA,ErrorCategory as Mm,getCurrentBrowser as tA,Subject as Om}from"@vkontakte/videoplayer-shared";var rA=16,_m=!1,Bm,Vm;try{_m=tA().browser===eA.Safari&&parseInt((Vm=(Bm=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:Bm[1])!=null?Vm:"",10)<=rA}catch(i){console.error(i)}var iu=class{constructor(e){this.bufferFull$=new Om;this.error$=new Om;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Mm.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let 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;_m&&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(){var a;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((a=e.signal)!=null&&a.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Mm.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Zw(t)}}},Nm=iu;var au=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 Sr,assertNever as ek,assertNonNullable as Ke,ErrorCategory as yr,fromEvent as mu,getExponentialDelay as bu,once as tk,isNonNullable as Ab,isNullable as Je,Subject as rk,Subscription as ik,ValueSubject as $i}from"@vkontakte/videoplayer-shared";var V=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 br=class extends V{};var ci=class extends V{};var di=class extends V{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 pi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var hi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fi=class extends V{constructor(t,r){super(t,r);this.data=this.content}};var j=class extends V{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Mt=class extends j{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,u=this.readUint32();s=this.readUint32();let l=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:u,SAPType:l,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var mi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var bi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends j{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 vi=class extends j{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Si=class extends j{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var yi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends j{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 Ii=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ei=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xi=class extends j{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var Pi=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends j{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 Ai=class extends j{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ki=class extends j{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let 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 aA={ftyp:di,moov:pi,moof:hi,mdat:fi,sidx:Mt,trak:mi,mdia:yi,mfhd:xi,tkhd:Ti,traf:Pi,tfhd:wi,tfdt:Ai,trun:ki,minf:Ii,sv3d:bi,st3d:gi,prhd:vi,proj:Ei,equi:Si,uuid:ci,unknown:br},Ot=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(a){break}return t}createBox(e,t){let r=aA[e];return r?new r(t,new i):new br(t,new i)}};var gr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,a,s;(s=(r=this.index)[a=t.type])!=null||(r[a]=[]),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 nA=new TextDecoder("ascii"),oA=i=>nA.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",uA=i=>{let e=new Mt(i,new Ot),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})},lA=(i,e)=>{let r=new Ot().parse(i),a=new gr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},cA=(i,e)=>{let r=new Ot().parse(i),s=new gr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},dA=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 Ot().parse(i),a=new gr(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 u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Fm={validateData:oA,parseInit:dA,getIndexRange:()=>{},parseSegments:uA,parseFeedableSegmentChunk:lA,getSegmentEndTime:cA};import{assertNonNullable as nu,isNonNullable as jm,isNullable as hA}from"@vkontakte/videoplayer-shared";import{assertNever as pA}from"@vkontakte/videoplayer-shared";var qm={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"}},Um=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=Ri(i,t),a=r in qm,s=a?qm[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 u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=Ri(u),d=l*2**((o-1)*8)+c,p=t+o,f;return p+d>i.byteLength?f=new DataView(i.buffer,i.byteOffset+p):f=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:f,valueSize:d}},Ri=(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},$e=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Ri(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:pA(e)}},Bt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Um(r);if(!e(a))return;a.type==="master"&&Bt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Hm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Um(i);return Bt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=$e(o,n):s===17026?t=$e(o,n):s===17029&&(r=$e(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Gm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],fA=[231,22612,22743,167,171,163,160,175],mA=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Bt(i,({tag:p,type:f,value:h,valueSize:b})=>{if(p===21419){let v=$e(h,f);l=Ri(v)}else p!==21420&&(l=void 0);return p===408125543?(e=h.byteOffset,t=h.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=$e(h,f):p===17545?a=$e(h,f):p===21420&&l===475249515?u=$e(h,f):p===374648427?Bt(h,({tag:v,type:S,value:g})=>v===30321?(c=$e(g,S)===1,!1):!0):s&&n&&Gm.includes(p)&&(o=!0),!o}),nu(e,"Failed to parse webm Segment start"),nu(t,"Failed to parse webm Segment end"),nu(a,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},bA=i=>{if(hA(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},gA=(i,e)=>{let t=!1,r=!1,a=o=>jm(o.time)&&jm(o.position),s=[],n;return Bt(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=$e(l,u));break;case 183:break;case 241:n&&(n.position=$e(l,u));break;default:t&&Gm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},vA=i=>{let e=0,t=!1;try{Bt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):fA.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Ym={validateData:Hm,parseInit:mA,getIndexRange:bA,parseSegments:gA,parseFeedableSegmentChunk:vA};var du=Oe(bb(),1);import{isNonNullable as vb,isNullable as Sb}from"@vkontakte/videoplayer-shared";var gb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var yb=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],a),hours:e(r==null?void 0:r[6],a),minutes:e(r==null?void 0:r[7],a),seconds:e(r==null?void 0:r[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Vt=(i,e)=>{let t=i;t=(0,du.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,du.default)(t,n,(o,u)=>Sb(s)?o:Sb(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Ib=(i,e)=>{var y,E,M,R,k,N,$,C,w,U,ee,A,x,_,H,Y,X,qe,Ki,Ar,B,te,le,me,tt,Yt,rt,vt,Wt,kr,qu,Uu,Hu,ju,Gu,Yu,Wu,Qu,zu,Ku,Ju,Xu;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(M=(E=(y=s.querySelector("BaseURL"))==null?void 0:y.textContent)==null?void 0:E.trim())!=null?M:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),h=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],v=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=yb(f);else if(h){let be=yb(h);vb(be)&&(p=be)}else v&&(p=parseInt(v,10));let S=0,g=(k=(R=s.getAttribute("profiles"))==null?void 0:R.split(","))!=null?k:[],I=g.includes("urn:webm:dash:profile:webm-on-demand:2012")||g.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let be of u){let Ji=be.getAttribute("mimeType"),Jg=be.getAttribute("codecs"),Zu=(N=be.getAttribute("contentType"))!=null?N:Ji==null?void 0:Ji.split("/")[0],Xg=(C=($=be.getAttribute("profiles"))==null?void 0:$.split(","))!=null?C:[],el=be.querySelectorAll("Representation"),Zg=be.querySelector("SegmentTemplate");if(Zu==="text"){for(let G of el){let it=G.getAttribute("id")||"",Xi=be.getAttribute("lang"),Qt=be.getAttribute("label"),Vs=(ee=(U=(w=G.querySelector("BaseURL"))==null?void 0:w.textContent)==null?void 0:U.trim())!=null?ee:"",_s=new URL(Vs||o,e).toString(),Zi=it.includes("_auto");a.text.push({id:it,lang:Xi,label:Qt,isAuto:Zi,kind:"text",url:_s})}continue}for(let G of el){let it=(A=G.getAttribute("mimeType"))!=null?A:Ji,Xi=(_=(x=G.getAttribute("codecs"))!=null?x:Jg)!=null?_:"",Qt=(Y=(H=G.getAttribute("contentType"))!=null?H:it==null?void 0:it.split("/")[0])!=null?Y:Zu,Vs=(qe=(X=be.getAttribute("profiles"))==null?void 0:X.split(","))!=null?qe:[],_s=parseInt((Ki=G.getAttribute("width"))!=null?Ki:"",10),Zi=parseInt((Ar=G.getAttribute("height"))!=null?Ar:"",10),tl=parseInt((B=G.getAttribute("bandwidth"))!=null?B:"",10)/1e3,rl=(te=G.getAttribute("frameRate"))!=null?te:"",ev=(le=G.getAttribute("quality"))!=null?le:void 0,tv=rl?gb(rl):void 0,rv=(me=G.getAttribute("id"))!=null?me:(S++).toString(10),iv=Qt==="video"?`${Zi}p`:Qt==="audio"?`${tl}Kbps`:Xi,av=`${rv}@${iv}`,sv=(rt=(Yt=(tt=G.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:Yt.trim())!=null?rt:"",il=new URL(sv||o,e).toString(),nv=[...g,...Xg,...Vs],Ns,ov=G.querySelector("SegmentBase"),St=(vt=G.querySelector("SegmentTemplate"))!=null?vt:Zg;if(ov){let yt=(kr=(Wt=G.querySelector("SegmentBase Initialization"))==null?void 0:Wt.getAttribute("range"))!=null?kr:"",[Tt,qs]=yt.split("-").map(zt=>parseInt(zt,10)),at={from:Tt,to:qs},Rr=(qu=G.querySelector("SegmentBase"))==null?void 0:qu.getAttribute("indexRange"),[Us,ea]=Rr?Rr.split("-").map(zt=>parseInt(zt,10)):[],Lr=Rr?{from:Us,to:ea}:void 0;Ns={type:"byteRange",url:il,initRange:at,indexRange:Lr}}else if(St){let yt={representationId:(Uu=G.getAttribute("id"))!=null?Uu:void 0,bandwidth:(Hu=G.getAttribute("bandwidth"))!=null?Hu:void 0},Tt=parseInt((ju=St.getAttribute("timescale"))!=null?ju:"",10),qs=(Gu=St.getAttribute("initialization"))!=null?Gu:"",at=St.getAttribute("media"),Rr=(Wu=parseInt((Yu=St.getAttribute("startNumber"))!=null?Yu:"",10))!=null?Wu:1,Us=Vt(qs,yt);if(!at)throw new ReferenceError("No media attribute in SegmentTemplate");let ea=(Qu=St.querySelectorAll("SegmentTimeline S"))!=null?Qu:[],Lr=[],zt=0,Hs="",js=0;if(ea.length){let ta=Rr,Pe=0;for(let Kt of ea){let Me=parseInt((zu=Kt.getAttribute("d"))!=null?zu:"",10),It=parseInt((Ku=Kt.getAttribute("r"))!=null?Ku:"",10)||0,ra=parseInt((Ju=Kt.getAttribute("t"))!=null?Ju:"",10);Pe=Number.isFinite(ra)?ra:Pe;let Gs=Me/Tt*1e3,Ys=Pe/Tt*1e3;for(let ia=0;ia<It+1;ia++){let lv=Vt(at,{...yt,segmentNumber:ta.toString(10),segmentTime:(Pe+ia*Me).toString(10)}),al=(Ys!=null?Ys:0)+ia*Gs,cv=al+Gs;ta++,Lr.push({time:{from:al,to:cv},url:lv})}Pe+=(It+1)*Me,zt+=(It+1)*Gs}js=Pe/Tt*1e3,Hs=Vt(at,{...yt,segmentNumber:ta.toString(10),segmentTime:Pe.toString(10)})}else if(vb(p)){let Pe=parseInt((Xu=St.getAttribute("duration"))!=null?Xu:"",10)/Tt*1e3,Kt=Math.ceil(p/Pe),Me=0;for(let It=1;It<Kt;It++){let ra=Vt(at,{...yt,segmentNumber:It.toString(10),segmentTime:Me.toString(10)});Lr.push({time:{from:Me,to:Me+Pe},url:ra}),Me+=Pe}js=Me,Hs=Vt(at,{...yt,segmentNumber:Kt.toString(10),segmentTime:Me.toString(10)})}let uv={time:{from:js,to:1/0},url:Hs};Ns={type:"template",baseUrl:il,segmentTemplateUrl:at,initUrl:Us,totalSegmentsDurationMs:zt,segments:Lr,nextSegmentBeyondManifest:uv,timescale:Tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qt||!it)continue;let Fs={video:"video",audio:"audio",text:"text"}[Qt];Fs&&a[Fs].push({id:av,kind:Fs,segmentReference:Ns,profiles:nv,duration:p,bitrate:tl,mime:it,codecs:Xi,width:_s,height:Zi,fps:tv,quality:ev})}}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,container:I,representations:a}};var hu=Oe(Ka(),1);import{videoSizeToQuality as ZA}from"@vkontakte/videoplayer-shared";var Eb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?lt(s):void 0)!=null?o:ZA({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},xb=({id:i,bitrate:e})=>({id:i,bitrate:e}),Pb=(i,e,t)=>{var a;let r=e.indexOf(t);return(a=(0,hu.default)(i,Math.round(i.length*r/e.length)))!=null?a:(0,hu.default)(i,-1)},wb=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),fu=i=>"url"in i,_t=i=>i.type==="template",Li=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Ci=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:l=!1,manifest:c}){this.currentSegmentLength$=new $i(0);this.onLastSegment$=new $i(!1);this.fullyBuffered$=new $i(!1);this.playingRepresentation$=new $i(void 0);this.playingRepresentationInit$=new $i(void 0);this.error$=new rk;this.gaps=[];this.subscription=new ik;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=Sr(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 Nm(this.sourceBuffer),this.subscription.add(mu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:yr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(mu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:yr.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,au(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=Sr(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();Ab(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=Sr(this.destroyAbortController.signal,async function*(e){var o;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let u of this.representations.keys()){let l=e.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!_t(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let t=(o=this.switchingToRepresentationId)!=null?o: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=l,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(c!=null&&c.dynamic),this.container=r,r){case"mp4":this.containerParser=Fm;break;case"webm":this.containerParser=Ym;break;default:ek(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()){var l,c;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(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=a==null?void 0:a.time.to)!=null?l:0)-((c=a==null?void 0:a.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=pt(this.sourceBuffer.buffered,e),f=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=a.time.to-e+100&&(s=f)}if(isFinite(this.bufferLimit)&&au(this.sourceBuffer.buffered)>=this.bufferLimit){let d=pt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))d="high";else{let p=(0,Tr.default)(o,0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&pt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Tr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}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;Ab(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==null?void 0:e.representations[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var t,r,a,s;for(let n of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!n||!_t(n.segmentReference))return;let o=n.segmentReference.segments.map(d=>({...d,status:"none",size:void 0})),u=(r=this.segments.get(n.id))!=null?r:[],l=(s=(a=(0,Tr.default)(u,-1))==null?void 0:a.time.to)!=null?s:0,c=o==null?void 0:o.findIndex(d=>Math.floor(l)>=Math.floor(d.time.from)&&Math.floor(l)<=Math.floor(d.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,d)}else{let d=o.slice(c+1);this.segments.set(n.id,[...u,...d])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let r of this.representations.values()){let a=r.segmentReference;if(!_t(a))return;let s=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),n=Vt(a.segmentTemplateUrl,{segmentTime:s}),o=(t=this.segments.get(r.id))!=null?t:[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let a=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=a==null?void 0:a.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(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:p,to:f}},h)=>{let b=p<=r&&f>=r,v=p>r||b||h===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&p<=r+S||f<=r+S;return(d==="none"||d==="partially_ejected"&&v&&g&&this.sourceBuffer&&!li(this.sourceBuffer.buffered,r))&&v&&g});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Sr(o,async function*(){let c=bu(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:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(this.isActiveLowLatency()){let p=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,p)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Li(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Sr(n,async function*(){let u=bu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),mu(window,"online").pipe(tk()).subscribe(()=>{l(),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(u){this.abortActiveSegments(e),Li(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(_t(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Tr.default)(e,0).byte.from,to:(0,Tr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:yr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!_t(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=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:yr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.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 u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",f=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,v=p?d.byte.to-r:e.byteLength,S=b<a,g=v<=a;if(d.status==="downloading"&&S&&g){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+b,f);this.sourceBufferTaskQueue.append(I,s).then(y=>y&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(f,a-b),c.loadedBytes>c.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),y=c.loadedBytes===f?I:this.containerParser.parseFeedableSegmentChunk(I);y!=null&&y.byteLength&&(d.status="partially_fed",c.feedingBytes+=y.byteLength,this.sourceBufferTaskQueue.append(y,s).then(E=>{if(s.aborted)n();else if(E)c.fedBytes+=y.byteLength,c.fedBytes===f&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",fu(e.segment)&&(e.segment.size=e.fedBytes);for(let a of this.representations.values())if(a.id!==t)for(let s of(r=this.segments.get(a.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.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||(t=n),s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=ru(()=>(0,kb.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?Sr(this.destroyAbortController.signal,async function*(){let o=bu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&_t(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:yr.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,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=fu(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;a+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let f of p)if(f.status==="none"&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.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 l=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+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let 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=ru(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:yr.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),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(l.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 Di=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Rb=i=>{var s;let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,a=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:a}};import{abortable as Mi,assertNever as Lb,fromEvent as $b,merge as ak,now as gu,Subscription as sk,ValueSubject as vu}from"@vkontakte/videoplayer-shared";var ss=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new vu(void 0);this.lastConnectionReused$=new vu(void 0);this.lastRequestFirstBytes$=new vu(void 0);this.abortAllController=new ze;this.subscription=new sk;this.fetchManifest=Mi(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Di(t));let r=yield Qe(t,{signal:this.abortAllController.signal}).catch(Oi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Mi(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:u=!1}={}){var k,N;let l=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let $=new URL(l,location.href);$.searchParams.append("bytes",`${r.from}-${r.to}`),l=$.toString();break}default:Lb(t)}this.requestQuic&&(l=Di(l));let d=this.abortAllController.signal,p;if(n){let $=new ze;if(p=ak($b(this.abortAllController.signal,"abort"),$b(n,"abort")).subscribe(()=>{try{$.abort()}catch(C){Oi(C)}}),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(C){Oi(C)}d=$.signal}let f=gu(),h=yield Qe(l,{priority:s,headers:c,signal:d}).catch(Oi),b=gu();if(!h)return p==null||p.unsubscribe(),null;if((k=this.throughputEstimator)==null||k.addRawRtt(b-f),!h.ok||!h.body)return p==null||p.unsubscribe(),Promise.reject(new Error(`Fetch error ${h.status}: ${h.statusText}`));if(this.onHeadersReceived(h.headers),!a&&!o)return p==null||p.unsubscribe(),h.arrayBuffer();let[v,S]=h.body.tee(),g=v.getReader();o&&((N=this.throughputEstimator)==null||N.trackStream(S,u));let I=0,y=new Uint8Array(0),E=!1,M=$=>{p==null||p.unsubscribe(),E=!0,Oi($)},R=Mi(d,async function*({done:$,value:C}){if(I===0&&this.lastRequestFirstBytes$.next(gu()-f),d.aborted){p==null||p.unsubscribe();return}if(!$&&C){let w=new Uint8Array(y.length+C.length);w.set(y),w.set(C,y.length),y=w,I+=C.byteLength,a==null||a(new DataView(y.buffer),I),yield g==null?void 0:g.read().then(R,M)}}.bind(this));return yield g==null?void 0:g.read().then(R,M),p==null||p.unsubscribe(),E?null:y.buffer}.bind(this));this.fetchByteRangeRepresentation=Mi(this.abortAllController.signal,async function*(e,t,r){var S;if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,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 p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let f=t.parseInit(p),h=(S=e.indexRange)!=null?S:t.getIndexRange(f);if(!h)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,h.from-n,h.to-h.from+1);else{let g=yield this.fetch(e.url,{range:h,priority:r,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let v=t.parseSegments(b,f,h);return{init:f,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=Mi(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}=Rb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:a}=e;switch(a){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Lb(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Oi=i=>{if(!Li(i))throw i};var Nt=(i,e,t)=>t*e+(1-t)*i,Su=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Cb=(i,e,t,r)=>{let a=0,s=t,n=Su(i,e),o=e<r?e:r;for(let u=0;u<o;u++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as nk,ValueSubject as Db}from"@vkontakte/videoplayer-shared";var ht=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Db(e.initial),this.debounced$=new Db(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Z(`raw_${t}`),this.smoothedSeries$=new Z(`smoothed_${t}`),this.reportedSeries$=new Z(`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)&&(nk(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 ns=class extends ht{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Nt(this.slow,t,this.params.emaAlphaSlow),this.fast=Nt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var os=class extends ht{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=Su(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Nt(this.emaSmoothed,t,this.params.emaAlpha);let a=Cb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var us=class extends ht{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?Nt(this.smoothed,t,this.params.emaAlpha):t}};var Ft=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ns({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new os({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 us({initial:e,label:"liveEdgeDelay",...t})}};var Mb=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var Xe=()=>window.ManagedMediaSource||window.MediaSource,ls=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Ob=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Bb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var qb=["timeupdate","progress","play","seeked","stalled","waiting"];var ds=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Fb;this.representationSubscription=new Fb;this.state$=new L("none");this.currentVideoRepresentation$=new he(void 0);this.currentVideoRepresentationInit$=new he(void 0);this.currentVideoSegmentLength$=new he(0);this.currentAudioSegmentLength$=new he(0);this.error$=new Nb;this.lastConnectionType$=new he(void 0);this.lastConnectionReused$=new he(void 0);this.lastRequestFirstBytes$=new he(void 0);this.isLive$=new he(!1);this.liveDuration$=new he(0);this.liveAvailabilityStartTime$=new he(void 0);this.bufferLength$=new he(0);this.liveLoadBufferLength$=new he(0);this.livePositionFromPlayer$=new he(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Nb;this.gapWatchdogActive=!1;this.destroyController=new ze;this.initManifest=yu(this.destroyController.signal,async function*(e,t,r){var a;this.element=e,this.manifestUrlString=J(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(a=this.manifest)!=null&&a.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ft.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=yu(this.destroyController.signal,async function*(){var a;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ft.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=Ib(e!=null?e:"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:ft.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;let r=({kind:s,mime:n,codecs:o})=>{var u,l,c,d;return!!((l=(u=this.element)==null?void 0:u.canPlayType)!=null&&l.call(u,n)&&((d=(c=Xe())==null?void 0:c.isTypeSupported)!=null&&d.call(c,`${n}; codecs="${o}"`))||s==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((a=t.duration)!=null?a:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:(0,Ub.default)(Object.entries(t.representations).map(([s,n])=>[s,n.filter(r)]))}}.bind(this));this.initRepresentations=yu(this.destroyController.signal,async function*(e,t,r){var f;qt(this.manifest),qt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=h=>{this.representationSubscription.add(Ir(h,"error").pipe(cs(b=>{var v;return!!((v=this.element)!=null&&v.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:ft.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?Bb():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ls())if(r){let h=document.createElement("source");a(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}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 Ci("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],_b(t)&&(this.audioBufferManager=new Ci("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(Tu(1e3).subscribe(h=>{var b;if((b=this.element)!=null&&b.paused){let v=Vo(this.manifestUrlString,2);this.manifestUrlString=J(this.manifestUrlString,v+1e3,2)}})),this.representationSubscription.add(Er(...qb.filter(h=>h!=="waiting").map(h=>Ir(this.element,h))).pipe(Iu(h=>this.element?pt(this.element.buffered,this.element.currentTime*1e3):0),uk(),cs(h=>!!h),lk(h=>{var b;(b=this.stallWatchdogSubscription)==null||b.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(cs(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=b-v,y=1+Math.sign(I)*g;Math.abs(I)<S?y=1:Math.abs(I)>S*2&&(y=1+Math.sign(I)*g*2),Mb(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var S,g;let v=0;if(b){let I=((g=(S=this.element)==null?void 0:S.currentTime)!=null?g:0)*1e3;v=Math.min(...this.bufferManagers.map(E=>{var M,R;return(R=(M=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:M.to)!=null?R:I}))-I}this.liveLoadBufferLength$.getValue()!==v&&this.liveLoadBufferLength$.next(v)}));let h=0;this.representationSubscription.add(Vb({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ck(1e3)).subscribe(async({liveLoadBufferLength:b,bufferLength:v})=>{if(qt(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,g=Vo(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,M=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,R=this.isActiveLowLatency?v:b,k=3;if(this.isActiveLowLatency?k=0:R<y+M&&R>=y?k=1:g!==0&&R<y&&(k=2),isFinite(b)&&(h=b>h?b:h),k===2||k===1){let N=h-(y+E),$=this.normolizeLiveOffset(Math.trunc(g+N/S)),C=Math.abs($-g),w;!b||C<=this.tuning.dashCmafLive.offsetCalculationError?w=g:$>0&&C>this.tuning.dashCmafLive.offsetCalculationError?w=$:w=0,this.manifestUrlString=J(this.manifestUrlString,w,2)}k!==3&&k!==0&&(h=0,this.updateLive())}))}let o=Er(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(Iu(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),u=Er(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(Iu(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add(Er(this.forceEnded$,Vb({allBuffersFull:o,someBufferEnded:u}).pipe(cs(({allBuffersFull:h,someBufferEnded:b})=>h&&b))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(h=this.source)==null||h.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:ft.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add(Er(...this.bufferManagers.map(h=>h.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(h=>{var b;return(b=this.source)==null?void 0:b.addEventListener("sourceopen",h)}));let l=(f=this.manifest.duration)!=null?f:0,c=(h,b)=>{var v;return Math.max(h,(v=b.duration)!=null?v:0)},d=this.manifest.representations.audio.reduce(c,l),p=this.manifest.representations.video.reduce(c,l);(d||p)&&(this.source.duration=Math.max(d,p)/1e3),this.audioBufferManager&&_b(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=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Tu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:ft.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ss({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ft.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var r,a,s,n;qt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=J(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((a=this.videoBufferManager)==null?void 0:a.seekLive((r=this.manifest)==null?void 0:r.representations.video)),await((n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.representations.audio)))}initBuffer(){qt(this.element),this.state$.setState("running"),this.subscription.add(Er(...qb.map(e=>Ir(this.element,e)),Ir(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ft.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ir(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ir(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&li(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)}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Tu(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:ft.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t)}seek(e,t){var a,s,n,o,u;qt(this.element),qt(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((a=this.videoBufferManager.findSegmentStartTime(e))!=null?a:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),li(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(a=>a.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)==null?void 0:e.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;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 ps=class{constructor(e,t){this.fov=e,this.orientation=t}};var hs=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!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let 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 Hb=`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 Fb=`#ifdef GL_ES
48
+ `;var jb=`#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 ps=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 cs(this.params.fov,this.params.orientation),this.cameraRotationManager=new ds(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(Nb,this.gl.VERTEX_SHADER),r=this.createShader(Fb,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,p=t+a;return[s,n,o,l,u,c,d,p]}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 Ht=class{constructor(e){this.subscription=new SA;this.videoState=new L("stopped");this.elementSize$=new Gb(void 0);this.textTracksManager=new Se;this.droppedFramesManager=new Za;this.videoTracks$=new Gb([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new za;this.textTracks=[];this.syncPlayback=()=>{var n,o,l;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==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let u=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(a.position-u,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==null?void 0:r.to)==="ready"&&T(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(l=this.liveOffset)==null||l.pause(),this.video.pause()):(r==null?void 0: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==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return dA(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new ps(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((a=e.projectionData)==null?void 0:a.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.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=ae(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(Q(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ls({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=oe(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:yu.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(Tu(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(hA(mA),vA()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(_e(this.video,t.isLooped,a)),this.subscription.add(ne(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(ve(this.video,t.playbackRate,r.playbackRateState$,a)),s(gA(this.video),this.elementSize$),s(Te(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})=>{var c;if(u==="manifest_ready"){let d=[];this.audioTracks=[],this.textTracks=[];let p=this.player.getRepresentations();qb(p,"Manifest not loaded or empty");let f=Array.from(p.audio).sort((S,g)=>g.bitrate-S.bitrate),h=Array.from(p.video).sort((S,g)=>g.bitrate-S.bitrate),b=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(let S of f){let g=yb(S);g&&this.audioTracks.push({track:g,representation:S})}for(let S of h){let g=Sb(S);if(g){d.push({track:g,representation:S});let I=!this.params.tuning.isAudioDisabled&&Tb(f,h,S);I&&this.audioRepresentations.set(S.id,I)}}this.videoTracks$.next(d);for(let S of b){let g=Ib(S);g&&this.textTracks.push({track:g,representation:S})}this.params.output.availableVideoTracks$.next(d.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));let v=this.selectVideoRepresentation();qb(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))==null?void 0:c.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:yu.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(hs(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$,fA(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(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);let f=this.params.desiredState.autoVideoTrackSwitching.getState(),h=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let b=d.id;!this.params.output.elementVisible$.getValue()&&f&&(b=this.videoTracks$.getValue().map(S=>S.representation).sort((S,g)=>g.bitrate-S.bitrate).filter(S=>{let g=jb(S),I=jb(d);if(g&&I)return Hb(g,I)&&Hb(g,h)}).map(S=>S.id)[0]),this.player.switchRepresentation("video",b).catch(n);let v=this.audioRepresentations.get(d.id);v&&this.player.switchRepresentation("audio",v.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(Ub(),Tu(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:d}})=>d===u))==null?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,d;if(u!=null&&u.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.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(Tu(({to:u})=>u==="ready"),Ub());this.subscription.add(hs(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(hs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=hs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,bA(["init"])).pipe(pA(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var d,p,f,h,b,v,S;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(d=this.params.desiredState.videoTrack.getState())==null?void 0:d.id,r=(p=this.videoTracks$.getValue().find(({track:{id:g}})=>g===t))==null?void 0:p.track,a=this.params.output.currentVideoTrack$.getValue(),s=pt(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&&(h=(f=this.audioRepresentations.get(r.id))==null?void 0:f.bitrate)!=null?h:0,a&&(v=(b=this.audioRepresentations.get(a.id))==null?void 0:b.bitrate)!=null?v:0),u=dt(this.videoTracks$.getValue().map(({track:g})=>g),{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!=null?u:r:r!=null?r:u;return c&&((S=this.videoTracks$.getValue().find(({track:g})=>g===c))==null?void 0:S.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ue(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.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:yu.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),se(this.video)}};var Oi=class extends Ht{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 Yb,interval as yA,map as TA}from"@vkontakte/videoplayer-shared";var Bi=class extends Ht{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(Yb({interval:yA(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var s;if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let n=e.position$.getValue()+(a-1);e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(Yb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(TA(({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(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,a)})}};var Qb=Oe(Ga(),1);import{assertNever as Vi,assertNonNullable as Wb,debounce as IA,ErrorCategory as fs,filter as EA,isNonNullable as xA,isNullable as PA,map as Iu,merge as kA,Observable as wA,observableFrom as AA,Subscription as RA,videoSizeToQuality as LA}from"@vkontakte/videoplayer-shared";var Ce={};var xr=(i,e)=>new wA(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),_i=class{constructor(e){this.subscription=new RA;this.videoState=new L("initializing");this.textTracksManager=new Se;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==null?void 0: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:Vi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Vi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Vi(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:Vi(e)}break;default:Vi(t)}};this.video=ae(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(Q(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),se(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:fs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Qb.default)(import("hls.js").then(a=>{e||(Ce.Hls=a.default,Ce.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Wb(Ce.Hls,"hls.js not loaded"),this.hls=new Ce.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Wb(Ce.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:fs.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=oe(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(ne(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ve(this.video,e.playbackRate,a.playbackRateState$,r)),s(Te(this.video),t.elementVisible$),this.subscription.add(xr(this.hls,Ce.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:fs.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)==null?void 0:c.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(()=>{var u;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(xr(this.hls,Ce.Events.MANIFEST_PARSED).pipe(Iu(({levels:u})=>u.reduce((c,d)=>{var g,I;let p=d.name||d.height.toString(10),{width:f,height:h}=d,b=(I=lt((g=d.attrs.QUALITY)!=null?g:""))!=null?I:LA({width:f,height:h});if(!b)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:f,height:h},fps:v};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(xr(this.hls,Ce.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let p=d.name,f=d.attrs.URI||"",h=d.lang,b="internal";c.push({id:p,url:f,language:h,type:b})}e.internalTextTracks.startTransitionTo(c)}}),s(xr(this.hls,Ce.Events.LEVEL_LOADING).pipe(Iu(({url:u})=>Q(u))),t.hostname$),s(xr(this.hls,Ce.Events.FRAG_CHANGED),u=>{var p,f,h,b;let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((f=c==null?void 0:c.startPTS)!=null?f:0))*1e3),t.currentAudioSegmentLength$.next((((h=d==null?void 0:d.endPTS)!=null?h:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(nt(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=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===u))==null?void 0:c.track},o=xr(this.hls,Ce.Events.LEVEL_SWITCHED).pipe(Iu(({level:u})=>n(this.hls.levels[u])));o.pipe(EA(xA)).subscribe(t.currentVideoTrack$,r),this.subscription.add(nt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{var h;if(PA(u))return;let c=(h=this.trackLevels.get(u.id))==null?void 0:h.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,f=this.hls.levels[p];!f||c.bitrate>f.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=kA(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,AA(["init"])).pipe(IA(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 ue(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fs.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 zb="X-Playback-Duration",Eu=async i=>{var a;let e=await Qe(i),t=await e.text(),r=(a=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:a[1];return r?parseInt(r,10):e.headers.has(zb)?parseInt(e.headers.get(zb),10):void 0};import{assertNever as BA,combine as VA,debounce as _A,ErrorCategory as bs,filter as NA,filterChanged as FA,isNonNullable as Jb,isNullable as gs,map as Xb,merge as qA,observableFrom as UA,Subscription as HA,ValueSubject as ku,VideoQuality as jA}from"@vkontakte/videoplayer-shared";var Pu=Oe(Da(),1);import{videoSizeToQuality as $A,getExponentialDelay as CA}from"@vkontakte/videoplayer-shared";var DA=i=>{let e=null;if(i.QUALITY&&(e=lt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=$A({width:t,height:r})}return e!=null?e:null},MA=(i,e)=>{var s,n;let t=i.split(`
92
- `),r=[],a=[];for(let o=0;o<t.length;o++){let l=t[o],u=l.match(/^#EXT-X-STREAM-INF:(.+)/),c=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!c)){if(u){let d=(0,Pu.default)(u[1].split(",").map(g=>g.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,f=DA(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[g,I]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));g&&I&&(v={width:g,height:I})}let S=new URL(t[++o],e).toString();f&&r.push({id:p,quality:f,url:S,bandwidth:h,size:v,fps:b})}if(c){let d=(0,Pu.default)(c[1].split(",").map(b=>b.split("=")).map(([b,v])=>[b,v.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),f=d.LANGUAGE,h=d.NAME;p&&f&&a.push({type:"internal",id:f,label:h,language:f,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},OA=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),xu=0,Kb=async(i,e=i,t)=>{let a=await(await Qe(i)).text();xu+=1;try{let{qualityManifests:s,textTracks:n}=MA(a,e);return{qualityManifests:s,textTracks:n}}catch(s){if(xu<=t.manifestRetryMaxCount)return await OA(CA(xu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Kb(i,e,t)}return{qualityManifests:[],textTracks:[]}},ms=Kb;var Ni=class{constructor(e){this.subscription=new HA;this.videoState=new L("stopped");this.textTracksManager=new Se;this.manifests$=new ku([]);this.liveOffset=new Ye;this.manifestStartTime$=new ku(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==null?void 0: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==null?void 0: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==null?void 0:a.to)==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return BA(t)}};var t;this.params=e,this.video=ae(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:jA.INVARIANT,url:this.params.source.url},ms(J(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:bs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:bs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),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(Q(this.params.source.url)),this.maxSeekBackTime$=new ku((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var l,u,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(l=a==null?void 0:a.to)==null?void 0:l.id)!=null?c:(u=t.getState())==null?void 0:u.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:bs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=oe(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(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),s(Te(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(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(FA(),Xb(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&&Jb(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(f=>f.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Q(p.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(()=>{var l,u,c;let o=(c=(u=(l=this.video)==null?void 0:l.getStartDate)==null?void 0:u.call(l))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(VA({startTime:this.manifestStartTime$.pipe(NA(Jb)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe(Xb(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=qA(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,UA(["init"])).pipe(_A(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){var o,l;let e=this.selectManifest();if(gs(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:u,min:c}=(l=(o=t==null?void 0:t.to)!=null?o:r)!=null?l:{};for(let[d,p]of[[u,"mq"],[c,"lq"]]){let f=String(parseFloat(d||""));p&&d&&a.searchParams.set(p,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=J(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Eu(n).then(u=>{var c;if(!gs(u))this.maxSeekBackTime$.next(u);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(gs(d)||!isFinite(d))try{Qe(n).then(p=>p.text()).then(p=>{var h;let f=(h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:h[1];if(f){let b=new URL(f,n).toString();Eu(b).then(v=>{gs(v)||this.maxSeekBackTime$.next(v)})}})}catch(p){}}})}playIfAllowed(){ue(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:bs.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 GA,debounce as YA,ErrorCategory as wu,fromEvent as Au,isNonNullable as WA,isNullable as QA,map as zA,merge as Zb,observableFrom as eg,Subscription as KA,ValueSubject as JA,VideoQuality as XA,isIOS as ZA}from"@vkontakte/videoplayer-shared";var Fi=class{constructor(e){this.subscription=new KA;this.videoState=new L("stopped");this.textTracksManager=new Se;this.manifests$=new JA([]);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==null?void 0: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==null?void 0:a.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return GA(t)}};this.params=e,this.video=ae(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:XA.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(Q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ms(J(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:wu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var l,u,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(l=a==null?void 0:a.to)==null?void 0:l.id)!=null?c:(u=t.getState())==null?void 0:u.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:wu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=oe(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(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(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(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{var d;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&&WA(u.to)){let p=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let f=this.manifests$.getValue().find(h=>h.id===p);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Q(f.url));let h=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(h!==b){let v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(h),v.playbackRate=h)}}}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(zA(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!ZA()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Zb(Au(o,"addtrack"),Au(o,"removetrack"),Au(o,"change"),eg(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=Zb(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,eg(["init"])).pipe(YA(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){var s,n;let e=this.selectManifest();if(QA(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}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[u,c]of[[o,"mq"],[l,"lq"]]){let d=String(parseFloat(u||""));c&&u&&a.searchParams.set(c,d)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ue(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:wu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as eR,assertNonNullable as tg,debounce as tR,ErrorCategory as rg,isHigher as rR,isHigherOrEqual as iR,isInvariantQuality as ig,isLowerOrEqual as aR,isNonNullable as sR,merge as nR,observableFrom as oR,Subscription as uR}from"@vkontakte/videoplayer-shared";var qi=class{constructor(e){this.subscription=new uR;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Se;this.syncPlayback=()=>{var l,u,c;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:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((l=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:l.max)!==((c=(u=this.trackUrls[n.to.id])==null?void 0:u.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0: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==null?void 0:r.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return eR(e)}};this.params=e,this.video=ae(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:rg.WTF,message:"MpegProvider internal logic error",thrown:o})},a=oe(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(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),s(Te(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(()=>{var l,u;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&sR(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(u=this.params.output.element$.getValue())==null?void 0:u.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=nR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,oR(["init"])).pipe(tR(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),se(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;tg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];tg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ci(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Q(t))}playIfAllowed(){ue(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:rg.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var a,s,n,o;let t,r=e;if(e&&((a=this.params.output.currentVideoTrack$.getValue())==null?void 0:a.quality)!==e){let l=(s=Object.values(this.trackUrls).find(d=>!ig(d.track.quality)&&aR(d.track.quality,e)))==null?void 0:s.track,u=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[u!=null?u:"0"])==null?void 0:o.track;if(l&&c&&iR(c.quality,l.quality)&&(t=l),!t){let d=Object.values(this.trackUrls).filter(f=>!ig(f.track.quality)&&rR(f.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let l=Object.values(this.trackUrls).map(u=>u.track);t=dt(l,{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 sg,debounce as pR,merge as ng,observableFrom as hR,Subscription as fR,map as og,ValueSubject as mR,ErrorCategory as Lu,VideoQuality as bR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as lR}from"@vkontakte/videoplayer-shared";var ag=["stun:videostun.mycdn.me:80"],cR=1e3,dR=3,Ru=()=>null,vs=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=Ru;this.externalStopCallback=Ru;this.externalErrorCallback=Ru;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:ag}]};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:lR.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(t){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),cR)}normalizeOptions(e={}){let t={stunServerList:ag,maxRetryNumber:dR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ui=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new mR(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==null?void 0:r.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return sg(e)}};this.subscription=new fR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ae(e.container),this.liveStreamClient=new vs(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),se(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})};ng(this.videoState.stateChangeStarted$.pipe(og(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(og(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=oe(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(Te(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(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.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(ne(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 sg(n.to)}},r)).add(ng(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,hR(["init"])).pipe(pR(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(Q(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:bR.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(){ue(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 Hi=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 Gi,assertNonNullable as bt,ErrorCategory as ks,filter as RR,isNonNullable as wg,isNullable as LR,map as $R,merge as CR,once as DR,Subject as De,Subscription as Ag,ValueSubject as O}from"@vkontakte/videoplayer-shared";import{assertNever as Ps,CurrentClientDevice as SR,getCurrentBrowser as yR}from"@vkontakte/videoplayer-shared";var vg=yR().device===SR.Android,Ee=document.createElement("video"),TR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',IR='video/mp4; codecs="hev1.1.6.L93.B0"',Sg='video/webm; codecs="vp09.00.10.08"',yg='video/webm; codecs="av01.0.00M.08"',ER='audio/mp4; codecs="mp4a.40.2"',xR='audio/webm; codecs="opus"',ug,lg,jt={mms:os(),mse:$b(),hls:!!((ug=Ee.canPlayType)!=null&&ug.call(Ee,"application/x-mpegurl")||(lg=Ee.canPlayType)!=null&&lg.call(Ee,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},cg,dg,Ie={mp4:!!((cg=Ee.canPlayType)!=null&&cg.call(Ee,"video/mp4")),webm:!!((dg=Ee.canPlayType)!=null&&dg.call(Ee,"video/webm")),cmaf:!0},Ss,pg,ys,hg,Ts,fg,Is,mg,Es,bg,xs,gg,Fe={h264:!!((pg=(Ss=Xe())==null?void 0:Ss.isTypeSupported)!=null&&pg.call(Ss,TR)),h265:!!((hg=(ys=Xe())==null?void 0:ys.isTypeSupported)!=null&&hg.call(ys,IR)),vp9:!!((fg=(Ts=Xe())==null?void 0:Ts.isTypeSupported)!=null&&fg.call(Ts,Sg)),av1:!!((mg=(Is=Xe())==null?void 0:Is.isTypeSupported)!=null&&mg.call(Is,yg)),aac:!!((bg=(Es=Xe())==null?void 0:Es.isTypeSupported)!=null&&bg.call(Es,ER)),opus:!!((gg=(xs=Xe())==null?void 0:xs.isTypeSupported)!=null&&gg.call(xs,xR))},ji=(Fe.h264||Fe.h265)&&Fe.aac,Gt,PR=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:yg}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Sg}})]);Gt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{PR()}catch(i){console.error(i)}var Pr=jt.hls&&Ie.mp4,Tg=()=>Object.keys(Fe).filter(i=>Fe[i]),Ig=(i,e=!1,t=!1)=>{let r=jt.mse||jt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Ie.mp4&&ji;case"DASH_WEBM":return r&&Ie.webm&&Fe.vp9&&Fe.opus;case"DASH_WEBM_AV1":return r&&Ie.webm&&Fe.av1&&Fe.opus;case"DASH_LIVE":return jt.mse&&Ie.mp4&&ji;case"DASH_LIVE_CMAF":return r&&Ie.mp4&&ji&&Ie.cmaf;case"DASH_ONDEMAND":return r&&Ie.mp4&&ji;case"HLS":case"HLS_ONDEMAND":return Pr||e&&jt.mse&&Ie.mp4&&ji;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Pr;case"MPEG":return Ie.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return jt.webrtc&&jt.ws&&Fe.h264&&(Ie.mp4||Ie.webm);default:return Ps(a)}})},mt=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 Gt?Gt[t].smooth?[t,e]:Gt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Gt?Gt[t].powerEfficient?[t,e]:Gt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ps(i)}return[e,t]},Eg=({webmCodec:i,androidPreferredFormat:e})=>{if(vg)switch(e){case"mpeg":return["MPEG",...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...mt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...mt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...mt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...mt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:Ps(e)}return Pr?[...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},xg=({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(vg)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:Ps(i)}else Pr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},$u=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 kR,map as Pg,Subscription as wR,Subject as AR}from"@vkontakte/videoplayer-shared";var kg=i=>new kR(e=>{let t=new wR,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Pg(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Pg(({type:u})=>u!==void 0)),n=new AR,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 MR={chunkDuration:5e3,maxParallelRequests:5},Yi=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new De;this.noAvailableProvidersError$=new De;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),currentVideoTrack$:new O(void 0),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),availableVideoTracks$:new O([]),availableAudioTracks$:new O([]),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new De,warning$:new De,willSeekEvent$:new De,seekedEvent$:new De,loopedEvent$:new De,endedEvent$:new De,firstBytesEvent$:new De,firstFrameEvent$:new De,canplay$:new De,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1)};this.subscription=new Ag;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Ig([...xg(this.params.tuning),...Eg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>wg(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 Hi(s);let n=[...$u(!0),...$u(!1)];this.chromecastFormatsIterator=new Hi(n.filter(o=>wg(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(LR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:ks.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 Gi(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 bt(o),new Oi({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return bt(o),new Bi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return bt(o),Pr||!this.params.tuning.useHlsJs?new Fi({...n,source:o}):new _i({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return bt(o),new Ni({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return bt(o),new qi({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return bt(o),new wm({...n,source:o,config:{...MR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return bt(o),new Ui({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 Gi(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 bt(o),new zr({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 Gi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Gi(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 Gi(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,Rg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Ag,t=!1,r=0;return e.add(CR(this.providerOutput.error$,kg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($R(a=>({id:`ProviderHangup:${a}`,category:ks.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(RR(({to:s})=>s==="playing"),DR()).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===ks.NETWORK,o=a.category===ks.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!=null?s:"SCREEN")}})),e}};import{fromEvent as ws,once as OR,combine as BR,Subscription as Lg,ValueSubject as Cu,map as VR,filter as _R,isNonNullable as As,now as fe,safeStorage as Du}from"@vkontakte/videoplayer-shared";var NR=5e3,$g="one_video_throughput",Cg="one_video_rtt",Ze=window.navigator.connection,Dg=()=>{let i=Ze==null?void 0:Ze.downlink;if(As(i)&&i!==10)return i*1e3},Mg=()=>{let i=Ze==null?void 0:Ze.rtt;if(As(i)&&i!==3e3)return i},Og=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Mu=class i{constructor(e){this.subscription=new Lg;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load($g)||(e.useBrowserEstimation?Dg():void 0)||NR,r=(s=(a=i.load(Cg))!=null?a:e.useBrowserEstimation?Mg():void 0)!=null?s:0;if(this.throughput$=new Cu(t),this.rtt$=new Cu(r),this.rttAdjustedThroughput$=new Cu(Og(t,r,e.rttPenaltyRequestSize)),this.throughput=Ft.getSmoothedValue(t,-1,e),this.rtt=Ft.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let l=Dg();l&&this.throughput.next(l);let u=Mg();As(u)&&this.rtt.next(u)};Ze&&"onchange"in Ze&&this.subscription.add(ws(Ze,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Du.set($g,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Du.set(Cg,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(BR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(VR(({throughput:n,rtt:o})=>Og(n,o,e.rttPenaltyRequestSize)),_R(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=fe(),a=new Lg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(ws(e,"progress").pipe(OR()).subscribe(s=>{t=s.loaded,r=fe()}));break;case 1:case 0:a.add(ws(e,"loadstart").subscribe(()=>{t=0,r=fe()}));break}a.add(ws(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=fe(),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=fe(),n=0,o=fe(),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,fe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(fe()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=fe()}o=fe()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&fe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,fe()-o,this.concurrentDownloads.size),n=0,o=fe());await(r==null?void 0:r.read().then(u,l))}};this.concurrentDownloads.add(e),r==null||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){var r;let t=Du.get(e);if(As(t))return(r=parseInt(t,10))!=null?r:void 0}},Bg=Mu;import{fillWithDefault as FR,VideoQuality as Vg}from"@vkontakte/videoplayer-shared";var _g={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:Vg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Vg.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}},Ng=i=>{var e;return{...FR(i,_g),configName:[...(e=i.configName)!=null?e:[],..._g.configName]}};import{assertNonNullable as Rs,combine as Ls,ErrorCategory as $s,filter as Wi,filterChanged as xe,fromEvent as Bu,isNonNullable as WR,isNullable as QR,Logger as zR,map as D,mapTo as Hg,merge as gt,now as Cs,once as et,Subject as F,Subscription as jg,tap as Gg,ValueSubject as P,isHigher as KR,isInvariantQuality as Yg}from"@vkontakte/videoplayer-shared";import{merge as qR,map as UR,filter as Fg,isNonNullable as HR}from"@vkontakte/videoplayer-shared";var Ou=({seekState:i,position$:e})=>qR(i.stateChangeEnded$.pipe(UR(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),Fg(HR)),e.pipe(Fg(()=>i.getState().state==="none")));import{assertNonNullable as jR}from"@vkontakte/videoplayer-shared";var qg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return jR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as GR,once as YR}from"@vkontakte/videoplayer-shared";var Ug=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(GR(a=>a.length>0),YR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var Ds=class{constructor(e={configName:[]}){this.subscription=new jg;this.logger=new zR;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 F,ready$:new F,started$:new F,playing$:new F,paused$:new F,stopped$:new F,willStart$:new F,willResume$:new F,willPause$:new F,willStop$:new F,willDestruct$:new F,watchCoverageRecord$:new F,watchCoverageLive$:new F,managedError$:new F,fatalError$:new F,ended$:new F,looped$:new F,seeked$:new F,willSeek$:new F,firstBytes$:new F,firstFrame$:new F,canplay$:new F,log$:new F};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:fm};if(this.initLogs(),this.tuning=Ng(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new aa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Bg(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,(p,f)=>{let h=typeof f;return["number","string","boolean"].includes(h)?f:f===null?null:`<${h}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:$s.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=qg(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Yi({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(a=e.failoverHosts)!=null?a:[],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(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.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&&!ai()?Bu(document,"visibilitychange").pipe(et()).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){Rs(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(Wi(r=>r.length>0),et()).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){var r;Rs(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.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){var t;return Ug(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.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(QR(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return WR(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.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(gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Wi(({from:e})=>e==="stopped"),et()).subscribe(()=>{this.initedAt=Cs(),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:$s.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(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),xe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(D(n=>n.map(({quality:o})=>o).sort((o,l)=>Yg(o)?1:Yg(l)?-1:KR(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==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(xe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(xe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(xe()).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!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(D(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(Ls({hasLiveOffsetByPaused:gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),xe(),D(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(Ls({atLiveEdge:Ls({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ou({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),xe(),Gg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ls({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),xe(),Gg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),xe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),xe()).subscribe(this.info.volume$)).add(Ou({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(gt(e.providerOutput.endedEvent$.pipe(Hg(!0)),e.providerOutput.seekedEvent$.pipe(Hg(!1))).pipe(xe()).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(D(n=>({id:n?`No${n}`:"NoProviders",category:$s.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(et(),D(n=>n!=null?n:Cs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),D(()=>Cs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),D(()=>Cs()-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(Wi(({to:n})=>n==="playing"),et()).subscribe(()=>r.next(!1)));let a=0,s=gt(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),xe());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(gt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var l,u;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=n==null?void 0:n.size)==null?void 0:l.width,height:(u=n==null?void 0:n.size)==null?void 0:u.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(gt(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(D(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new jg;this.subscription.add(t),this.subscription.add(e.current$.pipe(xe((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Wi(r=>r.length>0),et()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var a;let t,r=(a=this.desiredState.videoTrack.getState())==null?void 0:a.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=dt(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(gt(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(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(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Rs(this.providerContainer),Rs(e),hm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>pm(r)),this.providerContainer.current$.subscribe(({type:r})=>Zr("provider",r)),e.duration$.subscribe(r=>Zr("duration",r)),e.availableVideoTracks$.pipe(Wi(r=>!!r.length),et()).subscribe(r=>Zr("tracks",r)),this.events.fatalError$.subscribe(new Z("fatalError")),this.events.managedError$.subscribe(new Z("managedError")),e.position$.subscribe(new Z("position")),e.currentVideoTrack$.pipe(D(r=>r==null?void 0:r.quality)).subscribe(new Z("quality")),this.info.currentBuffer$.subscribe(new Z("buffer")),e.isBuffering$.subscribe(new Z("isBuffering"))].forEach(r=>this.subscription.add(r)),Zr("codecs",Tg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||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:$s.DOM,message:String(a)})})};this.subscription.add(gt(Bu(document,"visibilitychange"),Bu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&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 JH,Observable as XH,Subject as ZH,ValueSubject as ej,VideoQuality as tj}from"@vkontakte/videoplayer-shared";var rj=`@vkontakte/videoplayer-core@${rl}`;export{ra as ChromecastState,js as HttpConnectionType,XH as Observable,ce as PlaybackState,Ds as Player,rj as SDK_VERSION,ZH as Subject,JH as Subscription,Gs as Surface,rl as VERSION,ej as ValueSubject,Et as VideoFormat,tj as VideoQuality};
91
+ `;var fs=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 ps(this.params.fov,this.params.orientation),this.cameraRotationManager=new hs(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(Hb,this.gl.VERTEX_SHADER),r=this.createShader(jb,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,u=t-a,l=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,u,l,c,d,p]}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 Ht=class{constructor(e){this.subscription=new Ek;this.videoState=new L("stopped");this.elementSize$=new zb(void 0);this.textTracksManager=new Se;this.droppedFramesManager=new ts;this.videoTracks$=new zb([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new Ja;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;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==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(a.position-l,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==null?void 0:r.to)==="ready"&&T(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(r==null?void 0: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==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return mk(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new fs(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((a=e.projectionData)==null?void 0:a.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.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=ae(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(Q(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ds({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=oe(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Eu.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,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(xu(l=>l.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(gk(Sk),Ik()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(_e(this.video,t.isLooped,a)),this.subscription.add(ne(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(ve(this.video,t.playbackRate,r.playbackRateState$,a)),s(Tk(this.video),this.elementSize$),s(Te(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:l})=>{var c;if(l==="manifest_ready"){let d=[];this.audioTracks=[],this.textTracks=[];let p=this.player.getRepresentations();Gb(p,"Manifest not loaded or empty");let f=Array.from(p.audio).sort((S,g)=>g.bitrate-S.bitrate),h=Array.from(p.video).sort((S,g)=>g.bitrate-S.bitrate),b=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(let S of f){let g=xb(S);g&&this.audioTracks.push({track:g,representation:S})}for(let S of h){let g=Eb(S);if(g){d.push({track:g,representation:S});let I=!this.params.tuning.isAudioDisabled&&Pb(f,h,S);I&&this.audioRepresentations.set(S.id,I)}}this.videoTracks$.next(d);for(let S of b){let g=wb(S);g&&this.textTracks.push({track:g,representation:S})}this.params.output.availableVideoTracks$.next(d.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));let v=this.selectVideoRepresentation();Gb(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))==null?void 0:c.id,this.params.sourceHls)}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=l=>e.error$.next({id:"RepresentationSwitch",category:Eu.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(ms(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$,vk(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(l!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);let f=this.params.desiredState.autoVideoTrackSwitching.getState(),h=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let b=d.id;!this.params.output.elementVisible$.getValue()&&f&&(b=this.videoTracks$.getValue().map(S=>S.representation).sort((S,g)=>g.bitrate-S.bitrate).filter(S=>{let g=Qb(S),I=Qb(d);if(g&&I)return Wb(g,I)&&Wb(g,h)}).map(S=>S.id)[0]),this.player.switchRepresentation("video",b).catch(n);let v=this.audioRepresentations.get(d.id);v&&this.player.switchRepresentation("audio",v.id).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Yb(),xu(l=>{var c;return l&&((c=this.videoTracks$.getValue().find(({representation:{id:d}})=>d===l))==null?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.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(xu(({to:l})=>l==="ready"),Yb());this.subscription.add(ms(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(ms(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ms(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,yk(["init"])).pipe(bk(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var d,p,f,h,b,v,S;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(d=this.params.desiredState.videoTrack.getState())==null?void 0:d.id,r=(p=this.videoTracks$.getValue().find(({track:{id:g}})=>g===t))==null?void 0:p.track,a=this.params.output.currentVideoTrack$.getValue(),s=pt(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),u=Math.max(r&&!e&&(h=(f=this.audioRepresentations.get(r.id))==null?void 0:f.bitrate)!=null?h:0,a&&(v=(b=this.audioRepresentations.get(a.id))==null?void 0:b.bitrate)!=null?v:0),l=dt(this.videoTracks$.getValue().map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:u,forwardBufferHealth:o,current:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?l!=null?l:r:r!=null?r:l;return c&&((S=this.videoTracks$.getValue().find(({track:g})=>g===c))==null?void 0:S.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ue(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.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:Eu.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),se(this.video)}};var Bi=class extends Ht{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 Kb,interval as xk,map as Pk}from"@vkontakte/videoplayer-shared";var Vi=class extends Ht{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(Kb({interval:xk(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var s;if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let n=e.position$.getValue()+(a-1);e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(Kb({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Pk(({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(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,a)})}};var Xb=Oe(Wa(),1);import{assertNever as _i,assertNonNullable as Jb,debounce as wk,ErrorCategory as bs,filter as Ak,isNonNullable as kk,isNullable as Rk,map as Pu,merge as Lk,Observable as $k,observableFrom as Ck,Subscription as Dk,videoSizeToQuality as Mk}from"@vkontakte/videoplayer-shared";var Ce={};var xr=(i,e)=>new $k(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ni=class{constructor(e){this.subscription=new Dk;this.videoState=new L("initializing");this.textTracksManager=new Se;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==null?void 0: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:_i(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:_i(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:_i(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:_i(e)}break;default:_i(t)}};this.video=ae(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(Q(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),se(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:bs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Xb.default)(import("hls.js").then(a=>{e||(Ce.Hls=a.default,Ce.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Jb(Ce.Hls,"hls.js not loaded"),this.hls=new Ce.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Jb(Ce.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:bs.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=oe(this.video),s=(l,c)=>this.subscription.add(l.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(ne(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ve(this.video,e.playbackRate,a.playbackRateState$,r)),s(Te(this.video),t.elementVisible$),this.subscription.add(xr(this.hls,Ce.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:bs.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.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(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(xr(this.hls,Ce.Events.MANIFEST_PARSED).pipe(Pu(({levels:l})=>l.reduce((c,d)=>{var g,I;let p=d.name||d.height.toString(10),{width:f,height:h}=d,b=(I=lt((g=d.attrs.QUALITY)!=null?g:""))!=null?I:Mk({width:f,height:h});if(!b)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:f,height:h},fps:v};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(xr(this.hls,Ce.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,f=d.attrs.URI||"",h=d.lang,b="internal";c.push({id:p,url:f,language:h,type:b})}e.internalTextTracks.startTransitionTo(c)}}),s(xr(this.hls,Ce.Events.LEVEL_LOADING).pipe(Pu(({url:l})=>Q(l))),t.hostname$),s(xr(this.hls,Ce.Events.FRAG_CHANGED),l=>{var p,f,h,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((f=c==null?void 0:c.startPTS)!=null?f:0))*1e3),t.currentAudioSegmentLength$.next((((h=d==null?void 0:d.endPTS)!=null?h:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(nt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=xr(this.hls,Ce.Events.LEVEL_SWITCHED).pipe(Pu(({level:l})=>n(this.hls.levels[l])));o.pipe(Ak(kk)).subscribe(t.currentVideoTrack$,r),this.subscription.add(nt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var h;if(Rk(l))return;let c=(h=this.trackLevels.get(l.id))==null?void 0:h.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,f=this.hls.levels[p];!f||c.bitrate>f.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 u=Lk(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ck(["init"])).pipe(wk(0));this.subscription.add(u.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 ue(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bs.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 Zb="X-Playback-Duration",wu=async i=>{var a;let e=await Qe(i),t=await e.text(),r=(a=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:a[1];return r?parseInt(r,10):e.headers.has(Zb)?parseInt(e.headers.get(Zb),10):void 0};import{assertNever as Fk,combine as qk,debounce as Uk,ErrorCategory as vs,filter as Hk,filterChanged as jk,isNonNullable as tg,isNullable as Ss,map as rg,merge as Gk,observableFrom as Yk,Subscription as Wk,ValueSubject as Ru,VideoQuality as Qk}from"@vkontakte/videoplayer-shared";var ku=Oe(Oa(),1);import{videoSizeToQuality as Ok,getExponentialDelay as Bk}from"@vkontakte/videoplayer-shared";var Vk=i=>{let e=null;if(i.QUALITY&&(e=lt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=Ok({width:t,height:r})}return e!=null?e:null},_k=(i,e)=>{var s,n;let t=i.split(`
92
+ `),r=[],a=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,ku.default)(l[1].split(",").map(g=>g.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,f=Vk(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[g,I]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));g&&I&&(v={width:g,height:I})}let S=new URL(t[++o],e).toString();f&&r.push({id:p,quality:f,url:S,bandwidth:h,size:v,fps:b})}if(c){let d=(0,ku.default)(c[1].split(",").map(b=>b.split("=")).map(([b,v])=>[b,v.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),f=d.LANGUAGE,h=d.NAME;p&&f&&a.push({type:"internal",id:f,label:h,language:f,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},Nk=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Au=0,eg=async(i,e=i,t)=>{let a=await(await Qe(i)).text();Au+=1;try{let{qualityManifests:s,textTracks:n}=_k(a,e);return{qualityManifests:s,textTracks:n}}catch(s){if(Au<=t.manifestRetryMaxCount)return await Nk(Bk(Au-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),eg(i,e,t)}return{qualityManifests:[],textTracks:[]}},gs=eg;var Fi=class{constructor(e){this.subscription=new Wk;this.videoState=new L("stopped");this.textTracksManager=new Se;this.manifests$=new Ru([]);this.liveOffset=new Ye;this.manifestStartTime$=new Ru(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 l=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),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((a==null?void 0:a.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.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==null?void 0: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==null?void 0:a.to)==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Fk(t)}};var t;this.params=e,this.video=ae(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Qk.INVARIANT,url:this.params.source.url},gs(J(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:vs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:vs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),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(Q(this.params.source.url)),this.maxSeekBackTime$=new Ru((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:vs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=oe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,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(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),s(Te(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(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(jk(),rg(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&tg(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(f=>f.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Q(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(qk({startTime:this.manifestStartTime$.pipe(Hk(tg)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(rg(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=Gk(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Yk(["init"])).pipe(Uk(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){var o,u;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:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let f=String(parseFloat(d||""));p&&d&&a.searchParams.set(p,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=J(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),wu(n).then(l=>{var c;if(!Ss(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Ss(d)||!isFinite(d))try{Qe(n).then(p=>p.text()).then(p=>{var h;let f=(h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:h[1];if(f){let b=new URL(f,n).toString();wu(b).then(v=>{Ss(v)||this.maxSeekBackTime$.next(v)})}})}catch(p){}}})}playIfAllowed(){ue(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:vs.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 zk,debounce as Kk,ErrorCategory as Lu,fromEvent as $u,isNonNullable as Jk,isNullable as Xk,map as Zk,merge as ig,observableFrom as ag,Subscription as eR,ValueSubject as tR,VideoQuality as rR,isIOS as iR}from"@vkontakte/videoplayer-shared";var qi=class{constructor(e){this.subscription=new eR;this.videoState=new L("stopped");this.textTracksManager=new Se;this.manifests$=new tR([]);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 l=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),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!=="paused"&&l.state==="requested"&&this.seek(l.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==null?void 0:a.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return zk(t)}};this.params=e,this.video=ae(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:rR.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(Q(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),gs(J(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(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.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=oe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));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(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(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(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Jk(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(h=>h.id===p);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Q(f.url));let h=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(h!==b){let v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(h),v.playbackRate=h)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Zk(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!iR()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(ig($u(o,"addtrack"),$u(o,"removetrack"),$u(o,"change"),ag(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=ig(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ag(["init"])).pipe(Kk(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),se(this.video)}prepare(){var s,n;let e=this.selectManifest();if(Xk(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:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ue(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 aR,assertNonNullable as sg,debounce as sR,ErrorCategory as ng,isHigher as nR,isHigherOrEqual as oR,isInvariantQuality as og,isLowerOrEqual as uR,isNonNullable as lR,merge as cR,observableFrom as dR,Subscription as pR}from"@vkontakte/videoplayer-shared";var Ui=class{constructor(e){this.subscription=new pR;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Se;this.syncPlayback=()=>{var u,l,c;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:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0: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==null?void 0:r.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return aR(e)}};this.params=e,this.video=ae(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:ng.WTF,message:"MpegProvider internal logic error",thrown:o})},a=oe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,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(ne(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ve(this.video,t.playbackRate,a.playbackRateState$,r)),s(Te(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(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&lR(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=cR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,dR(["init"])).pipe(sR(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),se(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;sg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];sg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Di(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Q(t))}playIfAllowed(){ue(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:ng.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var a,s,n,o;let t,r=e;if(e&&((a=this.params.output.currentVideoTrack$.getValue())==null?void 0:a.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!og(d.track.quality)&&uR(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&oR(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(f=>!og(f.track.quality)&&nR(f.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=dt(u,{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 lg,debounce as bR,merge as cg,observableFrom as gR,Subscription as vR,map as dg,ValueSubject as SR,ErrorCategory as Du,VideoQuality as yR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as hR}from"@vkontakte/videoplayer-shared";var ug=["stun:videostun.mycdn.me:80"],fR=1e3,mR=3,Cu=()=>null,ys=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=Cu;this.externalStopCallback=Cu;this.externalErrorCallback=Cu;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:ug}]};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:hR.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(t){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),fR)}normalizeOptions(e={}){let t={stunServerList:ug,maxRetryNumber:mR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Hi=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new SR(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==null?void 0:r.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return lg(e)}};this.subscription=new vR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ae(e.container),this.liveStreamClient=new ys(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),se(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Du.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};cg(this.videoState.stateChangeStarted$.pipe(dg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(dg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=oe(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(Te(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(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.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(ne(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 lg(n.to)}},r)).add(cg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,gR(["init"])).pipe(bR(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(Q(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:yR.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:Du.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ue(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:Du.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ji=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 Wi,assertNonNullable as bt,ErrorCategory as Rs,filter as OR,isNonNullable as $g,isNullable as BR,map as VR,merge as _R,once as NR,Subject as De,Subscription as Cg,ValueSubject as O}from"@vkontakte/videoplayer-shared";import{assertNever as As,CurrentClientDevice as ER,getCurrentBrowser as xR}from"@vkontakte/videoplayer-shared";var Ig=xR().device===ER.Android,Ee=document.createElement("video"),PR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',wR='video/mp4; codecs="hev1.1.6.L93.B0"',Eg='video/webm; codecs="vp09.00.10.08"',xg='video/webm; codecs="av01.0.00M.08"',AR='audio/mp4; codecs="mp4a.40.2"',kR='audio/webm; codecs="opus"',pg,hg,jt={mms:ls(),mse:Ob(),hls:!!((pg=Ee.canPlayType)!=null&&pg.call(Ee,"application/x-mpegurl")||(hg=Ee.canPlayType)!=null&&hg.call(Ee,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},fg,mg,Ie={mp4:!!((fg=Ee.canPlayType)!=null&&fg.call(Ee,"video/mp4")),webm:!!((mg=Ee.canPlayType)!=null&&mg.call(Ee,"video/webm")),cmaf:!0},Ts,bg,Is,gg,Es,vg,xs,Sg,Ps,yg,ws,Tg,Fe={h264:!!((bg=(Ts=Xe())==null?void 0:Ts.isTypeSupported)!=null&&bg.call(Ts,PR)),h265:!!((gg=(Is=Xe())==null?void 0:Is.isTypeSupported)!=null&&gg.call(Is,wR)),vp9:!!((vg=(Es=Xe())==null?void 0:Es.isTypeSupported)!=null&&vg.call(Es,Eg)),av1:!!((Sg=(xs=Xe())==null?void 0:xs.isTypeSupported)!=null&&Sg.call(xs,xg)),aac:!!((yg=(Ps=Xe())==null?void 0:Ps.isTypeSupported)!=null&&yg.call(Ps,AR)),opus:!!((Tg=(ws=Xe())==null?void 0:ws.isTypeSupported)!=null&&Tg.call(ws,kR))},Gi=(Fe.h264||Fe.h265)&&Fe.aac,Gt,RR=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:xg}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Eg}})]);Gt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{RR()}catch(i){console.error(i)}var Pr=jt.hls&&Ie.mp4,Pg=()=>Object.keys(Fe).filter(i=>Fe[i]),wg=(i,e=!1,t=!1)=>{let r=jt.mse||jt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&Ie.mp4&&Gi;case"DASH_WEBM":return r&&Ie.webm&&Fe.vp9&&Fe.opus;case"DASH_WEBM_AV1":return r&&Ie.webm&&Fe.av1&&Fe.opus;case"DASH_LIVE":return jt.mse&&Ie.mp4&&Gi;case"DASH_LIVE_CMAF":return r&&Ie.mp4&&Gi&&Ie.cmaf;case"DASH_ONDEMAND":return r&&Ie.mp4&&Gi;case"HLS":case"HLS_ONDEMAND":return Pr||e&&jt.mse&&Ie.mp4&&Gi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Pr;case"MPEG":return Ie.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return jt.webrtc&&jt.ws&&Fe.h264&&(Ie.mp4||Ie.webm);default:return As(a)}})},mt=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 Gt?Gt[t].smooth?[t,e]:Gt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Gt?Gt[t].powerEfficient?[t,e]:Gt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:As(i)}return[e,t]},Ag=({webmCodec:i,androidPreferredFormat:e})=>{if(Ig)switch(e){case"mpeg":return["MPEG",...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...mt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...mt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...mt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...mt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:As(e)}return Pr?[...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...mt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},kg=({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(Ig)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:As(i)}else Pr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Mu=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 LR,map as Rg,Subscription as $R,Subject as CR}from"@vkontakte/videoplayer-shared";var Lg=i=>new LR(e=>{let t=new $R,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Rg(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Rg(({type:l})=>l!==void 0)),n=new CR,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var wr=null,ks=null;function Ou(){return wr||(wr=new(window.AudioContext||window.webkitAudioContext)),ks||(ks=new GainNode(wr,{gain:1}),ks.connect(wr.destination)),wr.resume().catch(),{audioCtx:wr,gainNode:ks}}import{getCurrentBrowser as DR,CurrentClientBrowser as MR}from"@vkontakte/videoplayer-shared";var Yi=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}=DR();return e!==MR.Safari&&"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}listener(e){if(!e)return;let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=Ou();a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(s){}}destroy(){let{gainNode:e}=Ou();e.gain.value=1}};var FR={chunkDuration:5e3,maxParallelRequests:5},Qi=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new De;this.noAvailableProvidersError$=new De;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),currentVideoTrack$:new O(void 0),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),availableVideoTracks$:new O([]),availableAudioTracks$:new O([]),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new De,warning$:new De,willSeekEvent$:new De,seekedEvent$:new De,loopedEvent$:new De,endedEvent$:new De,firstBytesEvent$:new De,firstFrameEvent$:new De,canplay$:new De,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1)};this.subscription=new Cg;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=wg([...kg(this.params.tuning),...Ag(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>$g(e.sources[u])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(u=>!a.includes(u)),...t.filter(u=>a.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new ji(s);let n=[...Mu(!0),...Mu(!1)];this.chromecastFormatsIterator=new ji(n.filter(u=>$g(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Yi(this.providerOutput.element$,(o=this.params.volumeMultiplier)!=null?o: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(BR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Rs.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 Wi(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]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return bt(o),new Bi({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return bt(o),new Vi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return bt(o),Pr||!this.params.tuning.useHlsJs?new qi({...n,source:o}):new Ni({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return bt(o),new Fi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return bt(o),new Ui({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return bt(o),new $m({...n,source:o,config:{...FR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return bt(o),new Hi({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 Wi(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 bt(o),new Kr({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 Wi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Wi(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 Wi(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,Dg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Cg,t=!1,r=0;return e.add(_R(this.providerOutput.error$,Lg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(VR(a=>({id:`ProviderHangup:${a}`,category:Rs.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(OR(({to:s})=>s==="playing"),NR()).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===Rs.NETWORK,o=a.category===Rs.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};import{fromEvent as Ls,once as qR,combine as UR,Subscription as Mg,ValueSubject as Bu,map as HR,filter as jR,isNonNullable as $s,now as fe,safeStorage as Vu}from"@vkontakte/videoplayer-shared";var GR=5e3,Og="one_video_throughput",Bg="one_video_rtt",Ze=window.navigator.connection,Vg=()=>{let i=Ze==null?void 0:Ze.downlink;if($s(i)&&i!==10)return i*1e3},_g=()=>{let i=Ze==null?void 0:Ze.rtt;if($s(i)&&i!==3e3)return i},Ng=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},_u=class i{constructor(e){this.subscription=new Mg;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load(Og)||(e.useBrowserEstimation?Vg():void 0)||GR,r=(s=(a=i.load(Bg))!=null?a:e.useBrowserEstimation?_g():void 0)!=null?s:0;if(this.throughput$=new Bu(t),this.rtt$=new Bu(r),this.rttAdjustedThroughput$=new Bu(Ng(t,r,e.rttPenaltyRequestSize)),this.throughput=Ft.getSmoothedValue(t,-1,e),this.rtt=Ft.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=Vg();u&&this.throughput.next(u);let l=_g();$s(l)&&this.rtt.next(l)};Ze&&"onchange"in Ze&&this.subscription.add(Ls(Ze,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Vu.set(Og,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Vu.set(Bg,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(UR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(HR(({throughput:n,rtt:o})=>Ng(n,o,e.rttPenaltyRequestSize)),jR(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=fe(),a=new Mg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Ls(e,"progress").pipe(qR()).subscribe(s=>{t=s.loaded,r=fe()}));break;case 1:case 0:a.add(Ls(e,"loadstart").subscribe(()=>{t=0,r=fe()}));break}a.add(Ls(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=fe(),u=n-t,l=o-r;this.addRawSpeed(u,l,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=fe(),n=0,o=fe(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,fe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(fe()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=fe()}o=fe()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&fe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,fe()-o,this.concurrentDownloads.size),n=0,o=fe());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}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){var r;let t=Vu.get(e);if($s(t))return(r=parseInt(t,10))!=null?r:void 0}},Fg=_u;import{fillWithDefault as YR,VideoQuality as qg}from"@vkontakte/videoplayer-shared";var Ug={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:qg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:qg.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},Hg=i=>{var e;return{...YR(i,Ug),configName:[...(e=i.configName)!=null?e:[],...Ug.configName]}};import{assertNonNullable as Cs,combine as Ds,ErrorCategory as Ms,filter as zi,filterChanged as xe,fromEvent as Fu,isNonNullable as ZR,isNullable as eL,Logger as tL,map as D,mapTo as Wg,merge as gt,now as Os,once as et,Subject as F,Subscription as Qg,tap as zg,ValueSubject as P,isHigher as rL,isInvariantQuality as Kg}from"@vkontakte/videoplayer-shared";import{merge as WR,map as QR,filter as jg,isNonNullable as zR}from"@vkontakte/videoplayer-shared";var Nu=({seekState:i,position$:e})=>WR(i.stateChangeEnded$.pipe(QR(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),jg(zR)),e.pipe(jg(()=>i.getState().state==="none")));import{assertNonNullable as KR}from"@vkontakte/videoplayer-shared";var Gg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return KR(e,`Wrong container or containerId {${i.container}}`),e};import{filter as JR,once as XR}from"@vkontakte/videoplayer-shared";var Yg=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(JR(a=>a.length>0),XR()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var Bs=class{constructor(e={configName:[]}){this.subscription=new Qg;this.logger=new tL;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 F,ready$:new F,started$:new F,playing$:new F,paused$:new F,stopped$:new F,willStart$:new F,willResume$:new F,willPause$:new F,willStop$:new F,willDestruct$:new F,watchCoverageRecord$:new F,watchCoverageLive$:new F,managedError$:new F,fatalError$:new F,ended$:new F,looped$:new F,seeked$:new F,willSeek$:new F,firstBytes$:new F,firstFrame$:new F,canplay$:new F,log$:new F};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:vm};if(this.initLogs(),this.tuning=Hg(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new na({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Fg(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 u=n.map(d=>JSON.stringify(d,(p,f)=>{let h=typeof f;return["number","string","boolean"].includes(h)?f:f===null?null:`<${h}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Ms.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=Gg(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Qi({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(a=e.failoverHosts)!=null?a:[],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(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.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&&!si()?Fu(document,"visibilitychange").pipe(et()).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){Cs(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(zi(r=>r.length>0),et()).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){var r;Cs(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.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){var t;return Yg(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.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(eL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return ZR(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.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(gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(zi(({from:e})=>e==="stopped"),et()).subscribe(()=>{this.initedAt=Os(),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:Ms.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(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),xe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(D(n=>n.map(({quality:o})=>o).sort((o,u)=>Kg(o)?1:Kg(u)?-1:rL(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.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==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(xe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(xe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(xe()).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!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(D(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(Ds({hasLiveOffsetByPaused:gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),xe(),D(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(Ds({atLiveEdge:Ds({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Nu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),xe(),zg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ds({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),xe(),zg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),xe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),xe()).subscribe(this.info.volume$)).add(Nu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(gt(e.providerOutput.endedEvent$.pipe(Wg(!0)),e.providerOutput.seekedEvent$.pipe(Wg(!1))).pipe(xe()).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(D(n=>({id:n?`No${n}`:"NoProviders",category:Ms.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(et(),D(n=>n!=null?n:Os()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),D(()=>Os()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),D(()=>Os()-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(zi(({to:n})=>n==="playing"),et()).subscribe(()=>r.next(!1)));let a=0,s=gt(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),xe());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(gt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(gt(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(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?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(D(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Qg;this.subscription.add(t),this.subscription.add(e.current$.pipe(xe((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(zi(r=>r.length>0),et()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var a;let t,r=(a=this.desiredState.videoTrack.getState())==null?void 0:a.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=dt(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(gt(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(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(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Cs(this.providerContainer),Cs(e),gm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>bm(r)),this.providerContainer.current$.subscribe(({type:r})=>ei("provider",r)),e.duration$.subscribe(r=>ei("duration",r)),e.availableVideoTracks$.pipe(zi(r=>!!r.length),et()).subscribe(r=>ei("tracks",r)),this.events.fatalError$.subscribe(new Z("fatalError")),this.events.managedError$.subscribe(new Z("managedError")),e.position$.subscribe(new Z("position")),e.currentVideoTrack$.pipe(D(r=>r==null?void 0:r.quality)).subscribe(new Z("quality")),this.info.currentBuffer$.subscribe(new Z("buffer")),e.isBuffering$.subscribe(new Z("isBuffering"))].forEach(r=>this.subscription.add(r)),ei("codecs",Pg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||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:Ms.DOM,message:String(a)})})};this.subscription.add(gt(Fu(document,"visibilitychange"),Fu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&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 cj,Observable as dj,Subject as pj,ValueSubject as hj,VideoQuality as fj}from"@vkontakte/videoplayer-shared";var mj=`@vkontakte/videoplayer-core@${nl}`;export{aa as ChromecastState,Ws as HttpConnectionType,dj as Observable,ce as PlaybackState,Bs as Player,mj as SDK_VERSION,pj as Subject,cj as Subscription,Qs as Surface,nl as VERSION,hj as ValueSubject,Et as VideoFormat,fj as VideoQuality};