@vkontakte/videoplayer-core 2.0.124-dev.4a771da1.0 → 2.0.124-dev.6bbb9242.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.124-dev.4a771da1.0
3
- * Mon, 03 Feb 2025 10:59:56 GMT
2
+ * @vkontakte/videoplayer-core v2.0.124-dev.6bbb9242.0
3
+ * Wed, 05 Feb 2025 07:06:19 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-124/doc/
5
5
  */
6
- var zT=Object.create;var io=Object.defineProperty,KT=Object.defineProperties,XT=Object.getOwnPropertyDescriptor,JT=Object.getOwnPropertyDescriptors,ZT=Object.getOwnPropertyNames,gs=Object.getOwnPropertySymbols,eI=Object.getPrototypeOf,ao=Object.prototype.hasOwnProperty,ad=Object.prototype.propertyIsEnumerable;var tI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,id=(a,e,t)=>e in a?io(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,I=(a,e)=>{for(var t in e||(e={}))ao.call(e,t)&&id(a,t,e[t]);if(gs)for(var t of gs(e))ad.call(e,t)&&id(a,t,e[t]);return a},$=(a,e)=>KT(a,JT(e));var sd=(a,e)=>{var t={};for(var r in a)ao.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&gs)for(var r of gs(a))e.indexOf(r)<0&&ad.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var rI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ZT(e))!ao.call(a,i)&&i!==t&&io(a,i,{get:()=>e[i],enumerable:!(r=XT(e,i))||r.enumerable});return a};var O=(a,e,t)=>(t=a!=null?zT(eI(a)):{},rI(e||!a||!a.__esModule?io(t,"default",{value:a,enumerable:!0}):t,a));var w=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),vs=function(a,e){this[0]=a,this[1]=e},ae=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof vs,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[tI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var re=m((oo,od)=>{"use strict";var Ti=function(a){return a&&a.Math===Math&&a};od.exports=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof global=="object"&&global)||Ti(typeof oo=="object"&&oo)||function(){return this}()||Function("return this")()});var pe=m((LC,ud)=>{"use strict";ud.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ii=m((MC,ld)=>{"use strict";var iI=pe();ld.exports=!iI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var uo=m((DC,hd)=>{"use strict";var aI=Ii(),pd=Function.prototype,cd=pd.apply,dd=pd.call;hd.exports=typeof Reflect=="object"&&Reflect.apply||(aI?dd.bind(cd):function(){return dd.apply(cd,arguments)})});var ne=m((CC,bd)=>{"use strict";var fd=Ii(),md=Function.prototype,lo=md.call,sI=fd&&md.bind.bind(lo,lo);bd.exports=fd?sI:function(a){return function(){return lo.apply(a,arguments)}}});var ir=m((BC,vd)=>{"use strict";var gd=ne(),nI=gd({}.toString),oI=gd("".slice);vd.exports=function(a){return oI(nI(a),8,-1)}});var co=m((VC,Sd)=>{"use strict";var uI=ir(),lI=ne();Sd.exports=function(a){if(uI(a)==="Function")return lI(a)}});var ee=m((OC,yd)=>{"use strict";var po=typeof document=="object"&&document.all;yd.exports=typeof po=="undefined"&&po!==void 0?function(a){return typeof a=="function"||a===po}:function(a){return typeof a=="function"}});var Me=m((_C,Td)=>{"use strict";var cI=pe();Td.exports=!cI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var De=m((NC,Id)=>{"use strict";var dI=Ii(),ys=Function.prototype.call;Id.exports=dI?ys.bind(ys):function(){return ys.apply(ys,arguments)}});var ho=m(Pd=>{"use strict";var Ed={}.propertyIsEnumerable,xd=Object.getOwnPropertyDescriptor,pI=xd&&!Ed.call({1:2},1);Pd.f=pI?function(e){var t=xd(this,e);return!!t&&t.enumerable}:Ed});var Ei=m((qC,wd)=>{"use strict";wd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var kd=m((UC,Ad)=>{"use strict";var hI=ne(),fI=pe(),mI=ir(),fo=Object,bI=hI("".split);Ad.exports=fI(function(){return!fo("z").propertyIsEnumerable(0)})?function(a){return mI(a)==="String"?bI(a,""):fo(a)}:fo});var Dr=m((HC,Rd)=>{"use strict";Rd.exports=function(a){return a==null}});var Mt=m((jC,$d)=>{"use strict";var gI=Dr(),vI=TypeError;$d.exports=function(a){if(gI(a))throw new vI("Can't call method on "+a);return a}});var ar=m((GC,Ld)=>{"use strict";var SI=kd(),yI=Mt();Ld.exports=function(a){return SI(yI(a))}});var Ce=m((QC,Md)=>{"use strict";var TI=ee();Md.exports=function(a){return typeof a=="object"?a!==null:TI(a)}});var Cr=m((WC,Dd)=>{"use strict";Dd.exports={}});var pt=m((YC,Bd)=>{"use strict";var mo=Cr(),bo=re(),II=ee(),Cd=function(a){return II(a)?a:void 0};Bd.exports=function(a,e){return arguments.length<2?Cd(mo[a])||Cd(bo[a]):mo[a]&&mo[a][e]||bo[a]&&bo[a][e]}});var xi=m((zC,Vd)=>{"use strict";var EI=ne();Vd.exports=EI({}.isPrototypeOf)});var sr=m((KC,Nd)=>{"use strict";var xI=re(),Od=xI.navigator,_d=Od&&Od.userAgent;Nd.exports=_d?String(_d):""});var vo=m((XC,Gd)=>{"use strict";var jd=re(),go=sr(),Fd=jd.process,qd=jd.Deno,Ud=Fd&&Fd.versions||qd&&qd.version,Hd=Ud&&Ud.v8,Ye,Ts;Hd&&(Ye=Hd.split("."),Ts=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!Ts&&go&&(Ye=go.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=go.match(/Chrome\/(\d+)/),Ye&&(Ts=+Ye[1])));Gd.exports=Ts});var So=m((JC,Wd)=>{"use strict";var Qd=vo(),PI=pe(),wI=re(),AI=wI.String;Wd.exports=!!Object.getOwnPropertySymbols&&!PI(function(){var a=Symbol("symbol detection");return!AI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Qd&&Qd<41})});var yo=m((ZC,Yd)=>{"use strict";var kI=So();Yd.exports=kI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var To=m((eB,zd)=>{"use strict";var RI=pt(),$I=ee(),LI=xi(),MI=yo(),DI=Object;zd.exports=MI?function(a){return typeof a=="symbol"}:function(a){var e=RI("Symbol");return $I(e)&&LI(e.prototype,DI(a))}});var Pi=m((tB,Kd)=>{"use strict";var CI=String;Kd.exports=function(a){try{return CI(a)}catch(e){return"Object"}}});var st=m((rB,Xd)=>{"use strict";var BI=ee(),VI=Pi(),OI=TypeError;Xd.exports=function(a){if(BI(a))return a;throw new OI(VI(a)+" is not a function")}});var wi=m((iB,Jd)=>{"use strict";var _I=st(),NI=Dr();Jd.exports=function(a,e){var t=a[e];return NI(t)?void 0:_I(t)}});var ep=m((aB,Zd)=>{"use strict";var Io=De(),Eo=ee(),xo=Ce(),FI=TypeError;Zd.exports=function(a,e){var t,r;if(e==="string"&&Eo(t=a.toString)&&!xo(r=Io(t,a))||Eo(t=a.valueOf)&&!xo(r=Io(t,a))||e!=="string"&&Eo(t=a.toString)&&!xo(r=Io(t,a)))return r;throw new FI("Can't convert object to primitive value")}});var ze=m((sB,tp)=>{"use strict";tp.exports=!0});var ap=m((nB,ip)=>{"use strict";var rp=re(),qI=Object.defineProperty;ip.exports=function(a,e){try{qI(rp,a,{value:e,configurable:!0,writable:!0})}catch(t){rp[a]=e}return e}});var Ai=m((oB,op)=>{"use strict";var UI=ze(),HI=re(),jI=ap(),sp="__core-js_shared__",np=op.exports=HI[sp]||jI(sp,{});(np.versions||(np.versions=[])).push({version:"3.38.0",mode:UI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Po=m((uB,lp)=>{"use strict";var up=Ai();lp.exports=function(a,e){return up[a]||(up[a]=e||{})}});var Br=m((lB,cp)=>{"use strict";var GI=Mt(),QI=Object;cp.exports=function(a){return QI(GI(a))}});var Ke=m((cB,dp)=>{"use strict";var WI=ne(),YI=Br(),zI=WI({}.hasOwnProperty);dp.exports=Object.hasOwn||function(e,t){return zI(YI(e),t)}});var wo=m((dB,pp)=>{"use strict";var KI=ne(),XI=0,JI=Math.random(),ZI=KI(1 .toString);pp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+ZI(++XI+JI,36)}});var he=m((pB,fp)=>{"use strict";var eE=re(),tE=Po(),hp=Ke(),rE=wo(),iE=So(),aE=yo(),Vr=eE.Symbol,Ao=tE("wks"),sE=aE?Vr.for||Vr:Vr&&Vr.withoutSetter||rE;fp.exports=function(a){return hp(Ao,a)||(Ao[a]=iE&&hp(Vr,a)?Vr[a]:sE("Symbol."+a)),Ao[a]}});var vp=m((hB,gp)=>{"use strict";var nE=De(),mp=Ce(),bp=To(),oE=wi(),uE=ep(),lE=he(),cE=TypeError,dE=lE("toPrimitive");gp.exports=function(a,e){if(!mp(a)||bp(a))return a;var t=oE(a,dE),r;if(t){if(e===void 0&&(e="default"),r=nE(t,a,e),!mp(r)||bp(r))return r;throw new cE("Can't convert object to primitive value")}return e===void 0&&(e="number"),uE(a,e)}});var ko=m((fB,Sp)=>{"use strict";var pE=vp(),hE=To();Sp.exports=function(a){var e=pE(a,"string");return hE(e)?e:e+""}});var Is=m((mB,Tp)=>{"use strict";var fE=re(),yp=Ce(),Ro=fE.document,mE=yp(Ro)&&yp(Ro.createElement);Tp.exports=function(a){return mE?Ro.createElement(a):{}}});var $o=m((bB,Ip)=>{"use strict";var bE=Me(),gE=pe(),vE=Is();Ip.exports=!bE&&!gE(function(){return Object.defineProperty(vE("div"),"a",{get:function(){return 7}}).a!==7})});var Pp=m(xp=>{"use strict";var SE=Me(),yE=De(),TE=ho(),IE=Ei(),EE=ar(),xE=ko(),PE=Ke(),wE=$o(),Ep=Object.getOwnPropertyDescriptor;xp.f=SE?Ep:function(e,t){if(e=EE(e),t=xE(t),wE)try{return Ep(e,t)}catch(r){}if(PE(e,t))return IE(!yE(TE.f,e,t),e[t])}});var Lo=m((vB,wp)=>{"use strict";var AE=pe(),kE=ee(),RE=/#|\.prototype\./,ki=function(a,e){var t=LE[$E(a)];return t===DE?!0:t===ME?!1:kE(e)?AE(e):!!e},$E=ki.normalize=function(a){return String(a).replace(RE,".").toLowerCase()},LE=ki.data={},ME=ki.NATIVE="N",DE=ki.POLYFILL="P";wp.exports=ki});var Or=m((SB,kp)=>{"use strict";var Ap=co(),CE=st(),BE=Ii(),VE=Ap(Ap.bind);kp.exports=function(a,e){return CE(a),e===void 0?a:BE?VE(a,e):function(){return a.apply(e,arguments)}}});var Mo=m((yB,Rp)=>{"use strict";var OE=Me(),_E=pe();Rp.exports=OE&&_E(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=m((TB,$p)=>{"use strict";var NE=Ce(),FE=String,qE=TypeError;$p.exports=function(a){if(NE(a))return a;throw new qE(FE(a)+" is not an object")}});var nr=m(Mp=>{"use strict";var UE=Me(),HE=$o(),jE=Mo(),Es=nt(),Lp=ko(),GE=TypeError,Do=Object.defineProperty,QE=Object.getOwnPropertyDescriptor,Co="enumerable",Bo="configurable",Vo="writable";Mp.f=UE?jE?function(e,t,r){if(Es(e),t=Lp(t),Es(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Vo in r&&!r[Vo]){var i=QE(e,t);i&&i[Vo]&&(e[t]=r.value,r={configurable:Bo in r?r[Bo]:i[Bo],enumerable:Co in r?r[Co]:i[Co],writable:!1})}return Do(e,t,r)}:Do:function(e,t,r){if(Es(e),t=Lp(t),Es(r),HE)try{return Do(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new GE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=m((EB,Dp)=>{"use strict";var WE=Me(),YE=nr(),zE=Ei();Dp.exports=WE?function(a,e,t){return YE.f(a,e,zE(1,t))}:function(a,e,t){return a[e]=t,a}});var se=m((xB,Bp)=>{"use strict";var Ri=re(),KE=uo(),XE=co(),JE=ee(),ZE=Pp().f,ex=Lo(),Nr=Cr(),tx=Or(),Fr=_r(),Cp=Ke();Ai();var rx=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return KE(a,this,arguments)};return e.prototype=a.prototype,e};Bp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Ri:i?Ri[t]:Ri[t]&&Ri[t].prototype,o=r?Nr:Nr[t]||Fr(Nr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,v;for(p in e)l=ex(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Cp(n,p),f=o[p],c&&(a.dontCallGetSet?(v=ZE(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=tx(h,Ri):a.wrap&&c?g=rx(h):s&&JE(h)?g=XE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Fr(g,"sham",!0),Fr(o,p,g),s&&(d=t+"Prototype",Cp(Nr,d)||Fr(Nr,d,{}),Fr(Nr[d],p,h),a.real&&u&&(l||!u[p])&&Fr(u,p,h)))}});var Op=m((PB,Vp)=>{"use strict";var ix=Math.ceil,ax=Math.floor;Vp.exports=Math.trunc||function(e){var t=+e;return(t>0?ax:ix)(t)}});var $i=m((wB,_p)=>{"use strict";var sx=Op();_p.exports=function(a){var e=+a;return e!==e||e===0?0:sx(e)}});var Fp=m((AB,Np)=>{"use strict";var nx=$i(),ox=Math.max,ux=Math.min;Np.exports=function(a,e){var t=nx(a);return t<0?ox(t+e,0):ux(t,e)}});var Oo=m((kB,qp)=>{"use strict";var lx=$i(),cx=Math.min;qp.exports=function(a){var e=lx(a);return e>0?cx(e,9007199254740991):0}});var qr=m((RB,Up)=>{"use strict";var dx=Oo();Up.exports=function(a){return dx(a.length)}});var _o=m(($B,jp)=>{"use strict";var px=ar(),hx=Fp(),fx=qr(),Hp=function(a){return function(e,t,r){var i=px(e),s=fx(i);if(s===0)return!a&&-1;var n=hx(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};jp.exports={includes:Hp(!0),indexOf:Hp(!1)}});var Li=m((LB,Gp)=>{"use strict";Gp.exports=function(){}});var Qp=m(()=>{"use strict";var mx=se(),bx=_o().includes,gx=pe(),vx=Li(),Sx=gx(function(){return!Array(1).includes()});mx({target:"Array",proto:!0,forced:Sx},{includes:function(e){return bx(this,e,arguments.length>1?arguments[1]:void 0)}});vx("includes")});var Dt=m((CB,Wp)=>{"use strict";var yx=pt();Wp.exports=yx});var zp=m((BB,Yp)=>{"use strict";Qp();var Tx=Dt();Yp.exports=Tx("Array","includes")});var Xp=m((VB,Kp)=>{"use strict";var Ix=zp();Kp.exports=Ix});var Xe=m((OB,Jp)=>{"use strict";var Ex=Xp();Jp.exports=Ex});var ws=m((zB,nh)=>{"use strict";var Lx=Po(),Mx=wo(),sh=Lx("keys");nh.exports=function(a){return sh[a]||(sh[a]=Mx(a))}});var uh=m((KB,oh)=>{"use strict";var Dx=pe();oh.exports=!Dx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var As=m((XB,ch)=>{"use strict";var Cx=Ke(),Bx=ee(),Vx=Br(),Ox=ws(),_x=uh(),lh=Ox("IE_PROTO"),qo=Object,Nx=qo.prototype;ch.exports=_x?qo.getPrototypeOf:function(a){var e=Vx(a);if(Cx(e,lh))return e[lh];var t=e.constructor;return Bx(t)&&e instanceof t?t.prototype:e instanceof qo?Nx:null}});var ks=m((JB,dh)=>{"use strict";dh.exports={}});var fh=m((ZB,hh)=>{"use strict";var Fx=ne(),Uo=Ke(),qx=ar(),Ux=_o().indexOf,Hx=ks(),ph=Fx([].push);hh.exports=function(a,e){var t=qx(a),r=0,i=[],s;for(s in t)!Uo(Hx,s)&&Uo(t,s)&&ph(i,s);for(;e.length>r;)Uo(t,s=e[r++])&&(~Ux(i,s)||ph(i,s));return i}});var Ho=m((eV,mh)=>{"use strict";mh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var jo=m((tV,bh)=>{"use strict";var jx=fh(),Gx=Ho();bh.exports=Object.keys||function(e){return jx(e,Gx)}});var Go=m((rV,Th)=>{"use strict";var vh=Me(),Qx=pe(),Sh=ne(),Wx=As(),Yx=jo(),zx=ar(),Kx=ho().f,yh=Sh(Kx),Xx=Sh([].push),Jx=vh&&Qx(function(){var a=Object.create(null);return a[2]=2,!yh(a,2)}),gh=function(a){return function(e){for(var t=zx(e),r=Yx(t),i=Jx&&Wx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!vh||(i?u in t:yh(t,u)))&&Xx(o,a?[u,t[u]]:t[u]);return o}};Th.exports={entries:gh(!0),values:gh(!1)}});var Ih=m(()=>{"use strict";var Zx=se(),eP=Go().entries;Zx({target:"Object",stat:!0},{entries:function(e){return eP(e)}})});var xh=m((sV,Eh)=>{"use strict";Ih();var tP=Cr();Eh.exports=tP.Object.entries});var wh=m((nV,Ph)=>{"use strict";var rP=xh();Ph.exports=rP});var Ur=m((oV,Ah)=>{"use strict";var iP=wh();Ah.exports=iP});var or=m((uV,kh)=>{"use strict";kh.exports={}});var Lh=m((lV,$h)=>{"use strict";var aP=re(),sP=ee(),Rh=aP.WeakMap;$h.exports=sP(Rh)&&/native code/.test(String(Rh))});var zo=m((cV,Ch)=>{"use strict";var nP=Lh(),Dh=re(),oP=Ce(),uP=_r(),Qo=Ke(),Wo=Ai(),lP=ws(),cP=ks(),Mh="Object already initialized",Yo=Dh.TypeError,dP=Dh.WeakMap,Rs,Mi,$s,pP=function(a){return $s(a)?Mi(a):Rs(a,{})},hP=function(a){return function(e){var t;if(!oP(e)||(t=Mi(e)).type!==a)throw new Yo("Incompatible receiver, "+a+" required");return t}};nP||Wo.state?(Je=Wo.state||(Wo.state=new dP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,Rs=function(a,e){if(Je.has(a))throw new Yo(Mh);return e.facade=a,Je.set(a,e),e},Mi=function(a){return Je.get(a)||{}},$s=function(a){return Je.has(a)}):(ur=lP("state"),cP[ur]=!0,Rs=function(a,e){if(Qo(a,ur))throw new Yo(Mh);return e.facade=a,uP(a,ur,e),e},Mi=function(a){return Qo(a,ur)?a[ur]:{}},$s=function(a){return Qo(a,ur)});var Je,ur;Ch.exports={set:Rs,get:Mi,has:$s,enforce:pP,getterFor:hP}});var Jo=m((dV,Vh)=>{"use strict";var Ko=Me(),fP=Ke(),Bh=Function.prototype,mP=Ko&&Object.getOwnPropertyDescriptor,Xo=fP(Bh,"name"),bP=Xo&&function(){}.name==="something",gP=Xo&&(!Ko||Ko&&mP(Bh,"name").configurable);Vh.exports={EXISTS:Xo,PROPER:bP,CONFIGURABLE:gP}});var _h=m(Oh=>{"use strict";var vP=Me(),SP=Mo(),yP=nr(),TP=nt(),IP=ar(),EP=jo();Oh.f=vP&&!SP?Object.defineProperties:function(e,t){TP(e);for(var r=IP(t),i=EP(t),s=i.length,n=0,o;s>n;)yP.f(e,o=i[n++],r[o]);return e}});var Zo=m((hV,Nh)=>{"use strict";var xP=pt();Nh.exports=xP("document","documentElement")});var iu=m((fV,Qh)=>{"use strict";var PP=nt(),wP=_h(),Fh=Ho(),AP=ks(),kP=Zo(),RP=Is(),$P=ws(),qh=">",Uh="<",tu="prototype",ru="script",jh=$P("IE_PROTO"),eu=function(){},Gh=function(a){return Uh+ru+qh+a+Uh+"/"+ru+qh},Hh=function(a){a.write(Gh("")),a.close();var e=a.parentWindow.Object;return a=null,e},LP=function(){var a=RP("iframe"),e="java"+ru+":",t;return a.style.display="none",kP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Gh("document.F=Object")),t.close(),t.F},Ls,Ms=function(){try{Ls=new ActiveXObject("htmlfile")}catch(e){}Ms=typeof document!="undefined"?document.domain&&Ls?Hh(Ls):LP():Hh(Ls);for(var a=Fh.length;a--;)delete Ms[tu][Fh[a]];return Ms()};AP[jh]=!0;Qh.exports=Object.create||function(e,t){var r;return e!==null?(eu[tu]=PP(e),r=new eu,eu[tu]=null,r[jh]=e):r=Ms(),t===void 0?r:wP.f(r,t)}});var Hr=m((mV,Wh)=>{"use strict";var MP=_r();Wh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:MP(a,e,t),a}});var ou=m((bV,Kh)=>{"use strict";var DP=pe(),CP=ee(),BP=Ce(),VP=iu(),Yh=As(),OP=Hr(),_P=he(),NP=ze(),nu=_P("iterator"),zh=!1,ht,au,su;[].keys&&(su=[].keys(),"next"in su?(au=Yh(Yh(su)),au!==Object.prototype&&(ht=au)):zh=!0);var FP=!BP(ht)||DP(function(){var a={};return ht[nu].call(a)!==a});FP?ht={}:NP&&(ht=VP(ht));CP(ht[nu])||OP(ht,nu,function(){return this});Kh.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:zh}});var Ds=m((gV,Jh)=>{"use strict";var qP=he(),UP=qP("toStringTag"),Xh={};Xh[UP]="z";Jh.exports=String(Xh)==="[object z]"});var Di=m((vV,Zh)=>{"use strict";var HP=Ds(),jP=ee(),Cs=ir(),GP=he(),QP=GP("toStringTag"),WP=Object,YP=Cs(function(){return arguments}())==="Arguments",zP=function(a,e){try{return a[e]}catch(t){}};Zh.exports=HP?Cs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=zP(e=WP(a),QP))=="string"?t:YP?Cs(e):(r=Cs(e))==="Object"&&jP(e.callee)?"Arguments":r}});var tf=m((SV,ef)=>{"use strict";var KP=Ds(),XP=Di();ef.exports=KP?{}.toString:function(){return"[object "+XP(this)+"]"}});var Ci=m((yV,af)=>{"use strict";var JP=Ds(),ZP=nr().f,ew=_r(),tw=Ke(),rw=tf(),iw=he(),rf=iw("toStringTag");af.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(tw(i,rf)||ZP(i,rf,{configurable:!0,value:e}),r&&!JP&&ew(i,"toString",rw))}});var nf=m((TV,sf)=>{"use strict";var aw=ou().IteratorPrototype,sw=iu(),nw=Ei(),ow=Ci(),uw=or(),lw=function(){return this};sf.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=sw(aw,{next:nw(+!r,t)}),ow(a,i,!1,!0),uw[i]=lw,a}});var uf=m((IV,of)=>{"use strict";var cw=ne(),dw=st();of.exports=function(a,e,t){try{return cw(dw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var cf=m((EV,lf)=>{"use strict";var pw=Ce();lf.exports=function(a){return pw(a)||a===null}});var pf=m((xV,df)=>{"use strict";var hw=cf(),fw=String,mw=TypeError;df.exports=function(a){if(hw(a))return a;throw new mw("Can't set "+fw(a)+" as a prototype")}});var uu=m((PV,hf)=>{"use strict";var bw=uf(),gw=Ce(),vw=Mt(),Sw=pf();hf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=bw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return vw(i),Sw(s),gw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var xf=m((wV,Ef)=>{"use strict";var yw=se(),Tw=De(),Bs=ze(),Tf=Jo(),Iw=ee(),Ew=nf(),ff=As(),mf=uu(),xw=Ci(),Pw=_r(),lu=Hr(),ww=he(),bf=or(),If=ou(),Aw=Tf.PROPER,kw=Tf.CONFIGURABLE,gf=If.IteratorPrototype,Vs=If.BUGGY_SAFARI_ITERATORS,Bi=ww("iterator"),vf="keys",Vi="values",Sf="entries",yf=function(){return this};Ef.exports=function(a,e,t,r,i,s,n){Ew(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Vs&&v&&v in c)return c[v];switch(v){case vf:return function(){return new t(this,v)};case Vi:return function(){return new t(this,v)};case Sf:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Bi]||c["@@iterator"]||i&&c[i],p=!Vs&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=ff(h.call(new a)),f!==Object.prototype&&f.next&&(!Bs&&ff(f)!==gf&&(mf?mf(f,gf):Iw(f[Bi])||lu(f,Bi,yf)),xw(f,u,!0,!0),Bs&&(bf[u]=yf))),Aw&&i===Vi&&d&&d.name!==Vi&&(!Bs&&kw?Pw(c,"name",Vi):(l=!0,p=function(){return Tw(d,this)})),i)if(b={values:o(Vi),keys:s?p:o(vf),entries:o(Sf)},n)for(g in b)(Vs||l||!(g in c))&&lu(c,g,b[g]);else yw({target:e,proto:!0,forced:Vs||l},b);return(!Bs||n)&&c[Bi]!==p&&lu(c,Bi,p,{name:i}),bf[e]=p,b}});var wf=m((AV,Pf)=>{"use strict";Pf.exports=function(a,e){return{value:a,done:e}}});var du=m((kV,Lf)=>{"use strict";var Rw=ar(),cu=Li(),Af=or(),Rf=zo(),$w=nr().f,Lw=xf(),Os=wf(),Mw=ze(),Dw=Me(),$f="Array Iterator",Cw=Rf.set,Bw=Rf.getterFor($f);Lf.exports=Lw(Array,"Array",function(a,e){Cw(this,{type:$f,target:Rw(a),index:0,kind:e})},function(){var a=Bw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Os(void 0,!0);switch(a.kind){case"keys":return Os(t,!1);case"values":return Os(e[t],!1)}return Os([t,e[t]],!1)},"values");var kf=Af.Arguments=Af.Array;cu("keys");cu("values");cu("entries");if(!Mw&&Dw&&kf.name!=="values")try{$w(kf,"name",{value:"values"})}catch(a){}});var Df=m((RV,Mf)=>{"use strict";var Vw=he(),Ow=or(),_w=Vw("iterator"),Nw=Array.prototype;Mf.exports=function(a){return a!==void 0&&(Ow.Array===a||Nw[_w]===a)}});var pu=m(($V,Bf)=>{"use strict";var Fw=Di(),Cf=wi(),qw=Dr(),Uw=or(),Hw=he(),jw=Hw("iterator");Bf.exports=function(a){if(!qw(a))return Cf(a,jw)||Cf(a,"@@iterator")||Uw[Fw(a)]}});var Of=m((LV,Vf)=>{"use strict";var Gw=De(),Qw=st(),Ww=nt(),Yw=Pi(),zw=pu(),Kw=TypeError;Vf.exports=function(a,e){var t=arguments.length<2?zw(a):e;if(Qw(t))return Ww(Gw(t,a));throw new Kw(Yw(a)+" is not iterable")}});var Ff=m((MV,Nf)=>{"use strict";var Xw=De(),_f=nt(),Jw=wi();Nf.exports=function(a,e,t){var r,i;_f(a);try{if(r=Jw(a,"return"),!r){if(e==="throw")throw t;return t}r=Xw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return _f(r),t}});var Ns=m((DV,jf)=>{"use strict";var Zw=Or(),eA=De(),tA=nt(),rA=Pi(),iA=Df(),aA=qr(),qf=xi(),sA=Of(),nA=pu(),Uf=Ff(),oA=TypeError,_s=function(a,e){this.stopped=a,this.result=e},Hf=_s.prototype;jf.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Zw(e,r),l,c,d,p,h,f,b,g=function(S){return l&&Uf(l,"normal",S),new _s(!0,S)},v=function(S){return i?(tA(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=nA(a),!c)throw new oA(rA(a)+" is not iterable");if(iA(c)){for(d=0,p=aA(a);p>d;d++)if(h=v(a[d]),h&&qf(Hf,h))return h;return new _s(!1)}l=sA(a,c)}for(f=s?a.next:l.next;!(b=eA(f,l)).done;){try{h=v(b.value)}catch(S){Uf(l,"throw",S)}if(typeof h=="object"&&h&&qf(Hf,h))return h}return new _s(!1)}});var Qf=m((CV,Gf)=>{"use strict";var uA=Me(),lA=nr(),cA=Ei();Gf.exports=function(a,e,t){uA?lA.f(a,e,cA(0,t)):a[e]=t}});var Wf=m(()=>{"use strict";var dA=se(),pA=Ns(),hA=Qf();dA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return pA(e,function(r,i){hA(t,r,i)},{AS_ENTRIES:!0}),t}})});var zf=m((OV,Yf)=>{"use strict";du();Wf();var fA=Cr();Yf.exports=fA.Object.fromEntries});var Xf=m((_V,Kf)=>{"use strict";Kf.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 Zf=m(()=>{"use strict";du();var mA=Xf(),bA=re(),gA=Ci(),Jf=or();for(Fs in mA)gA(bA[Fs],Fs),Jf[Fs]=Jf.Array;var Fs});var tm=m((qV,em)=>{"use strict";var vA=zf();Zf();em.exports=vA});var hu=m((UV,rm)=>{"use strict";var SA=tm();rm.exports=SA});var im=m(()=>{"use strict"});var fu=m((GV,am)=>{"use strict";var Oi=re(),yA=sr(),TA=ir(),qs=function(a){return yA.slice(0,a.length)===a};am.exports=function(){return qs("Bun/")?"BUN":qs("Cloudflare-Workers")?"CLOUDFLARE":qs("Deno/")?"DENO":qs("Node.js/")?"NODE":Oi.Bun&&typeof Bun.version=="string"?"BUN":Oi.Deno&&typeof Deno.version=="object"?"DENO":TA(Oi.process)==="process"?"NODE":Oi.window&&Oi.document?"BROWSER":"REST"}()});var Us=m((QV,sm)=>{"use strict";var IA=fu();sm.exports=IA==="NODE"});var om=m((WV,nm)=>{"use strict";var EA=nr();nm.exports=function(a,e,t){return EA.f(a,e,t)}});var cm=m((YV,lm)=>{"use strict";var xA=pt(),PA=om(),wA=he(),AA=Me(),um=wA("species");lm.exports=function(a){var e=xA(a);AA&&e&&!e[um]&&PA(e,um,{configurable:!0,get:function(){return this}})}});var pm=m((zV,dm)=>{"use strict";var kA=xi(),RA=TypeError;dm.exports=function(a,e){if(kA(e,a))return a;throw new RA("Incorrect invocation")}});var bu=m((KV,hm)=>{"use strict";var $A=ne(),LA=ee(),mu=Ai(),MA=$A(Function.toString);LA(mu.inspectSource)||(mu.inspectSource=function(a){return MA(a)});hm.exports=mu.inspectSource});var vu=m((XV,vm)=>{"use strict";var DA=ne(),CA=pe(),fm=ee(),BA=Di(),VA=pt(),OA=bu(),mm=function(){},bm=VA("Reflect","construct"),gu=/^\s*(?:class|function)\b/,_A=DA(gu.exec),NA=!gu.test(mm),_i=function(e){if(!fm(e))return!1;try{return bm(mm,[],e),!0}catch(t){return!1}},gm=function(e){if(!fm(e))return!1;switch(BA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return NA||!!_A(gu,OA(e))}catch(t){return!0}};gm.sham=!0;vm.exports=!bm||CA(function(){var a;return _i(_i.call)||!_i(Object)||!_i(function(){a=!0})||a})?gm:_i});var ym=m((JV,Sm)=>{"use strict";var FA=vu(),qA=Pi(),UA=TypeError;Sm.exports=function(a){if(FA(a))return a;throw new UA(qA(a)+" is not a constructor")}});var Su=m((ZV,Im)=>{"use strict";var Tm=nt(),HA=ym(),jA=Dr(),GA=he(),QA=GA("species");Im.exports=function(a,e){var t=Tm(a).constructor,r;return t===void 0||jA(r=Tm(t)[QA])?e:HA(r)}});var xm=m((eO,Em)=>{"use strict";var WA=ne();Em.exports=WA([].slice)});var wm=m((tO,Pm)=>{"use strict";var YA=TypeError;Pm.exports=function(a,e){if(a<e)throw new YA("Not enough arguments");return a}});var yu=m((rO,Am)=>{"use strict";var zA=sr();Am.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(zA)});var Ru=m((iO,Vm)=>{"use strict";var Be=re(),KA=uo(),XA=Or(),km=ee(),JA=Ke(),Bm=pe(),Rm=Zo(),ZA=xm(),$m=Is(),ek=wm(),tk=yu(),rk=Us(),wu=Be.setImmediate,Au=Be.clearImmediate,ik=Be.process,Tu=Be.Dispatch,ak=Be.Function,Lm=Be.MessageChannel,sk=Be.String,Iu=0,Ni={},Mm="onreadystatechange",Fi,lr,Eu,xu;Bm(function(){Fi=Be.location});var ku=function(a){if(JA(Ni,a)){var e=Ni[a];delete Ni[a],e()}},Pu=function(a){return function(){ku(a)}},Dm=function(a){ku(a.data)},Cm=function(a){Be.postMessage(sk(a),Fi.protocol+"//"+Fi.host)};(!wu||!Au)&&(wu=function(e){ek(arguments.length,1);var t=km(e)?e:ak(e),r=ZA(arguments,1);return Ni[++Iu]=function(){KA(t,void 0,r)},lr(Iu),Iu},Au=function(e){delete Ni[e]},rk?lr=function(a){ik.nextTick(Pu(a))}:Tu&&Tu.now?lr=function(a){Tu.now(Pu(a))}:Lm&&!tk?(Eu=new Lm,xu=Eu.port2,Eu.port1.onmessage=Dm,lr=XA(xu.postMessage,xu)):Be.addEventListener&&km(Be.postMessage)&&!Be.importScripts&&Fi&&Fi.protocol!=="file:"&&!Bm(Cm)?(lr=Cm,Be.addEventListener("message",Dm,!1)):Mm in $m("script")?lr=function(a){Rm.appendChild($m("script"))[Mm]=function(){Rm.removeChild(this),ku(a)}}:lr=function(a){setTimeout(Pu(a),0)});Vm.exports={set:wu,clear:Au}});var Nm=m((aO,_m)=>{"use strict";var Om=re(),nk=Me(),ok=Object.getOwnPropertyDescriptor;_m.exports=function(a){if(!nk)return Om[a];var e=ok(Om,a);return e&&e.value}});var $u=m((sO,qm)=>{"use strict";var Fm=function(){this.head=null,this.tail=null};Fm.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};qm.exports=Fm});var Hm=m((nO,Um)=>{"use strict";var uk=sr();Um.exports=/ipad|iphone|ipod/i.test(uk)&&typeof Pebble!="undefined"});var Gm=m((oO,jm)=>{"use strict";var lk=sr();jm.exports=/web0s(?!.*chrome)/i.test(lk)});var Jm=m((uO,Xm)=>{"use strict";var Gr=re(),ck=Nm(),Qm=Or(),Lu=Ru().set,dk=$u(),pk=yu(),hk=Hm(),fk=Gm(),Mu=Us(),Wm=Gr.MutationObserver||Gr.WebKitMutationObserver,Ym=Gr.document,zm=Gr.process,Hs=Gr.Promise,Bu=ck("queueMicrotask"),jr,Du,Cu,js,Km;Bu||(qi=new dk,Ui=function(){var a,e;for(Mu&&(a=zm.domain)&&a.exit();e=qi.get();)try{e()}catch(t){throw qi.head&&jr(),t}a&&a.enter()},!pk&&!Mu&&!fk&&Wm&&Ym?(Du=!0,Cu=Ym.createTextNode(""),new Wm(Ui).observe(Cu,{characterData:!0}),jr=function(){Cu.data=Du=!Du}):!hk&&Hs&&Hs.resolve?(js=Hs.resolve(void 0),js.constructor=Hs,Km=Qm(js.then,js),jr=function(){Km(Ui)}):Mu?jr=function(){zm.nextTick(Ui)}:(Lu=Qm(Lu,Gr),jr=function(){Lu(Ui)}),Bu=function(a){qi.head||jr(),qi.add(a)});var qi,Ui;Xm.exports=Bu});var eb=m((lO,Zm)=>{"use strict";Zm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Gs=m((cO,tb)=>{"use strict";tb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var cr=m((dO,rb)=>{"use strict";var mk=re();rb.exports=mk.Promise});var Qr=m((pO,nb)=>{"use strict";var bk=re(),Hi=cr(),gk=ee(),vk=Lo(),Sk=bu(),yk=he(),ib=fu(),Tk=ze(),Vu=vo(),ab=Hi&&Hi.prototype,Ik=yk("species"),Ou=!1,sb=gk(bk.PromiseRejectionEvent),Ek=vk("Promise",function(){var a=Sk(Hi),e=a!==String(Hi);if(!e&&Vu===66||Tk&&!(ab.catch&&ab.finally))return!0;if(!Vu||Vu<51||!/native code/.test(a)){var t=new Hi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Ik]=r,Ou=t.then(function(){})instanceof r,!Ou)return!0}return!e&&(ib==="BROWSER"||ib==="DENO")&&!sb});nb.exports={CONSTRUCTOR:Ek,REJECTION_EVENT:sb,SUBCLASSING:Ou}});var Wr=m((hO,ub)=>{"use strict";var ob=st(),xk=TypeError,Pk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new xk("Bad Promise constructor");e=r,t=i}),this.resolve=ob(e),this.reject=ob(t)};ub.exports.f=function(a){return new Pk(a)}});var Ab=m(()=>{"use strict";var wk=se(),Ak=ze(),zs=Us(),Ct=re(),Xr=De(),lb=Hr(),cb=uu(),kk=Ci(),Rk=cm(),$k=st(),Ys=ee(),Lk=Ce(),Mk=pm(),Dk=Su(),mb=Ru().set,Uu=Jm(),Ck=eb(),Bk=Gs(),Vk=$u(),bb=zo(),Ks=cr(),Hu=Qr(),gb=Wr(),Xs="Promise",vb=Hu.CONSTRUCTOR,Ok=Hu.REJECTION_EVENT,_k=Hu.SUBCLASSING,_u=bb.getterFor(Xs),Nk=bb.set,Yr=Ks&&Ks.prototype,dr=Ks,Qs=Yr,Sb=Ct.TypeError,Nu=Ct.document,ju=Ct.process,Fu=gb.f,Fk=Fu,qk=!!(Nu&&Nu.createEvent&&Ct.dispatchEvent),yb="unhandledrejection",Uk="rejectionhandled",db=0,Tb=1,Hk=2,Gu=1,Ib=2,Ws,pb,jk,hb,Eb=function(a){var e;return Lk(a)&&Ys(e=a.then)?e:!1},xb=function(a,e){var t=e.value,r=e.state===Tb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Ib&&Qk(e),e.rejection=Gu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Sb("Promise-chain cycle")):(l=Eb(u))?Xr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Pb=function(a,e){a.notified||(a.notified=!0,Uu(function(){for(var t=a.reactions,r;r=t.get();)xb(r,a);a.notified=!1,e&&!a.rejection&&Gk(a)}))},wb=function(a,e,t){var r,i;qk?(r=Nu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Ct.dispatchEvent(r)):r={promise:e,reason:t},!Ok&&(i=Ct["on"+a])?i(r):a===yb&&Ck("Unhandled promise rejection",t)},Gk=function(a){Xr(mb,Ct,function(){var e=a.facade,t=a.value,r=fb(a),i;if(r&&(i=Bk(function(){zs?ju.emit("unhandledRejection",t,e):wb(yb,e,t)}),a.rejection=zs||fb(a)?Ib:Gu,i.error))throw i.value})},fb=function(a){return a.rejection!==Gu&&!a.parent},Qk=function(a){Xr(mb,Ct,function(){var e=a.facade;zs?ju.emit("rejectionHandled",e):wb(Uk,e,a.value)})},zr=function(a,e,t){return function(r){a(e,r,t)}},Kr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Hk,Pb(a,!0))},qu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Sb("Promise can't be resolved itself");var r=Eb(e);r?Uu(function(){var i={done:!1};try{Xr(r,e,zr(qu,i,a),zr(Kr,i,a))}catch(s){Kr(i,s,a)}}):(a.value=e,a.state=Tb,Pb(a,!1))}catch(i){Kr({done:!1},i,a)}}};if(vb&&(dr=function(e){Mk(this,Qs),$k(e),Xr(Ws,this);var t=_u(this);try{e(zr(qu,t),zr(Kr,t))}catch(r){Kr(t,r)}},Qs=dr.prototype,Ws=function(e){Nk(this,{type:Xs,done:!1,notified:!1,parent:!1,reactions:new Vk,rejection:!1,state:db,value:void 0})},Ws.prototype=lb(Qs,"then",function(e,t){var r=_u(this),i=Fu(Dk(this,dr));return r.parent=!0,i.ok=Ys(e)?e:!0,i.fail=Ys(t)&&t,i.domain=zs?ju.domain:void 0,r.state===db?r.reactions.add(i):Uu(function(){xb(i,r)}),i.promise}),pb=function(){var a=new Ws,e=_u(a);this.promise=a,this.resolve=zr(qu,e),this.reject=zr(Kr,e)},gb.f=Fu=function(a){return a===dr||a===jk?new pb(a):Fk(a)},!Ak&&Ys(Ks)&&Yr!==Object.prototype)){hb=Yr.then,_k||lb(Yr,"then",function(e,t){var r=this;return new dr(function(i,s){Xr(hb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Yr.constructor}catch(a){}cb&&cb(Yr,Qs)}wk({global:!0,constructor:!0,wrap:!0,forced:vb},{Promise:dr});kk(dr,Xs,!1,!0);Rk(Xs)});var Mb=m((bO,Lb)=>{"use strict";var Wk=he(),Rb=Wk("iterator"),$b=!1;try{kb=0,Qu={next:function(){return{done:!!kb++}},return:function(){$b=!0}},Qu[Rb]=function(){return this},Array.from(Qu,function(){throw 2})}catch(a){}var kb,Qu;Lb.exports=function(a,e){try{if(!e&&!$b)return!1}catch(i){return!1}var t=!1;try{var r={};r[Rb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Wu=m((gO,Db)=>{"use strict";var Yk=cr(),zk=Mb(),Kk=Qr().CONSTRUCTOR;Db.exports=Kk||!zk(function(a){Yk.all(a).then(void 0,function(){})})});var Cb=m(()=>{"use strict";var Xk=se(),Jk=De(),Zk=st(),eR=Wr(),tR=Gs(),rR=Ns(),iR=Wu();Xk({target:"Promise",stat:!0,forced:iR},{all:function(e){var t=this,r=eR.f(t),i=r.resolve,s=r.reject,n=tR(function(){var o=Zk(t.resolve),u=[],l=0,c=1;rR(e,function(d){var p=l++,h=!1;c++,Jk(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Vb=m(()=>{"use strict";var aR=se(),sR=ze(),nR=Qr().CONSTRUCTOR,zu=cr(),oR=pt(),uR=ee(),lR=Hr(),Bb=zu&&zu.prototype;aR({target:"Promise",proto:!0,forced:nR,real:!0},{catch:function(a){return this.then(void 0,a)}});!sR&&uR(zu)&&(Yu=oR("Promise").prototype.catch,Bb.catch!==Yu&&lR(Bb,"catch",Yu,{unsafe:!0}));var Yu});var Ob=m(()=>{"use strict";var cR=se(),dR=De(),pR=st(),hR=Wr(),fR=Gs(),mR=Ns(),bR=Wu();cR({target:"Promise",stat:!0,forced:bR},{race:function(e){var t=this,r=hR.f(t),i=r.reject,s=fR(function(){var n=pR(t.resolve);mR(e,function(o){dR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var _b=m(()=>{"use strict";var gR=se(),vR=Wr(),SR=Qr().CONSTRUCTOR;gR({target:"Promise",stat:!0,forced:SR},{reject:function(e){var t=vR.f(this),r=t.reject;return r(e),t.promise}})});var Ku=m((wO,Nb)=>{"use strict";var yR=nt(),TR=Ce(),IR=Wr();Nb.exports=function(a,e){if(yR(a),TR(e)&&e.constructor===a)return e;var t=IR.f(a),r=t.resolve;return r(e),t.promise}});var Ub=m(()=>{"use strict";var ER=se(),xR=pt(),Fb=ze(),PR=cr(),qb=Qr().CONSTRUCTOR,wR=Ku(),AR=xR("Promise"),kR=Fb&&!qb;ER({target:"Promise",stat:!0,forced:Fb||qb},{resolve:function(e){return wR(kR&&this===AR?PR:this,e)}})});var Hb=m(()=>{"use strict";Ab();Cb();Vb();Ob();_b();Ub()});var Wb=m(()=>{"use strict";var RR=se(),$R=ze(),Js=cr(),LR=pe(),Gb=pt(),Qb=ee(),MR=Su(),jb=Ku(),DR=Hr(),Ju=Js&&Js.prototype,CR=!!Js&&LR(function(){Ju.finally.call({then:function(){}},function(){})});RR({target:"Promise",proto:!0,real:!0,forced:CR},{finally:function(a){var e=MR(this,Gb("Promise")),t=Qb(a);return this.then(t?function(r){return jb(e,a()).then(function(){return r})}:a,t?function(r){return jb(e,a()).then(function(){throw r})}:a)}});!$R&&Qb(Js)&&(Xu=Gb("Promise").prototype.finally,Ju.finally!==Xu&&DR(Ju,"finally",Xu,{unsafe:!0}));var Xu});var zb=m((DO,Yb)=>{"use strict";im();Hb();Wb();var BR=Dt();Yb.exports=BR("Promise","finally")});var Xb=m((CO,Kb)=>{"use strict";var VR=zb();Kb.exports=VR});var Zs=m((BO,Jb)=>{"use strict";var OR=Xb();Jb.exports=OR});var dg=m(()=>{"use strict";var XR=se(),JR=Go().values;XR({target:"Object",stat:!0},{values:function(e){return JR(e)}})});var hg=m((S_,pg)=>{"use strict";dg();var ZR=Cr();pg.exports=ZR.Object.values});var mg=m((y_,fg)=>{"use strict";var e$=hg();fg.exports=e$});var Zr=m((T_,bg)=>{"use strict";var t$=mg();bg.exports=t$});var Rg=m(()=>{"use strict";var g$=se(),v$=Br(),S$=qr(),y$=$i(),T$=Li();g$({target:"Array",proto:!0},{at:function(e){var t=v$(this),r=S$(t),i=y$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});T$("at")});var Lg=m((z_,$g)=>{"use strict";Rg();var I$=Dt();$g.exports=I$("Array","at")});var Dg=m((K_,Mg)=>{"use strict";var E$=Lg();Mg.exports=E$});var ti=m((X_,Cg)=>{"use strict";var x$=Dg();Cg.exports=x$});var Tl=m((wF,cv)=>{"use strict";var sL=ir();cv.exports=Array.isArray||function(e){return sL(e)==="Array"}});var pv=m((AF,dv)=>{"use strict";var nL=TypeError,oL=9007199254740991;dv.exports=function(a){if(a>oL)throw nL("Maximum allowed index exceeded");return a}});var mv=m((kF,fv)=>{"use strict";var uL=Tl(),lL=qr(),cL=pv(),dL=Or(),hv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?dL(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&uL(d)?(p=lL(d),u=hv(a,e,d,p,u,s-1)-1):(cL(u+1),a[u]=d),u++),l++;return u};fv.exports=hv});var Sv=m((RF,vv)=>{"use strict";var bv=Tl(),pL=vu(),hL=Ce(),fL=he(),mL=fL("species"),gv=Array;vv.exports=function(a){var e;return bv(a)&&(e=a.constructor,pL(e)&&(e===gv||bv(e.prototype))?e=void 0:hL(e)&&(e=e[mL],e===null&&(e=void 0))),e===void 0?gv:e}});var Tv=m(($F,yv)=>{"use strict";var bL=Sv();yv.exports=function(a,e){return new(bL(a))(e===0?0:e)}});var Iv=m(()=>{"use strict";var gL=se(),vL=mv(),SL=st(),yL=Br(),TL=qr(),IL=Tv();gL({target:"Array",proto:!0},{flatMap:function(e){var t=yL(this),r=TL(t),i;return SL(e),i=IL(t,0),i.length=vL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Ev=m(()=>{"use strict";var EL=Li();EL("flatMap")});var Pv=m((BF,xv)=>{"use strict";Iv();Ev();var xL=Dt();xv.exports=xL("Array","flatMap")});var Av=m((VF,wv)=>{"use strict";var PL=Pv();wv.exports=PL});var Il=m((OF,kv)=>{"use strict";var wL=Av();kv.exports=wL});var aa=m((YF,Yv)=>{"use strict";var CL=Di(),BL=String;Yv.exports=function(a){if(CL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return BL(a)}});var xl=m((zF,zv)=>{"use strict";zv.exports=`
7
- \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Jv=m((KF,Xv)=>{"use strict";var VL=ne(),OL=Mt(),_L=aa(),wl=xl(),Kv=VL("".replace),NL=RegExp("^["+wl+"]+"),FL=RegExp("(^|[^"+wl+"])["+wl+"]+$"),Pl=function(a){return function(e){var t=_L(OL(e));return a&1&&(t=Kv(t,NL,"")),a&2&&(t=Kv(t,FL,"$1")),t}};Xv.exports={start:Pl(1),end:Pl(2),trim:Pl(3)}});var rS=m((XF,tS)=>{"use strict";var qL=Jo().PROPER,UL=pe(),Zv=xl(),eS="\u200B\x85\u180E";tS.exports=function(a){return UL(function(){return!!Zv[a]()||eS[a]()!==eS||qL&&Zv[a].name!==a})}});var Al=m((JF,iS)=>{"use strict";var HL=Jv().start,jL=rS();iS.exports=jL("trimStart")?function(){return HL(this)}:"".trimStart});var sS=m(()=>{"use strict";var GL=se(),aS=Al();GL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==aS},{trimLeft:aS})});var oS=m(()=>{"use strict";sS();var QL=se(),nS=Al();QL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==nS},{trimStart:nS})});var lS=m((iq,uS)=>{"use strict";oS();var WL=Dt();uS.exports=WL("String","trimLeft")});var dS=m((aq,cS)=>{"use strict";var YL=lS();cS.exports=YL});var hS=m((sq,pS)=>{"use strict";var zL=dS();pS.exports=zL});var RS=m(()=>{"use strict"});var $S=m(()=>{"use strict"});var MS=m((q1,LS)=>{"use strict";var vM=Ce(),SM=ir(),yM=he(),TM=yM("match");LS.exports=function(a){var e;return vM(a)&&((e=a[TM])!==void 0?!!e:SM(a)==="RegExp")}});var CS=m((U1,DS)=>{"use strict";var IM=nt();DS.exports=function(){var a=IM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var OS=m((H1,VS)=>{"use strict";var EM=De(),xM=Ke(),PM=xi(),wM=CS(),BS=RegExp.prototype;VS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in BS)&&!xM(a,"flags")&&PM(BS,a)?EM(wM,a):e}});var NS=m((j1,_S)=>{"use strict";var Vl=ne(),AM=Br(),kM=Math.floor,Cl=Vl("".charAt),RM=Vl("".replace),Bl=Vl("".slice),$M=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,LM=/\$([$&'`]|\d{1,2})/g;_S.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=LM;return i!==void 0&&(i=AM(i),u=$M),RM(s,u,function(l,c){var d;switch(Cl(c,0)){case"$":return"$";case"&":return a;case"`":return Bl(e,0,t);case"'":return Bl(e,n);case"<":d=i[Bl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=kM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Cl(c,1):r[h-1]+Cl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var US=m(()=>{"use strict";var MM=se(),DM=De(),_l=ne(),FS=Mt(),CM=ee(),BM=Dr(),VM=MS(),oi=aa(),OM=wi(),_M=OS(),NM=NS(),FM=he(),qM=ze(),UM=FM("replace"),HM=TypeError,Ol=_l("".indexOf),jM=_l("".replace),qS=_l("".slice),GM=Math.max;MM({target:"String",proto:!0},{replaceAll:function(e,t){var r=FS(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!BM(e)){if(i=VM(e),i&&(s=oi(FS(_M(e))),!~Ol(s,"g")))throw new HM("`.replaceAll` does not allow non-global regexes");if(n=OM(e,UM),n)return DM(n,e,r,t);if(qM&&i)return jM(oi(r),e,t)}for(o=oi(r),u=oi(e),l=CM(t),l||(t=oi(t)),c=u.length,d=GM(1,c),p=Ol(o,u);p!==-1;)h=l?oi(t(u,p,o)):NM(u,o,p,[],void 0,t),b+=qS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Ol(o,u,p+d);return f<o.length&&(b+=qS(o,f)),b}})});var jS=m((W1,HS)=>{"use strict";RS();$S();US();var QM=Dt();HS.exports=QM("String","replaceAll")});var QS=m((Y1,GS)=>{"use strict";var WM=jS();GS.exports=WM});var YS=m((z1,WS)=>{"use strict";var YM=QS();WS.exports=YM});var KS=m((K1,zS)=>{"use strict";var zM=$i(),KM=aa(),XM=Mt(),JM=RangeError;zS.exports=function(e){var t=KM(XM(this)),r="",i=zM(e);if(i<0||i===1/0)throw new JM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var ty=m((X1,ey)=>{"use strict";var ZS=ne(),ZM=Oo(),XS=aa(),eD=KS(),tD=Mt(),rD=ZS(eD),iD=ZS("".slice),aD=Math.ceil,JS=function(a){return function(e,t,r){var i=XS(tD(e)),s=ZM(t),n=i.length,o=r===void 0?" ":XS(r),u,l;return s<=n||o===""?i:(u=s-n,l=rD(o,aD(u/o.length)),l.length>u&&(l=iD(l,0,u)),a?i+l:l+i)}};ey.exports={start:JS(!1),end:JS(!0)}});var iy=m((J1,ry)=>{"use strict";var sD=sr();ry.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(sD)});var ay=m(()=>{"use strict";var nD=se(),oD=ty().start,uD=iy();nD({target:"String",proto:!0,forced:uD},{padStart:function(e){return oD(this,e,arguments.length>1?arguments[1]:void 0)}})});var ny=m((tH,sy)=>{"use strict";ay();var lD=Dt();sy.exports=lD("String","padStart")});var uy=m((rH,oy)=>{"use strict";var cD=ny();oy.exports=cD});var cy=m((iH,ly)=>{"use strict";var dD=uy();ly.exports=dD});var nd="2.0.124-dev.4a771da1.0";var Ie=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Ie||{}),Lt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(Lt||{});var Ss=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ss||{}),so=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(so||{});var no=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(no||{});var qT=O(Xe(),1);import{assertNever as ah,assertNonNullable as xx,isNonNullable as xs,ValueSubject as No,Subject as Px,Subscription as wx,merge as Ax,observableFrom as kx,fromEvent as eh,map as th,tap as rh,filterChanged as Rx,isNullable as Fo,ErrorCategory as ih}from"@vkontakte/videoplayer-shared/es2015";var Zp=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var Ps=class{constructor(e){this.connection$=new No(void 0);this.castState$=new No("NOT_AVAILABLE");this.errorEvent$=new Px;this.realCastState$=new No("NOT_AVAILABLE");this.subscription=new wx;this.isDestroyed=!1;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=xs((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Zp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ih.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){xs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Fo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Fo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(eh(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return ah(i.sessionState)}})).add(Ax(eh(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(rh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),th(i=>i.castState)),kx([r.getCastState()])).pipe(Rx(),th($x),rh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=xs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();xx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Fo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?xs(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:ih.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},$x=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return ah(a)}};var bc=O(Xe(),1),TT=O(Ur(),1),IT=O(hu(),1);var ug=O(Zs(),1);import{assertNever as Zb}from"@vkontakte/videoplayer-shared/es2015";var fe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Zb(t)}return a},en=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Zb(e)}};var P=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as _R,Subject as tn,merge as eg}from"@vkontakte/videoplayer-shared/es2015";var C=class{constructor(e){this.transitionStarted$=new tn;this.transitionEnded$=new tn;this.transitionUpdated$=new tn;this.forceChanged$=new tn;this.stateChangeStarted$=eg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=eg(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||_R(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 NR}from"@vkontakte/videoplayer-shared/es2015";var tg=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return NR(a)}};import{assertNever as Jr,assertNonNullable as pr,debounce as rg,ErrorCategory as ig,fromEvent as hr,isNonNullable as ag,map as sg,merge as ng,observableFrom as FR,Subject as qR,Subscription as Zu,timeout as UR,getHighestQuality as HR}from"@vkontakte/videoplayer-shared/es2015";var jR=5,GR=5,QR=500,og=7e3,ji=class{constructor(e){this.subscription=new Zu;this.loadMediaTimeoutSubscription=new Zu;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Jr(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:Jr(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:Jr(e)}break}default:Jr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(tg(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 Zu;this.subscription.add(e),this.subscription.add(ng(this.videoState.stateChangeStarted$.pipe(sg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(sg(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new qR;e.add(i.pipe(rg(QR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(hr(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)>jR)&&i.next(o),s=o})),e.add(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<GR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:Jr(n)}}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=ng(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,FR(["init"])).pipe(rg(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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"),P(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"),P(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"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];pr(c);let d=HR(Object.keys(c));pr(d);let p=c[d];pr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];pr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];pr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];pr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];pr(c),r=fe(c.url),i="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:ig.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Jr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return ag(o)&&(n.metadata.title=o),ag(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(UR(og).subscribe(()=>s(`timeout(${og})`)))});(0,ug.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ig.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Sl=O(Xe(),1);import{clearVideoElement as cg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as WR}from"@vkontakte/videoplayer-shared/es2015";var lg=a=>{try{a.pause(),a.playbackRate=0,WR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as YR,Subscription as zR}from"@vkontakte/videoplayer-shared/es2015";var el=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)}},tl=window.WeakMap?new WeakMap:new el,rl=window.WeakMap?new WeakMap:new Map,KR=(a,e=20)=>{let t=0;return YR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?cg(t):(t=document.createElement("video"),a.appendChild(t)),tl.set(t,r);let i=new zR;return i.add(KR(t,e)),rl.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},xe=a=>{let e=rl.get(a);e==null||e.unsubscribe(),rl.delete(a);let t=tl.get(a);tl.delete(a),t?cg(a):lg(a)};var al=O(Zr(),1);import{assertNonNullable as Gi,isNonNullable as ut,isNullable as a$,fromEvent as ei,merge as gg,observableFrom as vg,filterChanged as Sg,map as Qi,Subject as yg,Subscription as s$,ValueSubject as n$,ErrorCategory as o$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as il,isNullable as r$,Subscription as i$}from"@vkontakte/videoplayer-shared/es2015";var rn=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=r$(i),l=new i$;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>rn(e,()=>a.loop,r=>{il(r)&&(a.loop=r)},{onError:t}),Pe=(a,e,t,r)=>rn(e,()=>({muted:a.muted,volume:a.volume}),i=>{il(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Fe=(a,e,t,r)=>rn(e,()=>a.playbackRate,i=>{il(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Bt=rn;var u$=a=>["__",a.language,a.label].join("|"),l$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},sl=class a{constructor(e){this.available$=new yg;this.current$=new n$(void 0);this.error$=new yg;this.subscription=new s$;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:o$.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(Bt(t.internalTextTracks,()=>(0,al.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Qi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Bt(t.externalTextTracks,()=>(0,al.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Qi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Bt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Bt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Gi(this.video);let{textTracks:e}=this.video;this.subscription.add(ei(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(gg(ei(e,"addtrack"),ei(e,"removetrack"),vg(["init"])).pipe(Qi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Sg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(gg(ei(e,"change"),vg(["init"])).pipe(Qi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Qi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Sg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(ei(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;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),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(ei(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;ut(t.align)&&(i.align=t.align),ut(t.position)&&(i.position=t.position),ut(t.size)&&(i.size=t.size),ut(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Gi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:u$(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){Gi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(a$(e)||!l$(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Gi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Gi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},qe=sl;var mt=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 Tg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},nl=a=>{let e=Tg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Ig=a=>{let e=Tg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ue,map as Vt,merge as xg,filterChanged as d$,isNonNullable as Pg,Subject as p$,filter as wg,mapTo as Ag,combine as h$,once as f$,ErrorCategory as m$,ValueSubject as kg,clientChecker as b$}from"@vkontakte/videoplayer-shared/es2015";var c$=3,Eg=(a,e,t=c$)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var we=a=>{let e=T=>Ue(a,T).pipe(Ag(void 0)),r=xg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Ue(a,T))).pipe(Vt(T=>T.type==="ended"?a.readyState<2:a.readyState<3),d$()),i=xg(Ue(a,"progress"),Ue(a,"timeupdate")).pipe(Vt(()=>Eg(a.buffered,a.currentTime))),s=b$.isSafari?h$({play:e("play").pipe(f$()),playing:e("playing")}).pipe(Ag(void 0)):e("playing"),n=Ue(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=Ue(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=Ue(a,"error").pipe(wg(()=>!!(a.error||a.played.length)),Vt(()=>{var x;let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:m$.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(x=a.error)!=null?x:void 0}})),l=Ue(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new p$,d=.3,p;l.subscribe(T=>{a.loop&&Pg(p)&&Pg(T)&&p>=a.duration-d&&T<=d&&c.next(p),p=T});let h=e("pause").pipe(wg(()=>!a.error&&p!==a.duration)),f=Ue(a,"enterpictureinpicture"),b=Ue(a,"leavepictureinpicture"),g=new kg(Ig(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new kg(nl(a));return Ue(a,"fullscreenchange").pipe(Vt(()=>nl(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ue(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as Ot}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Ot.Q_144P;case"lowest":return Ot.Q_240P;case"low":return Ot.Q_360P;case"sd":case"medium":return Ot.Q_480P;case"hd":case"high":return Ot.Q_720P;case"fullhd":case"full":return Ot.Q_1080P;case"quadhd":case"quad":return Ot.Q_1440P;case"ultrahd":case"ultra":return Ot.Q_2160P}};var Nt=O(ti(),1),qg=O(Xe(),1),an=O(Ur(),1);import{isNonNullable as oe,isNullable as ul,now as Ug,isHigher as ll,isHigherOrEqual as cl,isInvariantQuality as _g,isLower as Ng,isLowerOrEqual as dl,videoSizeToQuality as P$,assertNotEmptyArray as Hg,assertNonNullable as w$}from"@vkontakte/videoplayer-shared/es2015";var ol=!1,bt={},Bg=a=>{ol=a},Vg=()=>{bt={}},Og=a=>{a(bt)},Wi=(a,e)=>{var t;ol&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var r,i;if(!ol)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};var A$=new ve("best_bitrate"),jg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var pl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Yi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ug()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Gg='Assertion "ABR Tracks is empty array" failed',sn=(a,e,t,r)=>{var u;let i=[...e].sort(pl(1)),s=[...t].sort(pl(1)),n=s.filter(l=>oe(l.bitrate)&&oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,qg.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},Fg=a=>"quality"in a,Qg=(a,e,t,r)=>{var n;let i=oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Ug()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Fg(o)?"video":"audio",l=Fg(o)?o.quality:o.bitrate;return e({message:`
6
+ var zT=Object.create;var io=Object.defineProperty,KT=Object.defineProperties,XT=Object.getOwnPropertyDescriptor,JT=Object.getOwnPropertyDescriptors,ZT=Object.getOwnPropertyNames,gs=Object.getOwnPropertySymbols,eI=Object.getPrototypeOf,ao=Object.prototype.hasOwnProperty,ad=Object.prototype.propertyIsEnumerable;var tI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,id=(a,e,t)=>e in a?io(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,I=(a,e)=>{for(var t in e||(e={}))ao.call(e,t)&&id(a,t,e[t]);if(gs)for(var t of gs(e))ad.call(e,t)&&id(a,t,e[t]);return a},$=(a,e)=>KT(a,JT(e));var sd=(a,e)=>{var t={};for(var r in a)ao.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&gs)for(var r of gs(a))e.indexOf(r)<0&&ad.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var rI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ZT(e))!ao.call(a,i)&&i!==t&&io(a,i,{get:()=>e[i],enumerable:!(r=XT(e,i))||r.enumerable});return a};var O=(a,e,t)=>(t=a!=null?zT(eI(a)):{},rI(e||!a||!a.__esModule?io(t,"default",{value:a,enumerable:!0}):t,a));var w=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),vs=function(a,e){this[0]=a,this[1]=e},ae=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof vs,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[tI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var re=m((oo,od)=>{"use strict";var Ti=function(a){return a&&a.Math===Math&&a};od.exports=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof global=="object"&&global)||Ti(typeof oo=="object"&&oo)||function(){return this}()||Function("return this")()});var pe=m((L0,ud)=>{"use strict";ud.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ii=m((M0,ld)=>{"use strict";var iI=pe();ld.exports=!iI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var uo=m((D0,hd)=>{"use strict";var aI=Ii(),pd=Function.prototype,cd=pd.apply,dd=pd.call;hd.exports=typeof Reflect=="object"&&Reflect.apply||(aI?dd.bind(cd):function(){return dd.apply(cd,arguments)})});var ne=m((C0,bd)=>{"use strict";var fd=Ii(),md=Function.prototype,lo=md.call,sI=fd&&md.bind.bind(lo,lo);bd.exports=fd?sI:function(a){return function(){return lo.apply(a,arguments)}}});var ir=m((B0,vd)=>{"use strict";var gd=ne(),nI=gd({}.toString),oI=gd("".slice);vd.exports=function(a){return oI(nI(a),8,-1)}});var co=m((V0,Sd)=>{"use strict";var uI=ir(),lI=ne();Sd.exports=function(a){if(uI(a)==="Function")return lI(a)}});var ee=m((O0,yd)=>{"use strict";var po=typeof document=="object"&&document.all;yd.exports=typeof po=="undefined"&&po!==void 0?function(a){return typeof a=="function"||a===po}:function(a){return typeof a=="function"}});var Me=m((_0,Td)=>{"use strict";var cI=pe();Td.exports=!cI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var De=m((N0,Id)=>{"use strict";var dI=Ii(),ys=Function.prototype.call;Id.exports=dI?ys.bind(ys):function(){return ys.apply(ys,arguments)}});var ho=m(Pd=>{"use strict";var Ed={}.propertyIsEnumerable,xd=Object.getOwnPropertyDescriptor,pI=xd&&!Ed.call({1:2},1);Pd.f=pI?function(e){var t=xd(this,e);return!!t&&t.enumerable}:Ed});var Ei=m((q0,wd)=>{"use strict";wd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var kd=m((U0,Ad)=>{"use strict";var hI=ne(),fI=pe(),mI=ir(),fo=Object,bI=hI("".split);Ad.exports=fI(function(){return!fo("z").propertyIsEnumerable(0)})?function(a){return mI(a)==="String"?bI(a,""):fo(a)}:fo});var Dr=m((H0,Rd)=>{"use strict";Rd.exports=function(a){return a==null}});var Mt=m((j0,$d)=>{"use strict";var gI=Dr(),vI=TypeError;$d.exports=function(a){if(gI(a))throw new vI("Can't call method on "+a);return a}});var ar=m((G0,Ld)=>{"use strict";var SI=kd(),yI=Mt();Ld.exports=function(a){return SI(yI(a))}});var Ce=m((Q0,Md)=>{"use strict";var TI=ee();Md.exports=function(a){return typeof a=="object"?a!==null:TI(a)}});var Cr=m((W0,Dd)=>{"use strict";Dd.exports={}});var pt=m((Y0,Bd)=>{"use strict";var mo=Cr(),bo=re(),II=ee(),Cd=function(a){return II(a)?a:void 0};Bd.exports=function(a,e){return arguments.length<2?Cd(mo[a])||Cd(bo[a]):mo[a]&&mo[a][e]||bo[a]&&bo[a][e]}});var xi=m((z0,Vd)=>{"use strict";var EI=ne();Vd.exports=EI({}.isPrototypeOf)});var sr=m((K0,Nd)=>{"use strict";var xI=re(),Od=xI.navigator,_d=Od&&Od.userAgent;Nd.exports=_d?String(_d):""});var vo=m((X0,Gd)=>{"use strict";var jd=re(),go=sr(),Fd=jd.process,qd=jd.Deno,Ud=Fd&&Fd.versions||qd&&qd.version,Hd=Ud&&Ud.v8,Ye,Ts;Hd&&(Ye=Hd.split("."),Ts=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!Ts&&go&&(Ye=go.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=go.match(/Chrome\/(\d+)/),Ye&&(Ts=+Ye[1])));Gd.exports=Ts});var So=m((J0,Wd)=>{"use strict";var Qd=vo(),PI=pe(),wI=re(),AI=wI.String;Wd.exports=!!Object.getOwnPropertySymbols&&!PI(function(){var a=Symbol("symbol detection");return!AI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Qd&&Qd<41})});var yo=m((Z0,Yd)=>{"use strict";var kI=So();Yd.exports=kI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var To=m((eB,zd)=>{"use strict";var RI=pt(),$I=ee(),LI=xi(),MI=yo(),DI=Object;zd.exports=MI?function(a){return typeof a=="symbol"}:function(a){var e=RI("Symbol");return $I(e)&&LI(e.prototype,DI(a))}});var Pi=m((tB,Kd)=>{"use strict";var CI=String;Kd.exports=function(a){try{return CI(a)}catch(e){return"Object"}}});var st=m((rB,Xd)=>{"use strict";var BI=ee(),VI=Pi(),OI=TypeError;Xd.exports=function(a){if(BI(a))return a;throw new OI(VI(a)+" is not a function")}});var wi=m((iB,Jd)=>{"use strict";var _I=st(),NI=Dr();Jd.exports=function(a,e){var t=a[e];return NI(t)?void 0:_I(t)}});var ep=m((aB,Zd)=>{"use strict";var Io=De(),Eo=ee(),xo=Ce(),FI=TypeError;Zd.exports=function(a,e){var t,r;if(e==="string"&&Eo(t=a.toString)&&!xo(r=Io(t,a))||Eo(t=a.valueOf)&&!xo(r=Io(t,a))||e!=="string"&&Eo(t=a.toString)&&!xo(r=Io(t,a)))return r;throw new FI("Can't convert object to primitive value")}});var ze=m((sB,tp)=>{"use strict";tp.exports=!0});var ap=m((nB,ip)=>{"use strict";var rp=re(),qI=Object.defineProperty;ip.exports=function(a,e){try{qI(rp,a,{value:e,configurable:!0,writable:!0})}catch(t){rp[a]=e}return e}});var Ai=m((oB,op)=>{"use strict";var UI=ze(),HI=re(),jI=ap(),sp="__core-js_shared__",np=op.exports=HI[sp]||jI(sp,{});(np.versions||(np.versions=[])).push({version:"3.38.0",mode:UI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Po=m((uB,lp)=>{"use strict";var up=Ai();lp.exports=function(a,e){return up[a]||(up[a]=e||{})}});var Br=m((lB,cp)=>{"use strict";var GI=Mt(),QI=Object;cp.exports=function(a){return QI(GI(a))}});var Ke=m((cB,dp)=>{"use strict";var WI=ne(),YI=Br(),zI=WI({}.hasOwnProperty);dp.exports=Object.hasOwn||function(e,t){return zI(YI(e),t)}});var wo=m((dB,pp)=>{"use strict";var KI=ne(),XI=0,JI=Math.random(),ZI=KI(1 .toString);pp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+ZI(++XI+JI,36)}});var he=m((pB,fp)=>{"use strict";var eE=re(),tE=Po(),hp=Ke(),rE=wo(),iE=So(),aE=yo(),Vr=eE.Symbol,Ao=tE("wks"),sE=aE?Vr.for||Vr:Vr&&Vr.withoutSetter||rE;fp.exports=function(a){return hp(Ao,a)||(Ao[a]=iE&&hp(Vr,a)?Vr[a]:sE("Symbol."+a)),Ao[a]}});var vp=m((hB,gp)=>{"use strict";var nE=De(),mp=Ce(),bp=To(),oE=wi(),uE=ep(),lE=he(),cE=TypeError,dE=lE("toPrimitive");gp.exports=function(a,e){if(!mp(a)||bp(a))return a;var t=oE(a,dE),r;if(t){if(e===void 0&&(e="default"),r=nE(t,a,e),!mp(r)||bp(r))return r;throw new cE("Can't convert object to primitive value")}return e===void 0&&(e="number"),uE(a,e)}});var ko=m((fB,Sp)=>{"use strict";var pE=vp(),hE=To();Sp.exports=function(a){var e=pE(a,"string");return hE(e)?e:e+""}});var Is=m((mB,Tp)=>{"use strict";var fE=re(),yp=Ce(),Ro=fE.document,mE=yp(Ro)&&yp(Ro.createElement);Tp.exports=function(a){return mE?Ro.createElement(a):{}}});var $o=m((bB,Ip)=>{"use strict";var bE=Me(),gE=pe(),vE=Is();Ip.exports=!bE&&!gE(function(){return Object.defineProperty(vE("div"),"a",{get:function(){return 7}}).a!==7})});var Pp=m(xp=>{"use strict";var SE=Me(),yE=De(),TE=ho(),IE=Ei(),EE=ar(),xE=ko(),PE=Ke(),wE=$o(),Ep=Object.getOwnPropertyDescriptor;xp.f=SE?Ep:function(e,t){if(e=EE(e),t=xE(t),wE)try{return Ep(e,t)}catch(r){}if(PE(e,t))return IE(!yE(TE.f,e,t),e[t])}});var Lo=m((vB,wp)=>{"use strict";var AE=pe(),kE=ee(),RE=/#|\.prototype\./,ki=function(a,e){var t=LE[$E(a)];return t===DE?!0:t===ME?!1:kE(e)?AE(e):!!e},$E=ki.normalize=function(a){return String(a).replace(RE,".").toLowerCase()},LE=ki.data={},ME=ki.NATIVE="N",DE=ki.POLYFILL="P";wp.exports=ki});var Or=m((SB,kp)=>{"use strict";var Ap=co(),CE=st(),BE=Ii(),VE=Ap(Ap.bind);kp.exports=function(a,e){return CE(a),e===void 0?a:BE?VE(a,e):function(){return a.apply(e,arguments)}}});var Mo=m((yB,Rp)=>{"use strict";var OE=Me(),_E=pe();Rp.exports=OE&&_E(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=m((TB,$p)=>{"use strict";var NE=Ce(),FE=String,qE=TypeError;$p.exports=function(a){if(NE(a))return a;throw new qE(FE(a)+" is not an object")}});var nr=m(Mp=>{"use strict";var UE=Me(),HE=$o(),jE=Mo(),Es=nt(),Lp=ko(),GE=TypeError,Do=Object.defineProperty,QE=Object.getOwnPropertyDescriptor,Co="enumerable",Bo="configurable",Vo="writable";Mp.f=UE?jE?function(e,t,r){if(Es(e),t=Lp(t),Es(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Vo in r&&!r[Vo]){var i=QE(e,t);i&&i[Vo]&&(e[t]=r.value,r={configurable:Bo in r?r[Bo]:i[Bo],enumerable:Co in r?r[Co]:i[Co],writable:!1})}return Do(e,t,r)}:Do:function(e,t,r){if(Es(e),t=Lp(t),Es(r),HE)try{return Do(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new GE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=m((EB,Dp)=>{"use strict";var WE=Me(),YE=nr(),zE=Ei();Dp.exports=WE?function(a,e,t){return YE.f(a,e,zE(1,t))}:function(a,e,t){return a[e]=t,a}});var se=m((xB,Bp)=>{"use strict";var Ri=re(),KE=uo(),XE=co(),JE=ee(),ZE=Pp().f,ex=Lo(),Nr=Cr(),tx=Or(),Fr=_r(),Cp=Ke();Ai();var rx=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return KE(a,this,arguments)};return e.prototype=a.prototype,e};Bp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Ri:i?Ri[t]:Ri[t]&&Ri[t].prototype,o=r?Nr:Nr[t]||Fr(Nr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,v;for(p in e)l=ex(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Cp(n,p),f=o[p],c&&(a.dontCallGetSet?(v=ZE(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=tx(h,Ri):a.wrap&&c?g=rx(h):s&&JE(h)?g=XE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Fr(g,"sham",!0),Fr(o,p,g),s&&(d=t+"Prototype",Cp(Nr,d)||Fr(Nr,d,{}),Fr(Nr[d],p,h),a.real&&u&&(l||!u[p])&&Fr(u,p,h)))}});var Op=m((PB,Vp)=>{"use strict";var ix=Math.ceil,ax=Math.floor;Vp.exports=Math.trunc||function(e){var t=+e;return(t>0?ax:ix)(t)}});var $i=m((wB,_p)=>{"use strict";var sx=Op();_p.exports=function(a){var e=+a;return e!==e||e===0?0:sx(e)}});var Fp=m((AB,Np)=>{"use strict";var nx=$i(),ox=Math.max,ux=Math.min;Np.exports=function(a,e){var t=nx(a);return t<0?ox(t+e,0):ux(t,e)}});var Oo=m((kB,qp)=>{"use strict";var lx=$i(),cx=Math.min;qp.exports=function(a){var e=lx(a);return e>0?cx(e,9007199254740991):0}});var qr=m((RB,Up)=>{"use strict";var dx=Oo();Up.exports=function(a){return dx(a.length)}});var _o=m(($B,jp)=>{"use strict";var px=ar(),hx=Fp(),fx=qr(),Hp=function(a){return function(e,t,r){var i=px(e),s=fx(i);if(s===0)return!a&&-1;var n=hx(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};jp.exports={includes:Hp(!0),indexOf:Hp(!1)}});var Li=m((LB,Gp)=>{"use strict";Gp.exports=function(){}});var Qp=m(()=>{"use strict";var mx=se(),bx=_o().includes,gx=pe(),vx=Li(),Sx=gx(function(){return!Array(1).includes()});mx({target:"Array",proto:!0,forced:Sx},{includes:function(e){return bx(this,e,arguments.length>1?arguments[1]:void 0)}});vx("includes")});var Dt=m((CB,Wp)=>{"use strict";var yx=pt();Wp.exports=yx});var zp=m((BB,Yp)=>{"use strict";Qp();var Tx=Dt();Yp.exports=Tx("Array","includes")});var Xp=m((VB,Kp)=>{"use strict";var Ix=zp();Kp.exports=Ix});var Xe=m((OB,Jp)=>{"use strict";var Ex=Xp();Jp.exports=Ex});var ws=m((zB,nh)=>{"use strict";var Lx=Po(),Mx=wo(),sh=Lx("keys");nh.exports=function(a){return sh[a]||(sh[a]=Mx(a))}});var uh=m((KB,oh)=>{"use strict";var Dx=pe();oh.exports=!Dx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var As=m((XB,ch)=>{"use strict";var Cx=Ke(),Bx=ee(),Vx=Br(),Ox=ws(),_x=uh(),lh=Ox("IE_PROTO"),qo=Object,Nx=qo.prototype;ch.exports=_x?qo.getPrototypeOf:function(a){var e=Vx(a);if(Cx(e,lh))return e[lh];var t=e.constructor;return Bx(t)&&e instanceof t?t.prototype:e instanceof qo?Nx:null}});var ks=m((JB,dh)=>{"use strict";dh.exports={}});var fh=m((ZB,hh)=>{"use strict";var Fx=ne(),Uo=Ke(),qx=ar(),Ux=_o().indexOf,Hx=ks(),ph=Fx([].push);hh.exports=function(a,e){var t=qx(a),r=0,i=[],s;for(s in t)!Uo(Hx,s)&&Uo(t,s)&&ph(i,s);for(;e.length>r;)Uo(t,s=e[r++])&&(~Ux(i,s)||ph(i,s));return i}});var Ho=m((eV,mh)=>{"use strict";mh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var jo=m((tV,bh)=>{"use strict";var jx=fh(),Gx=Ho();bh.exports=Object.keys||function(e){return jx(e,Gx)}});var Go=m((rV,Th)=>{"use strict";var vh=Me(),Qx=pe(),Sh=ne(),Wx=As(),Yx=jo(),zx=ar(),Kx=ho().f,yh=Sh(Kx),Xx=Sh([].push),Jx=vh&&Qx(function(){var a=Object.create(null);return a[2]=2,!yh(a,2)}),gh=function(a){return function(e){for(var t=zx(e),r=Yx(t),i=Jx&&Wx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!vh||(i?u in t:yh(t,u)))&&Xx(o,a?[u,t[u]]:t[u]);return o}};Th.exports={entries:gh(!0),values:gh(!1)}});var Ih=m(()=>{"use strict";var Zx=se(),eP=Go().entries;Zx({target:"Object",stat:!0},{entries:function(e){return eP(e)}})});var xh=m((sV,Eh)=>{"use strict";Ih();var tP=Cr();Eh.exports=tP.Object.entries});var wh=m((nV,Ph)=>{"use strict";var rP=xh();Ph.exports=rP});var Ur=m((oV,Ah)=>{"use strict";var iP=wh();Ah.exports=iP});var or=m((uV,kh)=>{"use strict";kh.exports={}});var Lh=m((lV,$h)=>{"use strict";var aP=re(),sP=ee(),Rh=aP.WeakMap;$h.exports=sP(Rh)&&/native code/.test(String(Rh))});var zo=m((cV,Ch)=>{"use strict";var nP=Lh(),Dh=re(),oP=Ce(),uP=_r(),Qo=Ke(),Wo=Ai(),lP=ws(),cP=ks(),Mh="Object already initialized",Yo=Dh.TypeError,dP=Dh.WeakMap,Rs,Mi,$s,pP=function(a){return $s(a)?Mi(a):Rs(a,{})},hP=function(a){return function(e){var t;if(!oP(e)||(t=Mi(e)).type!==a)throw new Yo("Incompatible receiver, "+a+" required");return t}};nP||Wo.state?(Je=Wo.state||(Wo.state=new dP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,Rs=function(a,e){if(Je.has(a))throw new Yo(Mh);return e.facade=a,Je.set(a,e),e},Mi=function(a){return Je.get(a)||{}},$s=function(a){return Je.has(a)}):(ur=lP("state"),cP[ur]=!0,Rs=function(a,e){if(Qo(a,ur))throw new Yo(Mh);return e.facade=a,uP(a,ur,e),e},Mi=function(a){return Qo(a,ur)?a[ur]:{}},$s=function(a){return Qo(a,ur)});var Je,ur;Ch.exports={set:Rs,get:Mi,has:$s,enforce:pP,getterFor:hP}});var Jo=m((dV,Vh)=>{"use strict";var Ko=Me(),fP=Ke(),Bh=Function.prototype,mP=Ko&&Object.getOwnPropertyDescriptor,Xo=fP(Bh,"name"),bP=Xo&&function(){}.name==="something",gP=Xo&&(!Ko||Ko&&mP(Bh,"name").configurable);Vh.exports={EXISTS:Xo,PROPER:bP,CONFIGURABLE:gP}});var _h=m(Oh=>{"use strict";var vP=Me(),SP=Mo(),yP=nr(),TP=nt(),IP=ar(),EP=jo();Oh.f=vP&&!SP?Object.defineProperties:function(e,t){TP(e);for(var r=IP(t),i=EP(t),s=i.length,n=0,o;s>n;)yP.f(e,o=i[n++],r[o]);return e}});var Zo=m((hV,Nh)=>{"use strict";var xP=pt();Nh.exports=xP("document","documentElement")});var iu=m((fV,Qh)=>{"use strict";var PP=nt(),wP=_h(),Fh=Ho(),AP=ks(),kP=Zo(),RP=Is(),$P=ws(),qh=">",Uh="<",tu="prototype",ru="script",jh=$P("IE_PROTO"),eu=function(){},Gh=function(a){return Uh+ru+qh+a+Uh+"/"+ru+qh},Hh=function(a){a.write(Gh("")),a.close();var e=a.parentWindow.Object;return a=null,e},LP=function(){var a=RP("iframe"),e="java"+ru+":",t;return a.style.display="none",kP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Gh("document.F=Object")),t.close(),t.F},Ls,Ms=function(){try{Ls=new ActiveXObject("htmlfile")}catch(e){}Ms=typeof document!="undefined"?document.domain&&Ls?Hh(Ls):LP():Hh(Ls);for(var a=Fh.length;a--;)delete Ms[tu][Fh[a]];return Ms()};AP[jh]=!0;Qh.exports=Object.create||function(e,t){var r;return e!==null?(eu[tu]=PP(e),r=new eu,eu[tu]=null,r[jh]=e):r=Ms(),t===void 0?r:wP.f(r,t)}});var Hr=m((mV,Wh)=>{"use strict";var MP=_r();Wh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:MP(a,e,t),a}});var ou=m((bV,Kh)=>{"use strict";var DP=pe(),CP=ee(),BP=Ce(),VP=iu(),Yh=As(),OP=Hr(),_P=he(),NP=ze(),nu=_P("iterator"),zh=!1,ht,au,su;[].keys&&(su=[].keys(),"next"in su?(au=Yh(Yh(su)),au!==Object.prototype&&(ht=au)):zh=!0);var FP=!BP(ht)||DP(function(){var a={};return ht[nu].call(a)!==a});FP?ht={}:NP&&(ht=VP(ht));CP(ht[nu])||OP(ht,nu,function(){return this});Kh.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:zh}});var Ds=m((gV,Jh)=>{"use strict";var qP=he(),UP=qP("toStringTag"),Xh={};Xh[UP]="z";Jh.exports=String(Xh)==="[object z]"});var Di=m((vV,Zh)=>{"use strict";var HP=Ds(),jP=ee(),Cs=ir(),GP=he(),QP=GP("toStringTag"),WP=Object,YP=Cs(function(){return arguments}())==="Arguments",zP=function(a,e){try{return a[e]}catch(t){}};Zh.exports=HP?Cs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=zP(e=WP(a),QP))=="string"?t:YP?Cs(e):(r=Cs(e))==="Object"&&jP(e.callee)?"Arguments":r}});var tf=m((SV,ef)=>{"use strict";var KP=Ds(),XP=Di();ef.exports=KP?{}.toString:function(){return"[object "+XP(this)+"]"}});var Ci=m((yV,af)=>{"use strict";var JP=Ds(),ZP=nr().f,ew=_r(),tw=Ke(),rw=tf(),iw=he(),rf=iw("toStringTag");af.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(tw(i,rf)||ZP(i,rf,{configurable:!0,value:e}),r&&!JP&&ew(i,"toString",rw))}});var nf=m((TV,sf)=>{"use strict";var aw=ou().IteratorPrototype,sw=iu(),nw=Ei(),ow=Ci(),uw=or(),lw=function(){return this};sf.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=sw(aw,{next:nw(+!r,t)}),ow(a,i,!1,!0),uw[i]=lw,a}});var uf=m((IV,of)=>{"use strict";var cw=ne(),dw=st();of.exports=function(a,e,t){try{return cw(dw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var cf=m((EV,lf)=>{"use strict";var pw=Ce();lf.exports=function(a){return pw(a)||a===null}});var pf=m((xV,df)=>{"use strict";var hw=cf(),fw=String,mw=TypeError;df.exports=function(a){if(hw(a))return a;throw new mw("Can't set "+fw(a)+" as a prototype")}});var uu=m((PV,hf)=>{"use strict";var bw=uf(),gw=Ce(),vw=Mt(),Sw=pf();hf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=bw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return vw(i),Sw(s),gw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var xf=m((wV,Ef)=>{"use strict";var yw=se(),Tw=De(),Bs=ze(),Tf=Jo(),Iw=ee(),Ew=nf(),ff=As(),mf=uu(),xw=Ci(),Pw=_r(),lu=Hr(),ww=he(),bf=or(),If=ou(),Aw=Tf.PROPER,kw=Tf.CONFIGURABLE,gf=If.IteratorPrototype,Vs=If.BUGGY_SAFARI_ITERATORS,Bi=ww("iterator"),vf="keys",Vi="values",Sf="entries",yf=function(){return this};Ef.exports=function(a,e,t,r,i,s,n){Ew(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Vs&&v&&v in c)return c[v];switch(v){case vf:return function(){return new t(this,v)};case Vi:return function(){return new t(this,v)};case Sf:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Bi]||c["@@iterator"]||i&&c[i],p=!Vs&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=ff(h.call(new a)),f!==Object.prototype&&f.next&&(!Bs&&ff(f)!==gf&&(mf?mf(f,gf):Iw(f[Bi])||lu(f,Bi,yf)),xw(f,u,!0,!0),Bs&&(bf[u]=yf))),Aw&&i===Vi&&d&&d.name!==Vi&&(!Bs&&kw?Pw(c,"name",Vi):(l=!0,p=function(){return Tw(d,this)})),i)if(b={values:o(Vi),keys:s?p:o(vf),entries:o(Sf)},n)for(g in b)(Vs||l||!(g in c))&&lu(c,g,b[g]);else yw({target:e,proto:!0,forced:Vs||l},b);return(!Bs||n)&&c[Bi]!==p&&lu(c,Bi,p,{name:i}),bf[e]=p,b}});var wf=m((AV,Pf)=>{"use strict";Pf.exports=function(a,e){return{value:a,done:e}}});var du=m((kV,Lf)=>{"use strict";var Rw=ar(),cu=Li(),Af=or(),Rf=zo(),$w=nr().f,Lw=xf(),Os=wf(),Mw=ze(),Dw=Me(),$f="Array Iterator",Cw=Rf.set,Bw=Rf.getterFor($f);Lf.exports=Lw(Array,"Array",function(a,e){Cw(this,{type:$f,target:Rw(a),index:0,kind:e})},function(){var a=Bw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Os(void 0,!0);switch(a.kind){case"keys":return Os(t,!1);case"values":return Os(e[t],!1)}return Os([t,e[t]],!1)},"values");var kf=Af.Arguments=Af.Array;cu("keys");cu("values");cu("entries");if(!Mw&&Dw&&kf.name!=="values")try{$w(kf,"name",{value:"values"})}catch(a){}});var Df=m((RV,Mf)=>{"use strict";var Vw=he(),Ow=or(),_w=Vw("iterator"),Nw=Array.prototype;Mf.exports=function(a){return a!==void 0&&(Ow.Array===a||Nw[_w]===a)}});var pu=m(($V,Bf)=>{"use strict";var Fw=Di(),Cf=wi(),qw=Dr(),Uw=or(),Hw=he(),jw=Hw("iterator");Bf.exports=function(a){if(!qw(a))return Cf(a,jw)||Cf(a,"@@iterator")||Uw[Fw(a)]}});var Of=m((LV,Vf)=>{"use strict";var Gw=De(),Qw=st(),Ww=nt(),Yw=Pi(),zw=pu(),Kw=TypeError;Vf.exports=function(a,e){var t=arguments.length<2?zw(a):e;if(Qw(t))return Ww(Gw(t,a));throw new Kw(Yw(a)+" is not iterable")}});var Ff=m((MV,Nf)=>{"use strict";var Xw=De(),_f=nt(),Jw=wi();Nf.exports=function(a,e,t){var r,i;_f(a);try{if(r=Jw(a,"return"),!r){if(e==="throw")throw t;return t}r=Xw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return _f(r),t}});var Ns=m((DV,jf)=>{"use strict";var Zw=Or(),eA=De(),tA=nt(),rA=Pi(),iA=Df(),aA=qr(),qf=xi(),sA=Of(),nA=pu(),Uf=Ff(),oA=TypeError,_s=function(a,e){this.stopped=a,this.result=e},Hf=_s.prototype;jf.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Zw(e,r),l,c,d,p,h,f,b,g=function(S){return l&&Uf(l,"normal",S),new _s(!0,S)},v=function(S){return i?(tA(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=nA(a),!c)throw new oA(rA(a)+" is not iterable");if(iA(c)){for(d=0,p=aA(a);p>d;d++)if(h=v(a[d]),h&&qf(Hf,h))return h;return new _s(!1)}l=sA(a,c)}for(f=s?a.next:l.next;!(b=eA(f,l)).done;){try{h=v(b.value)}catch(S){Uf(l,"throw",S)}if(typeof h=="object"&&h&&qf(Hf,h))return h}return new _s(!1)}});var Qf=m((CV,Gf)=>{"use strict";var uA=Me(),lA=nr(),cA=Ei();Gf.exports=function(a,e,t){uA?lA.f(a,e,cA(0,t)):a[e]=t}});var Wf=m(()=>{"use strict";var dA=se(),pA=Ns(),hA=Qf();dA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return pA(e,function(r,i){hA(t,r,i)},{AS_ENTRIES:!0}),t}})});var zf=m((OV,Yf)=>{"use strict";du();Wf();var fA=Cr();Yf.exports=fA.Object.fromEntries});var Xf=m((_V,Kf)=>{"use strict";Kf.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 Zf=m(()=>{"use strict";du();var mA=Xf(),bA=re(),gA=Ci(),Jf=or();for(Fs in mA)gA(bA[Fs],Fs),Jf[Fs]=Jf.Array;var Fs});var tm=m((qV,em)=>{"use strict";var vA=zf();Zf();em.exports=vA});var hu=m((UV,rm)=>{"use strict";var SA=tm();rm.exports=SA});var im=m(()=>{"use strict"});var fu=m((GV,am)=>{"use strict";var Oi=re(),yA=sr(),TA=ir(),qs=function(a){return yA.slice(0,a.length)===a};am.exports=function(){return qs("Bun/")?"BUN":qs("Cloudflare-Workers")?"CLOUDFLARE":qs("Deno/")?"DENO":qs("Node.js/")?"NODE":Oi.Bun&&typeof Bun.version=="string"?"BUN":Oi.Deno&&typeof Deno.version=="object"?"DENO":TA(Oi.process)==="process"?"NODE":Oi.window&&Oi.document?"BROWSER":"REST"}()});var Us=m((QV,sm)=>{"use strict";var IA=fu();sm.exports=IA==="NODE"});var om=m((WV,nm)=>{"use strict";var EA=nr();nm.exports=function(a,e,t){return EA.f(a,e,t)}});var cm=m((YV,lm)=>{"use strict";var xA=pt(),PA=om(),wA=he(),AA=Me(),um=wA("species");lm.exports=function(a){var e=xA(a);AA&&e&&!e[um]&&PA(e,um,{configurable:!0,get:function(){return this}})}});var pm=m((zV,dm)=>{"use strict";var kA=xi(),RA=TypeError;dm.exports=function(a,e){if(kA(e,a))return a;throw new RA("Incorrect invocation")}});var bu=m((KV,hm)=>{"use strict";var $A=ne(),LA=ee(),mu=Ai(),MA=$A(Function.toString);LA(mu.inspectSource)||(mu.inspectSource=function(a){return MA(a)});hm.exports=mu.inspectSource});var vu=m((XV,vm)=>{"use strict";var DA=ne(),CA=pe(),fm=ee(),BA=Di(),VA=pt(),OA=bu(),mm=function(){},bm=VA("Reflect","construct"),gu=/^\s*(?:class|function)\b/,_A=DA(gu.exec),NA=!gu.test(mm),_i=function(e){if(!fm(e))return!1;try{return bm(mm,[],e),!0}catch(t){return!1}},gm=function(e){if(!fm(e))return!1;switch(BA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return NA||!!_A(gu,OA(e))}catch(t){return!0}};gm.sham=!0;vm.exports=!bm||CA(function(){var a;return _i(_i.call)||!_i(Object)||!_i(function(){a=!0})||a})?gm:_i});var ym=m((JV,Sm)=>{"use strict";var FA=vu(),qA=Pi(),UA=TypeError;Sm.exports=function(a){if(FA(a))return a;throw new UA(qA(a)+" is not a constructor")}});var Su=m((ZV,Im)=>{"use strict";var Tm=nt(),HA=ym(),jA=Dr(),GA=he(),QA=GA("species");Im.exports=function(a,e){var t=Tm(a).constructor,r;return t===void 0||jA(r=Tm(t)[QA])?e:HA(r)}});var xm=m((eO,Em)=>{"use strict";var WA=ne();Em.exports=WA([].slice)});var wm=m((tO,Pm)=>{"use strict";var YA=TypeError;Pm.exports=function(a,e){if(a<e)throw new YA("Not enough arguments");return a}});var yu=m((rO,Am)=>{"use strict";var zA=sr();Am.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(zA)});var Ru=m((iO,Vm)=>{"use strict";var Be=re(),KA=uo(),XA=Or(),km=ee(),JA=Ke(),Bm=pe(),Rm=Zo(),ZA=xm(),$m=Is(),ek=wm(),tk=yu(),rk=Us(),wu=Be.setImmediate,Au=Be.clearImmediate,ik=Be.process,Tu=Be.Dispatch,ak=Be.Function,Lm=Be.MessageChannel,sk=Be.String,Iu=0,Ni={},Mm="onreadystatechange",Fi,lr,Eu,xu;Bm(function(){Fi=Be.location});var ku=function(a){if(JA(Ni,a)){var e=Ni[a];delete Ni[a],e()}},Pu=function(a){return function(){ku(a)}},Dm=function(a){ku(a.data)},Cm=function(a){Be.postMessage(sk(a),Fi.protocol+"//"+Fi.host)};(!wu||!Au)&&(wu=function(e){ek(arguments.length,1);var t=km(e)?e:ak(e),r=ZA(arguments,1);return Ni[++Iu]=function(){KA(t,void 0,r)},lr(Iu),Iu},Au=function(e){delete Ni[e]},rk?lr=function(a){ik.nextTick(Pu(a))}:Tu&&Tu.now?lr=function(a){Tu.now(Pu(a))}:Lm&&!tk?(Eu=new Lm,xu=Eu.port2,Eu.port1.onmessage=Dm,lr=XA(xu.postMessage,xu)):Be.addEventListener&&km(Be.postMessage)&&!Be.importScripts&&Fi&&Fi.protocol!=="file:"&&!Bm(Cm)?(lr=Cm,Be.addEventListener("message",Dm,!1)):Mm in $m("script")?lr=function(a){Rm.appendChild($m("script"))[Mm]=function(){Rm.removeChild(this),ku(a)}}:lr=function(a){setTimeout(Pu(a),0)});Vm.exports={set:wu,clear:Au}});var Nm=m((aO,_m)=>{"use strict";var Om=re(),nk=Me(),ok=Object.getOwnPropertyDescriptor;_m.exports=function(a){if(!nk)return Om[a];var e=ok(Om,a);return e&&e.value}});var $u=m((sO,qm)=>{"use strict";var Fm=function(){this.head=null,this.tail=null};Fm.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};qm.exports=Fm});var Hm=m((nO,Um)=>{"use strict";var uk=sr();Um.exports=/ipad|iphone|ipod/i.test(uk)&&typeof Pebble!="undefined"});var Gm=m((oO,jm)=>{"use strict";var lk=sr();jm.exports=/web0s(?!.*chrome)/i.test(lk)});var Jm=m((uO,Xm)=>{"use strict";var Gr=re(),ck=Nm(),Qm=Or(),Lu=Ru().set,dk=$u(),pk=yu(),hk=Hm(),fk=Gm(),Mu=Us(),Wm=Gr.MutationObserver||Gr.WebKitMutationObserver,Ym=Gr.document,zm=Gr.process,Hs=Gr.Promise,Bu=ck("queueMicrotask"),jr,Du,Cu,js,Km;Bu||(qi=new dk,Ui=function(){var a,e;for(Mu&&(a=zm.domain)&&a.exit();e=qi.get();)try{e()}catch(t){throw qi.head&&jr(),t}a&&a.enter()},!pk&&!Mu&&!fk&&Wm&&Ym?(Du=!0,Cu=Ym.createTextNode(""),new Wm(Ui).observe(Cu,{characterData:!0}),jr=function(){Cu.data=Du=!Du}):!hk&&Hs&&Hs.resolve?(js=Hs.resolve(void 0),js.constructor=Hs,Km=Qm(js.then,js),jr=function(){Km(Ui)}):Mu?jr=function(){zm.nextTick(Ui)}:(Lu=Qm(Lu,Gr),jr=function(){Lu(Ui)}),Bu=function(a){qi.head||jr(),qi.add(a)});var qi,Ui;Xm.exports=Bu});var eb=m((lO,Zm)=>{"use strict";Zm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Gs=m((cO,tb)=>{"use strict";tb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var cr=m((dO,rb)=>{"use strict";var mk=re();rb.exports=mk.Promise});var Qr=m((pO,nb)=>{"use strict";var bk=re(),Hi=cr(),gk=ee(),vk=Lo(),Sk=bu(),yk=he(),ib=fu(),Tk=ze(),Vu=vo(),ab=Hi&&Hi.prototype,Ik=yk("species"),Ou=!1,sb=gk(bk.PromiseRejectionEvent),Ek=vk("Promise",function(){var a=Sk(Hi),e=a!==String(Hi);if(!e&&Vu===66||Tk&&!(ab.catch&&ab.finally))return!0;if(!Vu||Vu<51||!/native code/.test(a)){var t=new Hi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Ik]=r,Ou=t.then(function(){})instanceof r,!Ou)return!0}return!e&&(ib==="BROWSER"||ib==="DENO")&&!sb});nb.exports={CONSTRUCTOR:Ek,REJECTION_EVENT:sb,SUBCLASSING:Ou}});var Wr=m((hO,ub)=>{"use strict";var ob=st(),xk=TypeError,Pk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new xk("Bad Promise constructor");e=r,t=i}),this.resolve=ob(e),this.reject=ob(t)};ub.exports.f=function(a){return new Pk(a)}});var Ab=m(()=>{"use strict";var wk=se(),Ak=ze(),zs=Us(),Ct=re(),Xr=De(),lb=Hr(),cb=uu(),kk=Ci(),Rk=cm(),$k=st(),Ys=ee(),Lk=Ce(),Mk=pm(),Dk=Su(),mb=Ru().set,Uu=Jm(),Ck=eb(),Bk=Gs(),Vk=$u(),bb=zo(),Ks=cr(),Hu=Qr(),gb=Wr(),Xs="Promise",vb=Hu.CONSTRUCTOR,Ok=Hu.REJECTION_EVENT,_k=Hu.SUBCLASSING,_u=bb.getterFor(Xs),Nk=bb.set,Yr=Ks&&Ks.prototype,dr=Ks,Qs=Yr,Sb=Ct.TypeError,Nu=Ct.document,ju=Ct.process,Fu=gb.f,Fk=Fu,qk=!!(Nu&&Nu.createEvent&&Ct.dispatchEvent),yb="unhandledrejection",Uk="rejectionhandled",db=0,Tb=1,Hk=2,Gu=1,Ib=2,Ws,pb,jk,hb,Eb=function(a){var e;return Lk(a)&&Ys(e=a.then)?e:!1},xb=function(a,e){var t=e.value,r=e.state===Tb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Ib&&Qk(e),e.rejection=Gu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Sb("Promise-chain cycle")):(l=Eb(u))?Xr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Pb=function(a,e){a.notified||(a.notified=!0,Uu(function(){for(var t=a.reactions,r;r=t.get();)xb(r,a);a.notified=!1,e&&!a.rejection&&Gk(a)}))},wb=function(a,e,t){var r,i;qk?(r=Nu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Ct.dispatchEvent(r)):r={promise:e,reason:t},!Ok&&(i=Ct["on"+a])?i(r):a===yb&&Ck("Unhandled promise rejection",t)},Gk=function(a){Xr(mb,Ct,function(){var e=a.facade,t=a.value,r=fb(a),i;if(r&&(i=Bk(function(){zs?ju.emit("unhandledRejection",t,e):wb(yb,e,t)}),a.rejection=zs||fb(a)?Ib:Gu,i.error))throw i.value})},fb=function(a){return a.rejection!==Gu&&!a.parent},Qk=function(a){Xr(mb,Ct,function(){var e=a.facade;zs?ju.emit("rejectionHandled",e):wb(Uk,e,a.value)})},zr=function(a,e,t){return function(r){a(e,r,t)}},Kr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Hk,Pb(a,!0))},qu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Sb("Promise can't be resolved itself");var r=Eb(e);r?Uu(function(){var i={done:!1};try{Xr(r,e,zr(qu,i,a),zr(Kr,i,a))}catch(s){Kr(i,s,a)}}):(a.value=e,a.state=Tb,Pb(a,!1))}catch(i){Kr({done:!1},i,a)}}};if(vb&&(dr=function(e){Mk(this,Qs),$k(e),Xr(Ws,this);var t=_u(this);try{e(zr(qu,t),zr(Kr,t))}catch(r){Kr(t,r)}},Qs=dr.prototype,Ws=function(e){Nk(this,{type:Xs,done:!1,notified:!1,parent:!1,reactions:new Vk,rejection:!1,state:db,value:void 0})},Ws.prototype=lb(Qs,"then",function(e,t){var r=_u(this),i=Fu(Dk(this,dr));return r.parent=!0,i.ok=Ys(e)?e:!0,i.fail=Ys(t)&&t,i.domain=zs?ju.domain:void 0,r.state===db?r.reactions.add(i):Uu(function(){xb(i,r)}),i.promise}),pb=function(){var a=new Ws,e=_u(a);this.promise=a,this.resolve=zr(qu,e),this.reject=zr(Kr,e)},gb.f=Fu=function(a){return a===dr||a===jk?new pb(a):Fk(a)},!Ak&&Ys(Ks)&&Yr!==Object.prototype)){hb=Yr.then,_k||lb(Yr,"then",function(e,t){var r=this;return new dr(function(i,s){Xr(hb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Yr.constructor}catch(a){}cb&&cb(Yr,Qs)}wk({global:!0,constructor:!0,wrap:!0,forced:vb},{Promise:dr});kk(dr,Xs,!1,!0);Rk(Xs)});var Mb=m((bO,Lb)=>{"use strict";var Wk=he(),Rb=Wk("iterator"),$b=!1;try{kb=0,Qu={next:function(){return{done:!!kb++}},return:function(){$b=!0}},Qu[Rb]=function(){return this},Array.from(Qu,function(){throw 2})}catch(a){}var kb,Qu;Lb.exports=function(a,e){try{if(!e&&!$b)return!1}catch(i){return!1}var t=!1;try{var r={};r[Rb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Wu=m((gO,Db)=>{"use strict";var Yk=cr(),zk=Mb(),Kk=Qr().CONSTRUCTOR;Db.exports=Kk||!zk(function(a){Yk.all(a).then(void 0,function(){})})});var Cb=m(()=>{"use strict";var Xk=se(),Jk=De(),Zk=st(),eR=Wr(),tR=Gs(),rR=Ns(),iR=Wu();Xk({target:"Promise",stat:!0,forced:iR},{all:function(e){var t=this,r=eR.f(t),i=r.resolve,s=r.reject,n=tR(function(){var o=Zk(t.resolve),u=[],l=0,c=1;rR(e,function(d){var p=l++,h=!1;c++,Jk(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Vb=m(()=>{"use strict";var aR=se(),sR=ze(),nR=Qr().CONSTRUCTOR,zu=cr(),oR=pt(),uR=ee(),lR=Hr(),Bb=zu&&zu.prototype;aR({target:"Promise",proto:!0,forced:nR,real:!0},{catch:function(a){return this.then(void 0,a)}});!sR&&uR(zu)&&(Yu=oR("Promise").prototype.catch,Bb.catch!==Yu&&lR(Bb,"catch",Yu,{unsafe:!0}));var Yu});var Ob=m(()=>{"use strict";var cR=se(),dR=De(),pR=st(),hR=Wr(),fR=Gs(),mR=Ns(),bR=Wu();cR({target:"Promise",stat:!0,forced:bR},{race:function(e){var t=this,r=hR.f(t),i=r.reject,s=fR(function(){var n=pR(t.resolve);mR(e,function(o){dR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var _b=m(()=>{"use strict";var gR=se(),vR=Wr(),SR=Qr().CONSTRUCTOR;gR({target:"Promise",stat:!0,forced:SR},{reject:function(e){var t=vR.f(this),r=t.reject;return r(e),t.promise}})});var Ku=m((wO,Nb)=>{"use strict";var yR=nt(),TR=Ce(),IR=Wr();Nb.exports=function(a,e){if(yR(a),TR(e)&&e.constructor===a)return e;var t=IR.f(a),r=t.resolve;return r(e),t.promise}});var Ub=m(()=>{"use strict";var ER=se(),xR=pt(),Fb=ze(),PR=cr(),qb=Qr().CONSTRUCTOR,wR=Ku(),AR=xR("Promise"),kR=Fb&&!qb;ER({target:"Promise",stat:!0,forced:Fb||qb},{resolve:function(e){return wR(kR&&this===AR?PR:this,e)}})});var Hb=m(()=>{"use strict";Ab();Cb();Vb();Ob();_b();Ub()});var Wb=m(()=>{"use strict";var RR=se(),$R=ze(),Js=cr(),LR=pe(),Gb=pt(),Qb=ee(),MR=Su(),jb=Ku(),DR=Hr(),Ju=Js&&Js.prototype,CR=!!Js&&LR(function(){Ju.finally.call({then:function(){}},function(){})});RR({target:"Promise",proto:!0,real:!0,forced:CR},{finally:function(a){var e=MR(this,Gb("Promise")),t=Qb(a);return this.then(t?function(r){return jb(e,a()).then(function(){return r})}:a,t?function(r){return jb(e,a()).then(function(){throw r})}:a)}});!$R&&Qb(Js)&&(Xu=Gb("Promise").prototype.finally,Ju.finally!==Xu&&DR(Ju,"finally",Xu,{unsafe:!0}));var Xu});var zb=m((DO,Yb)=>{"use strict";im();Hb();Wb();var BR=Dt();Yb.exports=BR("Promise","finally")});var Xb=m((CO,Kb)=>{"use strict";var VR=zb();Kb.exports=VR});var Zs=m((BO,Jb)=>{"use strict";var OR=Xb();Jb.exports=OR});var dg=m(()=>{"use strict";var XR=se(),JR=Go().values;XR({target:"Object",stat:!0},{values:function(e){return JR(e)}})});var hg=m((S_,pg)=>{"use strict";dg();var ZR=Cr();pg.exports=ZR.Object.values});var mg=m((y_,fg)=>{"use strict";var e$=hg();fg.exports=e$});var Zr=m((T_,bg)=>{"use strict";var t$=mg();bg.exports=t$});var Rg=m(()=>{"use strict";var g$=se(),v$=Br(),S$=qr(),y$=$i(),T$=Li();g$({target:"Array",proto:!0},{at:function(e){var t=v$(this),r=S$(t),i=y$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});T$("at")});var Lg=m((z_,$g)=>{"use strict";Rg();var I$=Dt();$g.exports=I$("Array","at")});var Dg=m((K_,Mg)=>{"use strict";var E$=Lg();Mg.exports=E$});var ti=m((X_,Cg)=>{"use strict";var x$=Dg();Cg.exports=x$});var Tl=m((wF,cv)=>{"use strict";var sL=ir();cv.exports=Array.isArray||function(e){return sL(e)==="Array"}});var pv=m((AF,dv)=>{"use strict";var nL=TypeError,oL=9007199254740991;dv.exports=function(a){if(a>oL)throw nL("Maximum allowed index exceeded");return a}});var mv=m((kF,fv)=>{"use strict";var uL=Tl(),lL=qr(),cL=pv(),dL=Or(),hv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?dL(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&uL(d)?(p=lL(d),u=hv(a,e,d,p,u,s-1)-1):(cL(u+1),a[u]=d),u++),l++;return u};fv.exports=hv});var Sv=m((RF,vv)=>{"use strict";var bv=Tl(),pL=vu(),hL=Ce(),fL=he(),mL=fL("species"),gv=Array;vv.exports=function(a){var e;return bv(a)&&(e=a.constructor,pL(e)&&(e===gv||bv(e.prototype))?e=void 0:hL(e)&&(e=e[mL],e===null&&(e=void 0))),e===void 0?gv:e}});var Tv=m(($F,yv)=>{"use strict";var bL=Sv();yv.exports=function(a,e){return new(bL(a))(e===0?0:e)}});var Iv=m(()=>{"use strict";var gL=se(),vL=mv(),SL=st(),yL=Br(),TL=qr(),IL=Tv();gL({target:"Array",proto:!0},{flatMap:function(e){var t=yL(this),r=TL(t),i;return SL(e),i=IL(t,0),i.length=vL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Ev=m(()=>{"use strict";var EL=Li();EL("flatMap")});var Pv=m((BF,xv)=>{"use strict";Iv();Ev();var xL=Dt();xv.exports=xL("Array","flatMap")});var Av=m((VF,wv)=>{"use strict";var PL=Pv();wv.exports=PL});var Il=m((OF,kv)=>{"use strict";var wL=Av();kv.exports=wL});var aa=m((YF,Yv)=>{"use strict";var CL=Di(),BL=String;Yv.exports=function(a){if(CL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return BL(a)}});var xl=m((zF,zv)=>{"use strict";zv.exports=`
7
+ \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Jv=m((KF,Xv)=>{"use strict";var VL=ne(),OL=Mt(),_L=aa(),wl=xl(),Kv=VL("".replace),NL=RegExp("^["+wl+"]+"),FL=RegExp("(^|[^"+wl+"])["+wl+"]+$"),Pl=function(a){return function(e){var t=_L(OL(e));return a&1&&(t=Kv(t,NL,"")),a&2&&(t=Kv(t,FL,"$1")),t}};Xv.exports={start:Pl(1),end:Pl(2),trim:Pl(3)}});var rS=m((XF,tS)=>{"use strict";var qL=Jo().PROPER,UL=pe(),Zv=xl(),eS="\u200B\x85\u180E";tS.exports=function(a){return UL(function(){return!!Zv[a]()||eS[a]()!==eS||qL&&Zv[a].name!==a})}});var Al=m((JF,iS)=>{"use strict";var HL=Jv().start,jL=rS();iS.exports=jL("trimStart")?function(){return HL(this)}:"".trimStart});var sS=m(()=>{"use strict";var GL=se(),aS=Al();GL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==aS},{trimLeft:aS})});var oS=m(()=>{"use strict";sS();var QL=se(),nS=Al();QL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==nS},{trimStart:nS})});var lS=m((iq,uS)=>{"use strict";oS();var WL=Dt();uS.exports=WL("String","trimLeft")});var dS=m((aq,cS)=>{"use strict";var YL=lS();cS.exports=YL});var hS=m((sq,pS)=>{"use strict";var zL=dS();pS.exports=zL});var RS=m(()=>{"use strict"});var $S=m(()=>{"use strict"});var MS=m((q1,LS)=>{"use strict";var vM=Ce(),SM=ir(),yM=he(),TM=yM("match");LS.exports=function(a){var e;return vM(a)&&((e=a[TM])!==void 0?!!e:SM(a)==="RegExp")}});var CS=m((U1,DS)=>{"use strict";var IM=nt();DS.exports=function(){var a=IM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var OS=m((H1,VS)=>{"use strict";var EM=De(),xM=Ke(),PM=xi(),wM=CS(),BS=RegExp.prototype;VS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in BS)&&!xM(a,"flags")&&PM(BS,a)?EM(wM,a):e}});var NS=m((j1,_S)=>{"use strict";var Vl=ne(),AM=Br(),kM=Math.floor,Cl=Vl("".charAt),RM=Vl("".replace),Bl=Vl("".slice),$M=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,LM=/\$([$&'`]|\d{1,2})/g;_S.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=LM;return i!==void 0&&(i=AM(i),u=$M),RM(s,u,function(l,c){var d;switch(Cl(c,0)){case"$":return"$";case"&":return a;case"`":return Bl(e,0,t);case"'":return Bl(e,n);case"<":d=i[Bl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=kM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Cl(c,1):r[h-1]+Cl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var US=m(()=>{"use strict";var MM=se(),DM=De(),_l=ne(),FS=Mt(),CM=ee(),BM=Dr(),VM=MS(),oi=aa(),OM=wi(),_M=OS(),NM=NS(),FM=he(),qM=ze(),UM=FM("replace"),HM=TypeError,Ol=_l("".indexOf),jM=_l("".replace),qS=_l("".slice),GM=Math.max;MM({target:"String",proto:!0},{replaceAll:function(e,t){var r=FS(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!BM(e)){if(i=VM(e),i&&(s=oi(FS(_M(e))),!~Ol(s,"g")))throw new HM("`.replaceAll` does not allow non-global regexes");if(n=OM(e,UM),n)return DM(n,e,r,t);if(qM&&i)return jM(oi(r),e,t)}for(o=oi(r),u=oi(e),l=CM(t),l||(t=oi(t)),c=u.length,d=GM(1,c),p=Ol(o,u);p!==-1;)h=l?oi(t(u,p,o)):NM(u,o,p,[],void 0,t),b+=qS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Ol(o,u,p+d);return f<o.length&&(b+=qS(o,f)),b}})});var jS=m((W1,HS)=>{"use strict";RS();$S();US();var QM=Dt();HS.exports=QM("String","replaceAll")});var QS=m((Y1,GS)=>{"use strict";var WM=jS();GS.exports=WM});var YS=m((z1,WS)=>{"use strict";var YM=QS();WS.exports=YM});var KS=m((K1,zS)=>{"use strict";var zM=$i(),KM=aa(),XM=Mt(),JM=RangeError;zS.exports=function(e){var t=KM(XM(this)),r="",i=zM(e);if(i<0||i===1/0)throw new JM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var ty=m((X1,ey)=>{"use strict";var ZS=ne(),ZM=Oo(),XS=aa(),eD=KS(),tD=Mt(),rD=ZS(eD),iD=ZS("".slice),aD=Math.ceil,JS=function(a){return function(e,t,r){var i=XS(tD(e)),s=ZM(t),n=i.length,o=r===void 0?" ":XS(r),u,l;return s<=n||o===""?i:(u=s-n,l=rD(o,aD(u/o.length)),l.length>u&&(l=iD(l,0,u)),a?i+l:l+i)}};ey.exports={start:JS(!1),end:JS(!0)}});var iy=m((J1,ry)=>{"use strict";var sD=sr();ry.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(sD)});var ay=m(()=>{"use strict";var nD=se(),oD=ty().start,uD=iy();nD({target:"String",proto:!0,forced:uD},{padStart:function(e){return oD(this,e,arguments.length>1?arguments[1]:void 0)}})});var ny=m((tH,sy)=>{"use strict";ay();var lD=Dt();sy.exports=lD("String","padStart")});var uy=m((rH,oy)=>{"use strict";var cD=ny();oy.exports=cD});var cy=m((iH,ly)=>{"use strict";var dD=uy();ly.exports=dD});var nd="2.0.124-dev.6bbb9242.0";var Ie=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Ie||{}),Lt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(Lt||{});var Ss=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ss||{}),so=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(so||{});var no=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(no||{});var qT=O(Xe(),1);import{assertNever as ah,assertNonNullable as xx,isNonNullable as xs,ValueSubject as No,Subject as Px,Subscription as wx,merge as Ax,observableFrom as kx,fromEvent as eh,map as th,tap as rh,filterChanged as Rx,isNullable as Fo,ErrorCategory as ih}from"@vkontakte/videoplayer-shared/es2015";var Zp=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var Ps=class{constructor(e){this.connection$=new No(void 0);this.castState$=new No("NOT_AVAILABLE");this.errorEvent$=new Px;this.realCastState$=new No("NOT_AVAILABLE");this.subscription=new wx;this.isDestroyed=!1;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=xs((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Zp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ih.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){xs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Fo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Fo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(eh(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return ah(i.sessionState)}})).add(Ax(eh(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(rh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),th(i=>i.castState)),kx([r.getCastState()])).pipe(Rx(),th($x),rh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=xs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();xx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Fo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?xs(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:ih.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},$x=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return ah(a)}};var bc=O(Xe(),1),TT=O(Ur(),1),IT=O(hu(),1);var ug=O(Zs(),1);import{assertNever as Zb}from"@vkontakte/videoplayer-shared/es2015";var fe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Zb(t)}return a},en=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Zb(e)}};var P=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as _R,Subject as tn,merge as eg}from"@vkontakte/videoplayer-shared/es2015";var C=class{constructor(e){this.transitionStarted$=new tn;this.transitionEnded$=new tn;this.transitionUpdated$=new tn;this.forceChanged$=new tn;this.stateChangeStarted$=eg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=eg(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||_R(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 NR}from"@vkontakte/videoplayer-shared/es2015";var tg=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return NR(a)}};import{assertNever as Jr,assertNonNullable as pr,debounce as rg,ErrorCategory as ig,fromEvent as hr,isNonNullable as ag,map as sg,merge as ng,observableFrom as FR,Subject as qR,Subscription as Zu,timeout as UR,getHighestQuality as HR}from"@vkontakte/videoplayer-shared/es2015";var jR=5,GR=5,QR=500,og=7e3,ji=class{constructor(e){this.subscription=new Zu;this.loadMediaTimeoutSubscription=new Zu;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Jr(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:Jr(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:Jr(e)}break}default:Jr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(tg(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 Zu;this.subscription.add(e),this.subscription.add(ng(this.videoState.stateChangeStarted$.pipe(sg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(sg(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new qR;e.add(i.pipe(rg(QR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(hr(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)>jR)&&i.next(o),s=o})),e.add(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<GR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:Jr(n)}}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=ng(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,FR(["init"])).pipe(rg(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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"),P(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"),P(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"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];pr(c);let d=HR(Object.keys(c));pr(d);let p=c[d];pr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];pr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];pr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];pr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];pr(c),r=fe(c.url),i="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:ig.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Jr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return ag(o)&&(n.metadata.title=o),ag(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(UR(og).subscribe(()=>s(`timeout(${og})`)))});(0,ug.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ig.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Sl=O(Xe(),1);import{clearVideoElement as cg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as WR}from"@vkontakte/videoplayer-shared/es2015";var lg=a=>{try{a.pause(),a.playbackRate=0,WR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as YR,Subscription as zR}from"@vkontakte/videoplayer-shared/es2015";var el=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)}},tl=window.WeakMap?new WeakMap:new el,rl=window.WeakMap?new WeakMap:new Map,KR=(a,e=20)=>{let t=0;return YR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?cg(t):(t=document.createElement("video"),a.appendChild(t)),tl.set(t,r);let i=new zR;return i.add(KR(t,e)),rl.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},xe=a=>{let e=rl.get(a);e==null||e.unsubscribe(),rl.delete(a);let t=tl.get(a);tl.delete(a),t?cg(a):lg(a)};var al=O(Zr(),1);import{assertNonNullable as Gi,isNonNullable as ut,isNullable as a$,fromEvent as ei,merge as gg,observableFrom as vg,filterChanged as Sg,map as Qi,Subject as yg,Subscription as s$,ValueSubject as n$,ErrorCategory as o$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as il,isNullable as r$,Subscription as i$}from"@vkontakte/videoplayer-shared/es2015";var rn=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=r$(i),l=new i$;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>rn(e,()=>a.loop,r=>{il(r)&&(a.loop=r)},{onError:t}),Pe=(a,e,t,r)=>rn(e,()=>({muted:a.muted,volume:a.volume}),i=>{il(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Fe=(a,e,t,r)=>rn(e,()=>a.playbackRate,i=>{il(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Bt=rn;var u$=a=>["__",a.language,a.label].join("|"),l$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},sl=class a{constructor(e){this.available$=new yg;this.current$=new n$(void 0);this.error$=new yg;this.subscription=new s$;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:o$.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(Bt(t.internalTextTracks,()=>(0,al.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Qi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Bt(t.externalTextTracks,()=>(0,al.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Qi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Bt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Bt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Gi(this.video);let{textTracks:e}=this.video;this.subscription.add(ei(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(gg(ei(e,"addtrack"),ei(e,"removetrack"),vg(["init"])).pipe(Qi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Sg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(gg(ei(e,"change"),vg(["init"])).pipe(Qi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Qi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Sg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(ei(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;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),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(ei(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;ut(t.align)&&(i.align=t.align),ut(t.position)&&(i.position=t.position),ut(t.size)&&(i.size=t.size),ut(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Gi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:u$(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){Gi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(a$(e)||!l$(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Gi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Gi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},qe=sl;var mt=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 Tg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},nl=a=>{let e=Tg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Ig=a=>{let e=Tg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ue,map as Vt,merge as xg,filterChanged as d$,isNonNullable as Pg,Subject as p$,filter as wg,mapTo as Ag,combine as h$,once as f$,ErrorCategory as m$,ValueSubject as kg,clientChecker as b$}from"@vkontakte/videoplayer-shared/es2015";var c$=3,Eg=(a,e,t=c$)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var we=a=>{let e=T=>Ue(a,T).pipe(Ag(void 0)),r=xg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Ue(a,T))).pipe(Vt(T=>T.type==="ended"?a.readyState<2:a.readyState<3),d$()),i=xg(Ue(a,"progress"),Ue(a,"timeupdate")).pipe(Vt(()=>Eg(a.buffered,a.currentTime))),s=b$.isSafari?h$({play:e("play").pipe(f$()),playing:e("playing")}).pipe(Ag(void 0)):e("playing"),n=Ue(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=Ue(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=Ue(a,"error").pipe(wg(()=>!!(a.error||a.played.length)),Vt(()=>{var x;let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:m$.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(x=a.error)!=null?x:void 0}})),l=Ue(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new p$,d=.3,p;l.subscribe(T=>{a.loop&&Pg(p)&&Pg(T)&&p>=a.duration-d&&T<=d&&c.next(p),p=T});let h=e("pause").pipe(wg(()=>!a.error&&p!==a.duration)),f=Ue(a,"enterpictureinpicture"),b=Ue(a,"leavepictureinpicture"),g=new kg(Ig(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new kg(nl(a));return Ue(a,"fullscreenchange").pipe(Vt(()=>nl(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ue(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as Ot}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Ot.Q_144P;case"lowest":return Ot.Q_240P;case"low":return Ot.Q_360P;case"sd":case"medium":return Ot.Q_480P;case"hd":case"high":return Ot.Q_720P;case"fullhd":case"full":return Ot.Q_1080P;case"quadhd":case"quad":return Ot.Q_1440P;case"ultrahd":case"ultra":return Ot.Q_2160P}};var Nt=O(ti(),1),qg=O(Xe(),1),an=O(Ur(),1);import{isNonNullable as oe,isNullable as ul,now as Ug,isHigher as ll,isHigherOrEqual as cl,isInvariantQuality as _g,isLower as Ng,isLowerOrEqual as dl,videoSizeToQuality as P$,assertNotEmptyArray as Hg,assertNonNullable as w$}from"@vkontakte/videoplayer-shared/es2015";var ol=!1,bt={},Bg=a=>{ol=a},Vg=()=>{bt={}},Og=a=>{a(bt)},Wi=(a,e)=>{var t;ol&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var r,i;if(!ol)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};var A$=new ve("best_bitrate"),jg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var pl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Yi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ug()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Gg='Assertion "ABR Tracks is empty array" failed',sn=(a,e,t,r)=>{var u;let i=[...e].sort(pl(1)),s=[...t].sort(pl(1)),n=s.filter(l=>oe(l.bitrate)&&oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,qg.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},Fg=a=>"quality"in a,Qg=(a,e,t,r)=>{var n;let i=oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Ug()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Fg(o)?"video":"audio",l=Fg(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
9
  `}),o}return r==null||r.recordSwitch(t),t},k$=(a,e)=>Math.log(e)/Math.log(a),Ft=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{var U,R,H,N,Y,k;Hg(a,Gg);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let y=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(y-1)+1;else{let D=r.pixelRatioLogBase,[j=0,_=0,Oe=0]=r.pixelRatioLogCoefficients,It=k$(D,j*y+_)+Oe;Number.isFinite(It)&&(b*=It)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,v=r.considerPlaybackRate&&oe(o)?o:1,S=a.filter(y=>!_g(y.quality)).sort((y,D)=>ll(y.quality,D.quality)?-1:1),T=(U=(0,Nt.default)(S,-1))==null?void 0:U.quality,x=(R=(0,Nt.default)(S,0))==null?void 0:R.quality,E=ul(i)||oe(i.min)&&oe(i.max)&&Ng(i.max,i.min)||oe(i.min)&&x&&ll(i.min,x)||oe(i.max)&&T&&Ng(i.max,T),L=v*jg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),B={},M=S.filter(y=>{let D=!0;if(g)if(y.size)D=y.size.width<=g.width&&y.size.height<=g.height;else{let de=g&&P$(g);D=de?dl(y.quality,de):!0}if(!D)return B[y.quality]="FitsContainer",!1;let j=h||t;if(!(oe(j)&&isFinite(j)&&oe(y.bitrate)?j-s>=y.bitrate*L:!0))return B[y.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&oe(r.minBufferToSwitchUp)&&u&&!_g(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&ll(y.quality,u.quality))return B[y.quality]="Buffer",!1;if(!!d&&cl(y.quality,d))return B[y.quality]="DroppedFramesLimit",!1;if(!!p&&cl(y.quality,p))return B[y.quality]="StallsLimit",!1;let Q=E||(ul(i.max)||dl(y.quality,i.max))&&(ul(i.min)||cl(y.quality,i.min)),ce=oe(c)&&!c?dl(y.quality,r.backgroundVideoQualityLimit):!0;return!Q||!ce?(B[y.quality]="FitsQualityLimits",!1):!0})[0];M&&M.bitrate&&A$.next(M.bitrate);let q=(H=M!=null?M:(0,Nt.default)(S,-1))!=null?H:a[0];return q.quality!==((N=l==null?void 0:l.last)==null?void 0:N.quality)&&f({message:`
10
10
  [VIDEO TRACKS ABR]
@@ -121,6 +121,6 @@ void main(void) {
121
121
  // sample using new coordinates
122
122
  gl_FragColor = texture2D(u_texture, tc);
123
123
  }
124
- `;var Bn=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 i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Dn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Cn(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"),i=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(i,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(Oy,this.gl.VERTEX_SHADER),r=this.createShader(_y,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,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/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,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;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}};import{isNullable as BD,now as Ny,Subscription as VD,filter as OD,combine as Fy,ValueSubject as rc,isNonNullable as _D}from"@vkontakte/videoplayer-shared/es2015";var ic=class{constructor(){this.isSeeked$=new rc(!1);this.isBuffering$=new rc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new VD;this.severeStallOccurred$=new rc(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(Fy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(OD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Fy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(BD(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=Ny(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,_D(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Ny(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},qy=ic;import{combine as ND,map as FD,observeElementSize as qD,Subscription as UD,ValueSubject as ac,noop as HD}from"@vkontakte/videoplayer-shared/es2015";var Vn=class{constructor(){this.subscription=new UD;this.pipSize$=new ac(void 0);this.videoSize$=new ac(void 0);this.elementSize$=new ac(void 0);this.pictureInPictureWindowRemoveEventListener=HD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(qD(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(ND({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(FD(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Er=class{constructor(e){this.subscription=new KD;this.videoState=new C("stopped");this.droppedFramesManager=new ln;this.stallsManager=new qy;this.elementSizeManager=new Vn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Yi;this.audioTrackSwitchHistory=new Yi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.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(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(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"&&P(this.params.desiredState.playbackState,"paused");return;default:return QD(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Bn(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:((i=e.projectionData)==null?void 0:i.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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),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(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Mn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=we(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:sc.WTF,message:`${i} 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:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Uy(c=>!!c.length),jy()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(nc(c=>c.to.state!=="none"),ja());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ja()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),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(r.loadedMetadata$,e.loadedMetadataEvent$),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(Uy(Hy),jy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(nc(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Fe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(WD(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Ul(f));let b=[];for(let g of f.representations){let v=my(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Hl(h));let f=[];for(let b of h.representations){let g=fy($(I({},b),{streamId:h.id}));g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let f of h.representations){let b=by(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:sc.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(On(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,zD(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Gy.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(v=>{var S;return((S=this.videoTracksMap.get(v))==null?void 0:S.representation.id)===h.id});Hy(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,v).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ja()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Hl(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ja()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Ul(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(nc(({to:c})=>c==="ready"),ja());this.subscription.add(On(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,oc(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(On(u,this.player.state$.stateChangeEnded$,oc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=On(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,oc(["init"])).pipe(YD(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var B,Z,M,q,U,R,H,N,Y,k,y,D,j;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(B=e.videoTrack.getState())==null?void 0:B.id,n=[...this.videoTracksMap.keys()].find(({id:_})=>_===i),o=t.currentVideoTrack$.getValue(),u=((q=(M=e.videoStream.getState())!=null?M:n&&((Z=this.videoTracksMap.get(n))==null?void 0:Z.stream))!=null?q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:_})=>_===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(p,h||1/0),1),b=(U=e.audioStream.getState())!=null?U:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(R=[...this.audioStreamsMap.keys()].find(({id:_})=>_===(b==null?void 0:b.id)))!=null?R:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let _=sn(n,c,(H=this.audioStreamsMap.get(g))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(N=_==null?void 0:_.bitrate)!=null?N:-1/0)}if(o){let _=sn(o,c,(Y=this.audioStreamsMap.get(g))!=null?Y:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=_==null?void 0:_.bitrate)!=null?k:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),T=r?S!=null?S:n:n!=null?n:S,x=g&&Wg(T,c,(y=this.audioStreamsMap.get(g))!=null?y:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(D=this.videoTracksMap.get(T))==null?void 0:D.representation,L=x&&((j=this.audioTracksMap.get(x))==null?void 0:j.representation);if(E&&L)return[E,L];if(E&&!L&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sc.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),xe(this.video),this.tracer.end()}};var Ga=class extends Er{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 Qy,interval as XD,map as Wy}from"@vkontakte/videoplayer-shared/es2015";var Qa=class extends Er{constructor(e){super(e),this.liveOffset=new mt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(Wy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Qy({interval:XD(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(Qy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Wy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=gy(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=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,i)})}};var zy=O(Zs(),1);import{assertNever as Wa,assertNonNullable as Yy,debounce as JD,ErrorCategory as _n,filter as ZD,isNonNullable as e0,isNullable as t0,map as Nn,merge as r0,Observable as i0,observableFrom as a0,Subscription as s0,videoSizeToQuality as n0}from"@vkontakte/videoplayer-shared/es2015";var tt={};var pi=(a,e)=>new i0(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ya=class{constructor(e){this.subscription=new s0;this.videoState=new C("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Wa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Wa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Wa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Wa(e)}break;default:Wa(t)}};this.textTracksManager=new qe(e.source.url),this.video=Ee(e.container,e.tuning),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(ue(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),xe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:_n.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,zy.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Yy(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Yy(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:_n.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=we(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,r)),this.subscription.add(Pe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Fe(this.video,e.playbackRate,i.playbackRateState$,r)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Nn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(pi(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:_n.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},r)).add(i.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(pi(this.hls,tt.Events.MANIFEST_PARSED).pipe(Nn(({levels:l})=>l.reduce((c,d)=>{var S,T;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(T=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?T:n0({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(pi(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(pi(this.hls,tt.Events.LEVEL_LOADING).pipe(Nn(({url:l})=>ue(l))),t.hostname$),s(pi(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Bt(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=pi(this.hls,tt.Events.LEVEL_SWITCHED).pipe(Nn(({level:l})=>n(this.hls.levels[l])));o.pipe(ZD(e0)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Bt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(t0(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=r0(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a0(["init"])).pipe(JD(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)}playIfAllowed(){return w(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_n.DOM,thrown:t})))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("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"),P(this.params.desiredState.playbackState,"stopped",!0)}};var Ky="X-Playback-Duration",uc=a=>w(void 0,null,function*(){var i;let e=yield Ze(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Ky)?parseInt(e.headers.get(Ky),10):void 0});import{assertNever as g0,combine as v0,debounce as S0,ErrorCategory as Un,filter as y0,filterChanged as T0,isNonNullable as Zy,isNullable as Hn,map as eT,merge as I0,observableFrom as E0,Subscription as x0,ValueSubject as dc,VideoQuality as P0}from"@vkontakte/videoplayer-shared/es2015";var cc=O(hu(),1);import{videoSizeToQuality as o0,getExponentialDelay as u0}from"@vkontakte/videoplayer-shared/es2015";var l0=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=o0({width:t,height:r})}return e!=null?e:null},c0=(a,e)=>{var s,n;let t=a.split(`
125
- `),r=[],i=[];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,cc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=l0(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[S,T]=d.RESOLUTION.split("x").map(x=>parseInt(x,10));S&&T&&(g={width:S,height:T})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(c){let d=(0,cc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},d0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),lc=0,Xy=(i,...s)=>w(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield Ze(a,r)).text();lc+=1;try{let{qualityManifests:u,textTracks:l}=c0(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(lc<=t.manifestRetryMaxCount)return yield d0(u0(lc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Xy(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Fn=Xy;import{isNonNullable as p0,Subscription as h0,throttle as f0,ValueSubject as Jy,Subject as m0,ErrorCategory as b0}from"@vkontakte/videoplayer-shared/es2015";var qn=class{constructor(e,t,r,i,s){this.subscription=new h0;this.abortControllers={destroy:new me,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Jy(null);this.getCurrentTime$=new Jy(null);this.error$=new m0;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(f0(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return w(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return w(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return w(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield Ze(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
126
- `),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(p0(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([$(I({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return w(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return w(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:b0.WTF,thrown:t,message:e})}};var za=class{constructor(e){this.subscription=new x0;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new dc([]);this.liveOffset=new mt;this.manifestStartTime$=new dc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=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"),P(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((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(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(i==null?void 0:i.to)==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return g0(t)}};var r;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:P0.INVARIANT,url:this.params.source.url};let t=(i,s)=>Fn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new qn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new qe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Un.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Un.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),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(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new dc((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.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&&!i&&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:Un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.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.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(T0(),eT(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.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&&Zy(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(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(i.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(v0({startTime:this.manifestStartTime$.pipe(y0(Zy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(eT(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=I0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,E0(["init"])).pipe(S0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Hn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=fe(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),uc(n).then(c=>{var d;if(!Hn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Hn(p)||!isFinite(p))&&Ze(n).then(h=>h.text()).then(h=>{var b;let f=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(f){let g=new URL(f,n).toString();uc(g).then(v=>{Hn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Un.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()}generateLiveUrl(){let e=fe(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as w0,debounce as A0,ErrorCategory as pc,fromEvent as hc,isNonNullable as k0,isNullable as R0,map as tT,merge as rT,observableFrom as iT,Subscription as $0,ValueSubject as L0,VideoQuality as M0,clientChecker as D0}from"@vkontakte/videoplayer-shared/es2015";var Ka=class{constructor(e){this.subscription=new $0;this.videoState=new C("stopped");this.manifests$=new L0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=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"),P(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((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return w0(t)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:M0.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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fn(fe(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:pc.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(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.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&&!i&&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:pc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(tT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.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(i.loadedMetadata$.subscribe(()=>{var h;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&&k0(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===f);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(ue(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}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(tT(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)),!D0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(rT(hc(o,"addtrack"),hc(o,"removetrack"),hc(o,"change"),iT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=rT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,iT(["init"])).pipe(A0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(R0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=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&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var oT=O(Ur(),1),Xa=O(Zr(),1);import{assertNever as C0,assertNonNullable as aT,debounce as B0,ErrorCategory as sT,isHigher as V0,isHigherOrEqual as O0,isInvariantQuality as nT,isLowerOrEqual as _0,isNonNullable as N0,merge as F0,observableFrom as q0,Subscription as U0,map as H0}from"@vkontakte/videoplayer-shared/es2015";var Ja=class{constructor(e){this.subscription=new U0;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new qe;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return C0(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,oT.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Xa.default)(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:sT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(H0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.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&&N0(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=F0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,q0(["init"])).pipe(B0(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),xe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;aT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];aT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ba(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Xa.default)(this.trackUrls).find(d=>!nT(d.track.quality)&&_0(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&&O0(c.quality,u.quality)&&(t=u),!t){let d=(0,Xa.default)(this.trackUrls).filter(h=>!nT(h.track.quality)&&V0(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Xa.default)(this.trackUrls).map(l=>l.track);t=Ft(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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 lT,debounce as W0,merge as cT,observableFrom as Y0,Subscription as z0,map as dT,ValueSubject as K0,ErrorCategory as mc,VideoQuality as X0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as j0}from"@vkontakte/videoplayer-shared/es2015";var uT=["stun:videostun.mycdn.me:80"],G0=1e3,Q0=3,fc=()=>null,jn=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=fc;this.externalStopCallback=fc;this.externalErrorCallback=fc;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}}handleUpdateMessage(e){return w(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return w(this,null,function*(){try{let e={iceServers:[{urls:uT}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return w(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return w(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:j0.WTF,message:e.message})}onPeerConnectionStream(e){return w(this,null,function*(){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()))}}createOffer(){return w(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield 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),G0)}normalizeOptions(e={}){let t={stunServerList:uT,maxRetryNumber:Q0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Za=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new K0(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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return lT(e)}};this.subscription=new z0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new jn(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:mc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};cT(this.videoState.stateChangeStarted$.pipe(dT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(dT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=we(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(He(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Pe(this.video,t.volume,i.volumeState$,r)).add(i.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 lT(n.to)}},r)).add(cT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Y0(["init"])).pipe(W0(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(ue(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:X0.INVARIANT}),this.video.srcObject=e,P(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:mc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var es=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 rs,assertNonNullable as Wt,ErrorCategory as Gn,filter as gT,isNonNullable as vT,isNullable as sC,map as nC,merge as oC,once as uC,Subject as Le,Subscription as ST,ValueSubject as V,flattenObject as yT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as J0,map as pT,Subscription as Z0,Subject as eC}from"@vkontakte/videoplayer-shared/es2015";var hT=a=>new J0(e=>{let t=new Z0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(pT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(pT(({type:l})=>l!==void 0)),n=new eC,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.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),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as tC,Subscription as rC,combine as iC,filter as mT,once as bT}from"@vkontakte/videoplayer-shared/es2015";function fT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as aC}from"@vkontakte/videoplayer-shared/es2015";var ts=class ts{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new me;this.subscriptions=new rC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(mT(s=>!!s.type),bT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){aC.isSafari&&e!=="MPEG"||this.subscriptions.add(iC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(mT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),bT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return w(this,null,function*(){let{volumeMultiplier:t}=this,r=fT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:ts.errorId,category:tC.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${ts.errorId} exception`,thrown:e})}};ts.errorId="VolumeMultiplierManager";var hi=ts;var lC={chunkDuration:5e3,maxParallelRequests:5},is=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new Le;this.noAvailableProvidersError$=new Le;this.volumeMultiplierError$=new Le;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new Le,warning$:new Le,willSeekEvent$:new Le,soundProhibitedEvent$:new Le,seekedEvent$:new Le,loopedEvent$:new Le,endedEvent$:new Le,firstBytesEvent$:new Le,loadedMetadataEvent$:new Le,firstFrameEvent$:new Le,canplay$:new Le,isLive$:new V(void 0),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new ST;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=jv([...Qv(this.params.tuning),...Gv(this.params.tuning)],this.params.tuning).filter(l=>vT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,bc.default)(i,l)),...t.filter(l=>(0,bc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",yT(s)),this.screenFormatsIterator=new es(s);let n=[...El(!0),...El(!1)];this.chromecastFormatsIterator=new es(n.filter(l=>vT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&hi.isSupported()&&(this.volumeMultiplierManager=new hi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(sC(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Gn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination: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"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?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}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return rs(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,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":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Wt(o),new Ga($(I({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Qa($(I({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Wt(o),si||!this.params.tuning.useHlsJs?new Ka($(I({},n),{source:o})):new Ya($(I({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new za($(I({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Ja($(I({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new uv($(I({},n),{source:o,config:$(I({},lC),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Za({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return rs(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Wt(o),new ji({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,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 rs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return rs(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 rs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);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 $(I({},e),{url:r(e.url)})}return(0,IT.default)((0,TT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new ST,t=!1,r=0;return e.add(oC(this.providerOutput.error$.pipe(gT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),hT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(nC(i=>({id:`ProviderHangup:${i}`,category:Gn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(gT(({to:s})=>s==="playing"),uC()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Gn.NETWORK,u=i.category===Gn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=$(I({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",yT(n))})),e}};import{fromEvent as Qn,once as cC,combine as dC,Subscription as ET,ValueSubject as gc,map as pC,filter as hC,isNonNullable as Wn,now as Ve,safeStorage as vc}from"@vkontakte/videoplayer-shared/es2015";var fC=5e3,xT="one_video_throughput",PT="one_video_rtt",yt=window.navigator.connection,wT=()=>{let a=yt==null?void 0:yt.downlink;if(Wn(a)&&a!==10)return a*1e3},AT=()=>{let a=yt==null?void 0:yt.rtt;if(Wn(a)&&a!==3e3)return a},kT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Sc=class a{constructor(e){this.subscription=new ET;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(xT)||(e.useBrowserEstimation?wT():void 0)||fC,r=(s=(i=a.load(PT))!=null?i:e.useBrowserEstimation?AT():void 0)!=null?s:0;if(this.throughput$=new gc(t),this.rtt$=new gc(r),this.rttAdjustedThroughput$=new gc(kT(t,r,e.rttPenaltyRequestSize)),this.throughput=Sr.getSmoothedValue(t,-1,e),this.rtt=Sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=wT();u&&this.throughput.next(u);let l=AT();Wn(l)&&this.rtt.next(l)};yt&&"onchange"in yt&&this.subscription.add(Qn(yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{vc.set(xT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{vc.set(PT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dC({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(pC(({throughput:n,rtt:o})=>kT(n,o,e.rttPenaltyRequestSize)),hC(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=Ve(),i=new ET;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Qn(e,"progress").pipe(cC()).subscribe(s=>{t=s.loaded,r=Ve()}));break;case 1:case 0:i.add(Qn(e,"loadstart").subscribe(()=>{t=0,r=Ve()}));break}i.add(Qn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ve(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Ve(),n=0,o=Ve(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>w(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Ve();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Ve()}else n+=d.byteLength;o=Ve()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ve()-o,this.concurrentDownloads.size),n=0,o=Ve());yield 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,i=!1){if(a.sanityCheck(e,t,i)){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 i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=vc.get(e);if(Wn(t))return(r=parseInt(t,10))!=null?r:void 0}},RT=Sc;import{fillWithDefault as mC,VideoQuality as $T}from"@vkontakte/videoplayer-shared/es2015";var LT={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:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:$T.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:$T.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:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{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:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!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,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,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,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},MT=a=>{var e;return $(I({},mC(a,LT)),{configName:[...(e=a.configName)!=null?e:[],...LT.configName]})};import{assertNonNullable as Yn,combine as Tt,ErrorCategory as zn,filter as Te,filterChanged as W,fromEvent as Tc,isNonNullable as IC,isNullable as EC,Logger as xC,map as G,mapTo as VT,merge as Yt,now as Kn,once as ct,Subject as X,Subscription as OT,tap as _T,ValueSubject as A,isHigher as PC,isInvariantQuality as NT,flattenObject as zt,throttle as Ic,getTraceSubscriptionMethod as FT,Tracer as wC,InternalsExposure as AC}from"@vkontakte/videoplayer-shared/es2015";import{merge as bC,map as gC,filter as DT,isNonNullable as vC}from"@vkontakte/videoplayer-shared/es2015";var yc=({seekState:a,position$:e})=>bC(a.stateChangeEnded$.pipe(gC(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),DT(vC)),e.pipe(DT(()=>a.getState().state==="none")));import{assertNonNullable as SC}from"@vkontakte/videoplayer-shared/es2015";var CT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return SC(e,`Wrong container or containerId {${a.container}}`),e};import{filter as yC,once as TC}from"@vkontakte/videoplayer-shared/es2015";var BT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(yC(i=>i.length>0),TC()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Xn=class{constructor(e={configName:[]},t=wC.createRootTracer(!1)){this.subscription=new OT;this.logger=new xC;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new A("stopped"),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new X,ready$:new X,started$:new X,playing$:new X,paused$:new X,stopped$:new X,willStart$:new X,willResume$:new X,willPause$:new X,willStop$:new X,willDestruct$:new X,watchCoverageRecord$:new X,watchCoverageLive$:new X,managedError$:new X,fatalError$:new X,ended$:new X,looped$:new X,seeked$:new X,willSeek$:new X,autoplaySoundProhibited$:new X,firstBytes$:new X,loadedMetadata$:new X,firstFrame$:new X,canplay$:new X,log$:new X};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Og,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=MT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ps({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new RT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new AC("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,qT.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:zn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=sd(i,["container"]);return this.tracer.log("initVideo",zt(r)),this.domContainer=CT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new is({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),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(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Zi()?(this.tracer.log("request play from hidden tab"),Tc(document,"visibilitychange").pipe(ct()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),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.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Yn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Te(r=>r.length>0),ct()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",zt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Yn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",zt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>I({type:"external"},t))),this}selectTextTrack(e){var t;return BT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",I({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.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(EC(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return IC(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:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Te(({from:e})=>e==="stopped"),ct()).subscribe(()=>{this.initedAt=Kn(),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();this.tracer.log("willSeekEvent",zt(n)),n.state==="requested"?this.desiredState.seekState.setState($(I({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:zn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ct()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",zt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Tt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>NT(u)?1:NT(l)?-1:PC(l,u)?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.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(W()).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$.pipe(W((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(W((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(W()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(W()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(W()).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(G(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(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Tt({hasLiveOffsetByPaused:Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),W(),G(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(Tt({atLiveEdge:Tt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:yc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),W(),_T(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Tt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),W(),_T(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),W()).subscribe(this.info.volume$)).add(yc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Yt(e.providerOutput.endedEvent$.pipe(VT(!0)),e.providerOutput.seekedEvent$.pipe(VT(!1))).pipe(W()).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.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:zn.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.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(ct(),G(n=>n!=null?n:Kn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ct(),G(()=>Kn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ct(),G(()=>Kn()-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 A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new A(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Te(({to:n})=>n==="playing"),ct()).subscribe(()=>r.next(!1)));let i=0,s=Yt(e.providerOutput.isBuffering$,t,r).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),W());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Yt(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(Yt(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(G(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 OT;this.subscription.add(t),this.subscription.add(e.current$.pipe(W((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Te(r=>r.length>0),ct()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput: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(Yt(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(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;Yn(this.providerContainer),Yn(e),Vg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Bg(r)),this.providerContainer.current$.subscribe(({type:r})=>Wi("provider",r)),e.duration$.subscribe(r=>Wi("duration",r)),e.availableVideoTracks$.pipe(Te(r=>!!r.length),ct()).subscribe(r=>Wi("tracks",r)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(G(r=>r==null?void 0:r.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(r=>this.subscription.add(r)),Wi("codecs",Hv())}initTracerSubscription(){let e=FT(this.tracer.log.bind(this.tracer)),t=FT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(W()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Tt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Te(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),W((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Te(r=>r>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Te(r=>r>0),W()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Tt({currentBuffer:this.info.currentBuffer$.pipe(Te(r=>r.end>0),W((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(W())}).pipe(Ic(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(W()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(W()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(W()).subscribe(e("canChangePlaybackSpeed"))).add(Tt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Te(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Ic(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),Te(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),Te(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(W()).subscribe(e("muted"))).add(this.info.volume$.pipe(W()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(W(),Te(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Tt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Te(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Ic(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),Te(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>w(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:zn.DOM,message:String(i)})})});this.subscription.add(Yt(Tc(document,"visibilitychange"),Tc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",zt({quality:t,availableTracks:zt(e),track:zt(r),isAutoQuality:!r})),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 U4,Observable as H4,Subject as j4,ValueSubject as G4,VideoQuality as Q4}from"@vkontakte/videoplayer-shared/es2015";var W4=`@vkontakte/videoplayer-core@${nd}`;export{Ss as ChromecastState,so as HttpConnectionType,H4 as Observable,Ie as PlaybackState,Xn as Player,W4 as SDK_VERSION,j4 as Subject,U4 as Subscription,no as Surface,nd as VERSION,G4 as ValueSubject,Lt as VideoFormat,Q4 as VideoQuality};
124
+ `;var Bn=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 i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Dn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Cn(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"),i=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(i,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(Oy,this.gl.VERTEX_SHADER),r=this.createShader(_y,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,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/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,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;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}};import{isNullable as BD,now as Ny,Subscription as VD,filter as OD,combine as Fy,ValueSubject as rc,isNonNullable as _D}from"@vkontakte/videoplayer-shared/es2015";var ic=class{constructor(){this.isSeeked$=new rc(!1);this.isBuffering$=new rc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new VD;this.severeStallOccurred$=new rc(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(Fy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(OD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Fy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(BD(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=Ny(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,_D(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Ny(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},qy=ic;import{combine as ND,map as FD,observeElementSize as qD,Subscription as UD,ValueSubject as ac,noop as HD}from"@vkontakte/videoplayer-shared/es2015";var Vn=class{constructor(){this.subscription=new UD;this.pipSize$=new ac(void 0);this.videoSize$=new ac(void 0);this.elementSize$=new ac(void 0);this.pictureInPictureWindowRemoveEventListener=HD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(qD(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(ND({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(FD(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Er=class{constructor(e){this.subscription=new KD;this.videoState=new C("stopped");this.droppedFramesManager=new ln;this.stallsManager=new qy;this.elementSizeManager=new Vn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Yi;this.audioTrackSwitchHistory=new Yi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.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(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(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"&&P(this.params.desiredState.playbackState,"paused");return;default:return QD(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Bn(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:((i=e.projectionData)==null?void 0:i.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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),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(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Mn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=we(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:sc.WTF,message:`${i} 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:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Uy(c=>!!c.length),jy()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(nc(c=>c.to.state!=="none"),ja());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ja()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),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(r.loadedMetadata$,e.loadedMetadataEvent$),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(Uy(Hy),jy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(nc(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Fe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(WD(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Ul(f));let b=[];for(let g of f.representations){let v=my(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Hl(h));let f=[];for(let b of h.representations){let g=fy($(I({},b),{streamId:h.id}));g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let f of h.representations){let b=by(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:sc.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(On(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,zD(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Gy.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(v=>{var S;return((S=this.videoTracksMap.get(v))==null?void 0:S.representation.id)===h.id});Hy(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,v).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ja()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Hl(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ja()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Ul(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(nc(({to:c})=>c==="ready"),ja());this.subscription.add(On(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,oc(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(On(u,this.player.state$.stateChangeEnded$,oc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=On(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,oc(["init"])).pipe(YD(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var B,Z,M,q,U,R,H,N,Y,k,y,D,j;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(B=e.videoTrack.getState())==null?void 0:B.id,n=[...this.videoTracksMap.keys()].find(({id:_})=>_===i),o=t.currentVideoTrack$.getValue(),u=((q=(M=e.videoStream.getState())!=null?M:n&&((Z=this.videoTracksMap.get(n))==null?void 0:Z.stream))!=null?q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:_})=>_===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(p,h||1/0),1),b=(U=e.audioStream.getState())!=null?U:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(R=[...this.audioStreamsMap.keys()].find(({id:_})=>_===(b==null?void 0:b.id)))!=null?R:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let _=sn(n,c,(H=this.audioStreamsMap.get(g))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(N=_==null?void 0:_.bitrate)!=null?N:-1/0)}if(o){let _=sn(o,c,(Y=this.audioStreamsMap.get(g))!=null?Y:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=_==null?void 0:_.bitrate)!=null?k:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),T=r?S!=null?S:n:n!=null?n:S,x=g&&Wg(T,c,(y=this.audioStreamsMap.get(g))!=null?y:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(D=this.videoTracksMap.get(T))==null?void 0:D.representation,L=x&&((j=this.audioTracksMap.get(x))==null?void 0:j.representation);if(E&&L)return[E,L];if(E&&!L&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sc.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),xe(this.video),this.tracer.end()}};var Ga=class extends Er{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 Qy,interval as XD,map as Wy}from"@vkontakte/videoplayer-shared/es2015";var Qa=class extends Er{constructor(e){super(e),this.liveOffset=new mt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(Wy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Qy({interval:XD(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(Qy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Wy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=gy(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=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,i)})}};var zy=O(Zs(),1);import{assertNever as Wa,assertNonNullable as Yy,debounce as JD,ErrorCategory as _n,filter as ZD,isNonNullable as eC,isNullable as tC,map as Nn,merge as rC,Observable as iC,observableFrom as aC,Subscription as sC,videoSizeToQuality as nC}from"@vkontakte/videoplayer-shared/es2015";var tt={};var pi=(a,e)=>new iC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ya=class{constructor(e){this.subscription=new sC;this.videoState=new C("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Wa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Wa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Wa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Wa(e)}break;default:Wa(t)}};this.textTracksManager=new qe(e.source.url),this.video=Ee(e.container,e.tuning),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(ue(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),xe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:_n.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,zy.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Yy(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Yy(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:_n.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=we(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,r)),this.subscription.add(Pe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Fe(this.video,e.playbackRate,i.playbackRateState$,r)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Nn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(pi(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:_n.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},r)).add(i.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(pi(this.hls,tt.Events.MANIFEST_PARSED).pipe(Nn(({levels:l})=>l.reduce((c,d)=>{var S,T;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(T=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?T:nC({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(pi(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(pi(this.hls,tt.Events.LEVEL_LOADING).pipe(Nn(({url:l})=>ue(l))),t.hostname$),s(pi(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Bt(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=pi(this.hls,tt.Events.LEVEL_SWITCHED).pipe(Nn(({level:l})=>n(this.hls.levels[l])));o.pipe(ZD(eC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Bt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(tC(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=rC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,aC(["init"])).pipe(JD(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)}playIfAllowed(){return w(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_n.DOM,thrown:t})))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("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"),P(this.params.desiredState.playbackState,"stopped",!0)}};var Ky="X-Playback-Duration",uc=a=>w(void 0,null,function*(){var i;let e=yield Ze(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Ky)?parseInt(e.headers.get(Ky),10):void 0});import{assertNever as gC,combine as vC,debounce as SC,ErrorCategory as Un,filter as yC,filterChanged as TC,isNonNullable as Zy,isNullable as Hn,map as eT,merge as IC,observableFrom as EC,Subscription as xC,ValueSubject as dc,VideoQuality as PC}from"@vkontakte/videoplayer-shared/es2015";var cc=O(hu(),1);import{videoSizeToQuality as oC,getExponentialDelay as uC}from"@vkontakte/videoplayer-shared/es2015";var lC=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=oC({width:t,height:r})}return e!=null?e:null},cC=(a,e)=>{var s,n;let t=a.split(`
125
+ `),r=[],i=[];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,cc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=lC(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[S,T]=d.RESOLUTION.split("x").map(x=>parseInt(x,10));S&&T&&(g={width:S,height:T})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(c){let d=(0,cc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},dC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),lc=0,Xy=(i,...s)=>w(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield Ze(a,r)).text();lc+=1;try{let{qualityManifests:u,textTracks:l}=cC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(lc<=t.manifestRetryMaxCount)return yield dC(uC(lc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Xy(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Fn=Xy;import{isNonNullable as pC,Subscription as hC,throttle as fC,ValueSubject as Jy,Subject as mC,ErrorCategory as bC}from"@vkontakte/videoplayer-shared/es2015";var qn=class{constructor(e,t,r,i,s){this.subscription=new hC;this.abortControllers={destroy:new me,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Jy(null);this.getCurrentTime$=new Jy(null);this.error$=new mC;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(fC(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return w(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return w(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return w(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield Ze(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
126
+ `),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(pC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([$(I({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return w(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return w(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:bC.WTF,thrown:t,message:e})}};var za=class{constructor(e){this.subscription=new xC;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new dc([]);this.liveOffset=new mt;this.manifestStartTime$=new dc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=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"),P(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((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(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(i==null?void 0:i.to)==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return gC(t)}};var r;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:PC.INVARIANT,url:this.params.source.url};let t=(i,s)=>Fn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new qn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new qe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Un.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Un.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),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(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new dc((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.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&&!i&&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:Un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.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.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(TC(),eT(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.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&&Zy(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(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(i.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(vC({startTime:this.manifestStartTime$.pipe(yC(Zy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(eT(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=IC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,EC(["init"])).pipe(SC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Hn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=fe(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),uc(n).then(c=>{var d;if(!Hn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Hn(p)||!isFinite(p))&&Ze(n).then(h=>h.text()).then(h=>{var b;let f=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(f){let g=new URL(f,n).toString();uc(g).then(v=>{Hn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Un.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()}generateLiveUrl(){let e=fe(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as wC,debounce as AC,ErrorCategory as pc,fromEvent as hc,isNonNullable as kC,isNullable as RC,map as tT,merge as rT,observableFrom as iT,Subscription as $C,ValueSubject as LC,VideoQuality as MC,clientChecker as DC}from"@vkontakte/videoplayer-shared/es2015";var Ka=class{constructor(e){this.subscription=new $C;this.videoState=new C("stopped");this.manifests$=new LC([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=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"),P(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((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return wC(t)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:MC.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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fn(fe(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:pc.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(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.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&&!i&&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:pc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(tT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.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(i.loadedMetadata$.subscribe(()=>{var h;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&&kC(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===f);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(ue(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}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(tT(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)),!DC.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(rT(hc(o,"addtrack"),hc(o,"removetrack"),hc(o,"change"),iT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=rT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,iT(["init"])).pipe(AC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(RC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=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&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var oT=O(Ur(),1),Xa=O(Zr(),1);import{assertNever as CC,assertNonNullable as aT,debounce as BC,ErrorCategory as sT,isHigher as VC,isHigherOrEqual as OC,isInvariantQuality as nT,isLowerOrEqual as _C,isNonNullable as NC,merge as FC,observableFrom as qC,Subscription as UC,map as HC}from"@vkontakte/videoplayer-shared/es2015";var Ja=class{constructor(e){this.subscription=new UC;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new qe;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return CC(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,oT.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Xa.default)(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:sT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(HC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.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&&NC(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=FC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,qC(["init"])).pipe(BC(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),xe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;aT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];aT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ba(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Xa.default)(this.trackUrls).find(d=>!nT(d.track.quality)&&_C(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&&OC(c.quality,u.quality)&&(t=u),!t){let d=(0,Xa.default)(this.trackUrls).filter(h=>!nT(h.track.quality)&&VC(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Xa.default)(this.trackUrls).map(l=>l.track);t=Ft(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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 lT,debounce as WC,merge as cT,observableFrom as YC,Subscription as zC,map as dT,ValueSubject as KC,ErrorCategory as mc,VideoQuality as XC}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as jC}from"@vkontakte/videoplayer-shared/es2015";var uT=["stun:videostun.mycdn.me:80"],GC=1e3,QC=3,fc=()=>null,jn=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=fc;this.externalStopCallback=fc;this.externalErrorCallback=fc;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}}handleUpdateMessage(e){return w(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return w(this,null,function*(){try{let e={iceServers:[{urls:uT}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return w(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return w(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:jC.WTF,message:e.message})}onPeerConnectionStream(e){return w(this,null,function*(){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()))}}createOffer(){return w(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield 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),GC)}normalizeOptions(e={}){let t={stunServerList:uT,maxRetryNumber:QC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Za=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new KC(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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return lT(e)}};this.subscription=new zC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new jn(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.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:mc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};cT(this.videoState.stateChangeStarted$.pipe(dT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(dT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=we(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(He(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Pe(this.video,t.volume,i.volumeState$,r)).add(i.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 lT(n.to)}},r)).add(cT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,YC(["init"])).pipe(WC(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(ue(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:XC.INVARIANT}),this.video.srcObject=e,P(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:mc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var es=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 rs,assertNonNullable as Wt,ErrorCategory as Gn,filter as gT,isNonNullable as vT,isNullable as s0,map as n0,merge as o0,once as u0,Subject as Le,Subscription as ST,ValueSubject as V,flattenObject as yT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as JC,map as pT,Subscription as ZC,Subject as e0}from"@vkontakte/videoplayer-shared/es2015";var hT=a=>new JC(e=>{let t=new ZC,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(pT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(pT(({type:l})=>l!==void 0)),n=new e0,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.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),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as t0,Subscription as r0,combine as i0,filter as mT,once as bT}from"@vkontakte/videoplayer-shared/es2015";function fT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as a0}from"@vkontakte/videoplayer-shared/es2015";var ts=class ts{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new me;this.subscriptions=new r0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(mT(s=>!!s.type),bT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){a0.isSafari&&e!=="MPEG"||this.subscriptions.add(i0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(mT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),bT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return w(this,null,function*(){let{volumeMultiplier:t}=this,r=fT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:ts.errorId,category:t0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${ts.errorId} exception`,thrown:e})}};ts.errorId="VolumeMultiplierManager";var hi=ts;var l0={chunkDuration:5e3,maxParallelRequests:5},is=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new Le;this.noAvailableProvidersError$=new Le;this.volumeMultiplierError$=new Le;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new Le,warning$:new Le,willSeekEvent$:new Le,soundProhibitedEvent$:new Le,seekedEvent$:new Le,loopedEvent$:new Le,endedEvent$:new Le,firstBytesEvent$:new Le,loadedMetadataEvent$:new Le,firstFrameEvent$:new Le,canplay$:new Le,isLive$:new V(void 0),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new ST;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=jv([...Qv(this.params.tuning),...Gv(this.params.tuning)],this.params.tuning).filter(l=>vT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,bc.default)(i,l)),...t.filter(l=>(0,bc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",yT(s)),this.screenFormatsIterator=new es(s);let n=[...El(!0),...El(!1)];this.chromecastFormatsIterator=new es(n.filter(l=>vT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&hi.isSupported()&&(this.volumeMultiplierManager=new hi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(s0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Gn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination: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"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?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}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return rs(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,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":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Wt(o),new Ga($(I({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Qa($(I({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Wt(o),si||!this.params.tuning.useHlsJs?new Ka($(I({},n),{source:o})):new Ya($(I({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new za($(I({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Ja($(I({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new uv($(I({},n),{source:o,config:$(I({},l0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Za({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return rs(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Wt(o),new ji({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,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 rs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return rs(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 rs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);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 $(I({},e),{url:r(e.url)})}return(0,IT.default)((0,TT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new ST,t=!1,r=0;return e.add(o0(this.providerOutput.error$.pipe(gT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),hT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(n0(i=>({id:`ProviderHangup:${i}`,category:Gn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(gT(({to:s})=>s==="playing"),u0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Gn.NETWORK,u=i.category===Gn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=$(I({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",yT(n))})),e}};import{fromEvent as Qn,once as c0,combine as d0,Subscription as ET,ValueSubject as gc,map as p0,filter as h0,isNonNullable as Wn,now as Ve,safeStorage as vc}from"@vkontakte/videoplayer-shared/es2015";var f0=5e3,xT="one_video_throughput",PT="one_video_rtt",yt=window.navigator.connection,wT=()=>{let a=yt==null?void 0:yt.downlink;if(Wn(a)&&a!==10)return a*1e3},AT=()=>{let a=yt==null?void 0:yt.rtt;if(Wn(a)&&a!==3e3)return a},kT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Sc=class a{constructor(e){this.subscription=new ET;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(xT)||(e.useBrowserEstimation?wT():void 0)||f0,r=(s=(i=a.load(PT))!=null?i:e.useBrowserEstimation?AT():void 0)!=null?s:0;if(this.throughput$=new gc(t),this.rtt$=new gc(r),this.rttAdjustedThroughput$=new gc(kT(t,r,e.rttPenaltyRequestSize)),this.throughput=Sr.getSmoothedValue(t,-1,e),this.rtt=Sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=wT();u&&this.throughput.next(u);let l=AT();Wn(l)&&this.rtt.next(l)};yt&&"onchange"in yt&&this.subscription.add(Qn(yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{vc.set(xT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{vc.set(PT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(d0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(p0(({throughput:n,rtt:o})=>kT(n,o,e.rttPenaltyRequestSize)),h0(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=Ve(),i=new ET;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Qn(e,"progress").pipe(c0()).subscribe(s=>{t=s.loaded,r=Ve()}));break;case 1:case 0:i.add(Qn(e,"loadstart").subscribe(()=>{t=0,r=Ve()}));break}i.add(Qn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ve(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Ve(),n=0,o=Ve(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>w(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Ve();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Ve()}else n+=d.byteLength;o=Ve()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ve()-o,this.concurrentDownloads.size),n=0,o=Ve());yield 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,i=!1){if(a.sanityCheck(e,t,i)){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 i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=vc.get(e);if(Wn(t))return(r=parseInt(t,10))!=null?r:void 0}},RT=Sc;import{fillWithDefault as m0,VideoQuality as $T}from"@vkontakte/videoplayer-shared/es2015";var LT={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:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:$T.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:$T.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:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{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:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!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,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,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,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},MT=a=>{var e;return $(I({},m0(a,LT)),{configName:[...(e=a.configName)!=null?e:[],...LT.configName]})};import{assertNonNullable as Yn,combine as Tt,ErrorCategory as zn,filter as Te,filterChanged as W,fromEvent as Tc,isNonNullable as I0,isNullable as E0,Logger as x0,map as G,mapTo as VT,merge as Yt,now as Kn,once as ct,Subject as X,Subscription as OT,tap as _T,ValueSubject as A,isHigher as P0,isInvariantQuality as NT,flattenObject as zt,throttle as Ic,getTraceSubscriptionMethod as FT,Tracer as w0,InternalsExposure as A0}from"@vkontakte/videoplayer-shared/es2015";import{merge as b0,map as g0,filter as DT,isNonNullable as v0}from"@vkontakte/videoplayer-shared/es2015";var yc=({seekState:a,position$:e})=>b0(a.stateChangeEnded$.pipe(g0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),DT(v0)),e.pipe(DT(()=>a.getState().state==="none")));import{assertNonNullable as S0}from"@vkontakte/videoplayer-shared/es2015";var CT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return S0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as y0,once as T0}from"@vkontakte/videoplayer-shared/es2015";var BT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(y0(i=>i.length>0),T0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Xn=class{constructor(e={configName:[]},t=w0.createRootTracer(!1)){this.subscription=new OT;this.logger=new x0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new A("stopped"),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new X,ready$:new X,started$:new X,playing$:new X,paused$:new X,stopped$:new X,willStart$:new X,willResume$:new X,willPause$:new X,willStop$:new X,willDestruct$:new X,watchCoverageRecord$:new X,watchCoverageLive$:new X,managedError$:new X,fatalError$:new X,ended$:new X,looped$:new X,seeked$:new X,willSeek$:new X,autoplaySoundProhibited$:new X,firstBytes$:new X,loadedMetadata$:new X,firstFrame$:new X,canplay$:new X,log$:new X};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Og,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=MT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ps({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new RT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new A0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,qT.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:zn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=sd(i,["container"]);return this.tracer.log("initVideo",zt(r)),this.domContainer=CT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new is({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),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(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Zi()?(this.tracer.log("request play from hidden tab"),Tc(document,"visibilitychange").pipe(ct()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),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.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Yn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Te(r=>r.length>0),ct()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",zt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Yn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",zt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>I({type:"external"},t))),this}selectTextTrack(e){var t;return BT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",I({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.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(E0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return I0(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:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Te(({from:e})=>e==="stopped"),ct()).subscribe(()=>{this.initedAt=Kn(),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();this.tracer.log("willSeekEvent",zt(n)),n.state==="requested"?this.desiredState.seekState.setState($(I({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:zn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ct()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",zt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Tt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>NT(u)?1:NT(l)?-1:P0(l,u)?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.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(W()).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$.pipe(W((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(W((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(W()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(W()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(W()).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(G(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(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Tt({hasLiveOffsetByPaused:Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),W(),G(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(Tt({atLiveEdge:Tt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:yc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),W(),_T(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Tt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),W(),_T(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),W()).subscribe(this.info.volume$)).add(yc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Yt(e.providerOutput.endedEvent$.pipe(VT(!0)),e.providerOutput.seekedEvent$.pipe(VT(!1))).pipe(W()).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.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:zn.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.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(ct(),G(n=>n!=null?n:Kn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ct(),G(()=>Kn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ct(),G(()=>Kn()-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 A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new A(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Te(({to:n})=>n==="playing"),ct()).subscribe(()=>r.next(!1)));let i=0,s=Yt(e.providerOutput.isBuffering$,t,r).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),W());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Yt(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(Yt(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(G(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 OT;this.subscription.add(t),this.subscription.add(e.current$.pipe(W((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Te(r=>r.length>0),ct()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput: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(Yt(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(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;Yn(this.providerContainer),Yn(e),Vg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Bg(r)),this.providerContainer.current$.subscribe(({type:r})=>Wi("provider",r)),e.duration$.subscribe(r=>Wi("duration",r)),e.availableVideoTracks$.pipe(Te(r=>!!r.length),ct()).subscribe(r=>Wi("tracks",r)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(G(r=>r==null?void 0:r.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(r=>this.subscription.add(r)),Wi("codecs",Hv())}initTracerSubscription(){let e=FT(this.tracer.log.bind(this.tracer)),t=FT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(W()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Tt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Te(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),W((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Te(r=>r>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Te(r=>r>0),W()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Tt({currentBuffer:this.info.currentBuffer$.pipe(Te(r=>r.end>0),W((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(W())}).pipe(Ic(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(W()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(W()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(W()).subscribe(e("canChangePlaybackSpeed"))).add(Tt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Te(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Ic(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),Te(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),Te(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(W()).subscribe(e("muted"))).add(this.info.volume$.pipe(W()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(W(),Te(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Tt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Te(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Ic(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),Te(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>w(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:zn.DOM,message:String(i)})})});this.subscription.add(Yt(Tc(document,"visibilitychange"),Tc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",zt({quality:t,availableTracks:zt(e),track:zt(r),isAutoQuality:!r})),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 U4,Observable as H4,Subject as j4,ValueSubject as G4,VideoQuality as Q4}from"@vkontakte/videoplayer-shared/es2015";var W4=`@vkontakte/videoplayer-core@${nd}`;export{Ss as ChromecastState,so as HttpConnectionType,H4 as Observable,Ie as PlaybackState,Xn as Player,W4 as SDK_VERSION,j4 as Subject,U4 as Subscription,no as Surface,nd as VERSION,G4 as ValueSubject,Lt as VideoFormat,Q4 as VideoQuality};