@vkontakte/videoplayer-core 2.0.128-dev.1d1cd071.0 → 2.0.128-dev.3a6dea1e.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,52 +1,52 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.128-dev.1d1cd071.0
3
- * Tue, 04 Mar 2025 10:35:47 GMT
2
+ * @vkontakte/videoplayer-core v2.0.128-dev.3a6dea1e.0
3
+ * Wed, 05 Mar 2025 12:48:34 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-128/doc/
5
5
  */
6
- var uI=Object.create;var uo=Object.defineProperty,lI=Object.defineProperties,cI=Object.getOwnPropertyDescriptor,dI=Object.getOwnPropertyDescriptors,pI=Object.getOwnPropertyNames,vs=Object.getOwnPropertySymbols,hI=Object.getPrototypeOf,lo=Object.prototype.hasOwnProperty,dd=Object.prototype.propertyIsEnumerable;var fI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,cd=(a,e,t)=>e in a?uo(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,E=(a,e)=>{for(var t in e||(e={}))lo.call(e,t)&&cd(a,t,e[t]);if(vs)for(var t of vs(e))dd.call(e,t)&&cd(a,t,e[t]);return a},R=(a,e)=>lI(a,dI(e));var pd=(a,e)=>{var t={};for(var r in a)lo.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&vs)for(var r of vs(a))e.indexOf(r)<0&&dd.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var mI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of pI(e))!lo.call(a,i)&&i!==t&&uo(a,i,{get:()=>e[i],enumerable:!(r=cI(e,i))||r.enumerable});return a};var O=(a,e,t)=>(t=a!=null?uI(hI(a)):{},mI(e||!a||!a.__esModule?uo(t,"default",{value:a,enumerable:!0}):t,a));var P=(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())}),Ss=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 Ss,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[fI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var re=m((ho,fd)=>{"use strict";var Ii=function(a){return a&&a.Math===Math&&a};fd.exports=Ii(typeof globalThis=="object"&&globalThis)||Ii(typeof window=="object"&&window)||Ii(typeof self=="object"&&self)||Ii(typeof global=="object"&&global)||Ii(typeof ho=="object"&&ho)||function(){return this}()||Function("return this")()});var de=m((j0,md)=>{"use strict";md.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ei=m((Q0,bd)=>{"use strict";var bI=de();bd.exports=!bI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var fo=m((G0,yd)=>{"use strict";var gI=Ei(),Sd=Function.prototype,gd=Sd.apply,vd=Sd.call;yd.exports=typeof Reflect=="object"&&Reflect.apply||(gI?vd.bind(gd):function(){return vd.apply(gd,arguments)})});var ne=m((W0,Ed)=>{"use strict";var Td=Ei(),Id=Function.prototype,mo=Id.call,vI=Td&&Id.bind.bind(mo,mo);Ed.exports=Td?vI:function(a){return function(){return mo.apply(a,arguments)}}});var ir=m((Y0,Pd)=>{"use strict";var xd=ne(),SI=xd({}.toString),yI=xd("".slice);Pd.exports=function(a){return yI(SI(a),8,-1)}});var bo=m((z0,wd)=>{"use strict";var TI=ir(),II=ne();wd.exports=function(a){if(TI(a)==="Function")return II(a)}});var ee=m((K0,Ad)=>{"use strict";var go=typeof document=="object"&&document.all;Ad.exports=typeof go=="undefined"&&go!==void 0?function(a){return typeof a=="function"||a===go}:function(a){return typeof a=="function"}});var De=m((X0,kd)=>{"use strict";var EI=de();kd.exports=!EI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ce=m((J0,Ld)=>{"use strict";var xI=Ei(),Is=Function.prototype.call;Ld.exports=xI?Is.bind(Is):function(){return Is.apply(Is,arguments)}});var vo=m(Md=>{"use strict";var Rd={}.propertyIsEnumerable,$d=Object.getOwnPropertyDescriptor,PI=$d&&!Rd.call({1:2},1);Md.f=PI?function(e){var t=$d(this,e);return!!t&&t.enumerable}:Rd});var xi=m((eV,Dd)=>{"use strict";Dd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Vd=m((tV,Cd)=>{"use strict";var wI=ne(),AI=de(),kI=ir(),So=Object,LI=wI("".split);Cd.exports=AI(function(){return!So("z").propertyIsEnumerable(0)})?function(a){return kI(a)==="String"?LI(a,""):So(a)}:So});var Cr=m((rV,Od)=>{"use strict";Od.exports=function(a){return a==null}});var Dt=m((iV,Bd)=>{"use strict";var RI=Cr(),$I=TypeError;Bd.exports=function(a){if(RI(a))throw new $I("Can't call method on "+a);return a}});var ar=m((aV,_d)=>{"use strict";var MI=Vd(),DI=Dt();_d.exports=function(a){return MI(DI(a))}});var Ve=m((sV,Nd)=>{"use strict";var CI=ee();Nd.exports=function(a){return typeof a=="object"?a!==null:CI(a)}});var Vr=m((nV,Fd)=>{"use strict";Fd.exports={}});var ht=m((oV,Ud)=>{"use strict";var yo=Vr(),To=re(),VI=ee(),qd=function(a){return VI(a)?a:void 0};Ud.exports=function(a,e){return arguments.length<2?qd(yo[a])||qd(To[a]):yo[a]&&yo[a][e]||To[a]&&To[a][e]}});var Pi=m((uV,Hd)=>{"use strict";var OI=ne();Hd.exports=OI({}.isPrototypeOf)});var sr=m((lV,Gd)=>{"use strict";var BI=re(),jd=BI.navigator,Qd=jd&&jd.userAgent;Gd.exports=Qd?String(Qd):""});var Eo=m((cV,Jd)=>{"use strict";var Xd=re(),Io=sr(),Wd=Xd.process,Yd=Xd.Deno,zd=Wd&&Wd.versions||Yd&&Yd.version,Kd=zd&&zd.v8,Ye,Es;Kd&&(Ye=Kd.split("."),Es=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!Es&&Io&&(Ye=Io.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=Io.match(/Chrome\/(\d+)/),Ye&&(Es=+Ye[1])));Jd.exports=Es});var xo=m((dV,ep)=>{"use strict";var Zd=Eo(),_I=de(),NI=re(),FI=NI.String;ep.exports=!!Object.getOwnPropertySymbols&&!_I(function(){var a=Symbol("symbol detection");return!FI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Zd&&Zd<41})});var Po=m((pV,tp)=>{"use strict";var qI=xo();tp.exports=qI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var wo=m((hV,rp)=>{"use strict";var UI=ht(),HI=ee(),jI=Pi(),QI=Po(),GI=Object;rp.exports=QI?function(a){return typeof a=="symbol"}:function(a){var e=UI("Symbol");return HI(e)&&jI(e.prototype,GI(a))}});var wi=m((fV,ip)=>{"use strict";var WI=String;ip.exports=function(a){try{return WI(a)}catch(e){return"Object"}}});var at=m((mV,ap)=>{"use strict";var YI=ee(),zI=wi(),KI=TypeError;ap.exports=function(a){if(YI(a))return a;throw new KI(zI(a)+" is not a function")}});var Ai=m((bV,sp)=>{"use strict";var XI=at(),JI=Cr();sp.exports=function(a,e){var t=a[e];return JI(t)?void 0:XI(t)}});var op=m((gV,np)=>{"use strict";var Ao=Ce(),ko=ee(),Lo=Ve(),ZI=TypeError;np.exports=function(a,e){var t,r;if(e==="string"&&ko(t=a.toString)&&!Lo(r=Ao(t,a))||ko(t=a.valueOf)&&!Lo(r=Ao(t,a))||e!=="string"&&ko(t=a.toString)&&!Lo(r=Ao(t,a)))return r;throw new ZI("Can't convert object to primitive value")}});var ze=m((vV,up)=>{"use strict";up.exports=!0});var dp=m((SV,cp)=>{"use strict";var lp=re(),eE=Object.defineProperty;cp.exports=function(a,e){try{eE(lp,a,{value:e,configurable:!0,writable:!0})}catch(t){lp[a]=e}return e}});var ki=m((yV,fp)=>{"use strict";var tE=ze(),rE=re(),iE=dp(),pp="__core-js_shared__",hp=fp.exports=rE[pp]||iE(pp,{});(hp.versions||(hp.versions=[])).push({version:"3.38.0",mode:tE?"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 Ro=m((TV,bp)=>{"use strict";var mp=ki();bp.exports=function(a,e){return mp[a]||(mp[a]=e||{})}});var Or=m((IV,gp)=>{"use strict";var aE=Dt(),sE=Object;gp.exports=function(a){return sE(aE(a))}});var Ke=m((EV,vp)=>{"use strict";var nE=ne(),oE=Or(),uE=nE({}.hasOwnProperty);vp.exports=Object.hasOwn||function(e,t){return uE(oE(e),t)}});var $o=m((xV,Sp)=>{"use strict";var lE=ne(),cE=0,dE=Math.random(),pE=lE(1 .toString);Sp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+pE(++cE+dE,36)}});var pe=m((PV,Tp)=>{"use strict";var hE=re(),fE=Ro(),yp=Ke(),mE=$o(),bE=xo(),gE=Po(),Br=hE.Symbol,Mo=fE("wks"),vE=gE?Br.for||Br:Br&&Br.withoutSetter||mE;Tp.exports=function(a){return yp(Mo,a)||(Mo[a]=bE&&yp(Br,a)?Br[a]:vE("Symbol."+a)),Mo[a]}});var Pp=m((wV,xp)=>{"use strict";var SE=Ce(),Ip=Ve(),Ep=wo(),yE=Ai(),TE=op(),IE=pe(),EE=TypeError,xE=IE("toPrimitive");xp.exports=function(a,e){if(!Ip(a)||Ep(a))return a;var t=yE(a,xE),r;if(t){if(e===void 0&&(e="default"),r=SE(t,a,e),!Ip(r)||Ep(r))return r;throw new EE("Can't convert object to primitive value")}return e===void 0&&(e="number"),TE(a,e)}});var Do=m((AV,wp)=>{"use strict";var PE=Pp(),wE=wo();wp.exports=function(a){var e=PE(a,"string");return wE(e)?e:e+""}});var xs=m((kV,kp)=>{"use strict";var AE=re(),Ap=Ve(),Co=AE.document,kE=Ap(Co)&&Ap(Co.createElement);kp.exports=function(a){return kE?Co.createElement(a):{}}});var Vo=m((LV,Lp)=>{"use strict";var LE=De(),RE=de(),$E=xs();Lp.exports=!LE&&!RE(function(){return Object.defineProperty($E("div"),"a",{get:function(){return 7}}).a!==7})});var Mp=m($p=>{"use strict";var ME=De(),DE=Ce(),CE=vo(),VE=xi(),OE=ar(),BE=Do(),_E=Ke(),NE=Vo(),Rp=Object.getOwnPropertyDescriptor;$p.f=ME?Rp:function(e,t){if(e=OE(e),t=BE(t),NE)try{return Rp(e,t)}catch(r){}if(_E(e,t))return VE(!DE(CE.f,e,t),e[t])}});var Oo=m(($V,Dp)=>{"use strict";var FE=de(),qE=ee(),UE=/#|\.prototype\./,Li=function(a,e){var t=jE[HE(a)];return t===GE?!0:t===QE?!1:qE(e)?FE(e):!!e},HE=Li.normalize=function(a){return String(a).replace(UE,".").toLowerCase()},jE=Li.data={},QE=Li.NATIVE="N",GE=Li.POLYFILL="P";Dp.exports=Li});var _r=m((MV,Vp)=>{"use strict";var Cp=bo(),WE=at(),YE=Ei(),zE=Cp(Cp.bind);Vp.exports=function(a,e){return WE(a),e===void 0?a:YE?zE(a,e):function(){return a.apply(e,arguments)}}});var Bo=m((DV,Op)=>{"use strict";var KE=De(),XE=de();Op.exports=KE&&XE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=m((CV,Bp)=>{"use strict";var JE=Ve(),ZE=String,ex=TypeError;Bp.exports=function(a){if(JE(a))return a;throw new ex(ZE(a)+" is not an object")}});var nr=m(Np=>{"use strict";var tx=De(),rx=Vo(),ix=Bo(),Ps=st(),_p=Do(),ax=TypeError,_o=Object.defineProperty,sx=Object.getOwnPropertyDescriptor,No="enumerable",Fo="configurable",qo="writable";Np.f=tx?ix?function(e,t,r){if(Ps(e),t=_p(t),Ps(r),typeof e=="function"&&t==="prototype"&&"value"in r&&qo in r&&!r[qo]){var i=sx(e,t);i&&i[qo]&&(e[t]=r.value,r={configurable:Fo in r?r[Fo]:i[Fo],enumerable:No in r?r[No]:i[No],writable:!1})}return _o(e,t,r)}:_o:function(e,t,r){if(Ps(e),t=_p(t),Ps(r),rx)try{return _o(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new ax("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Nr=m((OV,Fp)=>{"use strict";var nx=De(),ox=nr(),ux=xi();Fp.exports=nx?function(a,e,t){return ox.f(a,e,ux(1,t))}:function(a,e,t){return a[e]=t,a}});var se=m((BV,Up)=>{"use strict";var Ri=re(),lx=fo(),cx=bo(),dx=ee(),px=Mp().f,hx=Oo(),Fr=Vr(),fx=_r(),qr=Nr(),qp=Ke();ki();var mx=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 lx(a,this,arguments)};return e.prototype=a.prototype,e};Up.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?Fr:Fr[t]||qr(Fr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,v;for(p in e)l=hx(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&qp(n,p),f=o[p],c&&(a.dontCallGetSet?(v=px(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=fx(h,Ri):a.wrap&&c?g=mx(h):s&&dx(h)?g=cx(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&qr(g,"sham",!0),qr(o,p,g),s&&(d=t+"Prototype",qp(Fr,d)||qr(Fr,d,{}),qr(Fr[d],p,h),a.real&&u&&(l||!u[p])&&qr(u,p,h)))}});var jp=m((_V,Hp)=>{"use strict";var bx=Math.ceil,gx=Math.floor;Hp.exports=Math.trunc||function(e){var t=+e;return(t>0?gx:bx)(t)}});var $i=m((NV,Qp)=>{"use strict";var vx=jp();Qp.exports=function(a){var e=+a;return e!==e||e===0?0:vx(e)}});var Wp=m((FV,Gp)=>{"use strict";var Sx=$i(),yx=Math.max,Tx=Math.min;Gp.exports=function(a,e){var t=Sx(a);return t<0?yx(t+e,0):Tx(t,e)}});var Uo=m((qV,Yp)=>{"use strict";var Ix=$i(),Ex=Math.min;Yp.exports=function(a){var e=Ix(a);return e>0?Ex(e,9007199254740991):0}});var Ur=m((UV,zp)=>{"use strict";var xx=Uo();zp.exports=function(a){return xx(a.length)}});var Ho=m((HV,Xp)=>{"use strict";var Px=ar(),wx=Wp(),Ax=Ur(),Kp=function(a){return function(e,t,r){var i=Px(e),s=Ax(i);if(s===0)return!a&&-1;var n=wx(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}};Xp.exports={includes:Kp(!0),indexOf:Kp(!1)}});var Mi=m((jV,Jp)=>{"use strict";Jp.exports=function(){}});var Zp=m(()=>{"use strict";var kx=se(),Lx=Ho().includes,Rx=de(),$x=Mi(),Mx=Rx(function(){return!Array(1).includes()});kx({target:"Array",proto:!0,forced:Mx},{includes:function(e){return Lx(this,e,arguments.length>1?arguments[1]:void 0)}});$x("includes")});var Ct=m((WV,eh)=>{"use strict";var Dx=ht();eh.exports=Dx});var rh=m((YV,th)=>{"use strict";Zp();var Cx=Ct();th.exports=Cx("Array","includes")});var ah=m((zV,ih)=>{"use strict";var Vx=rh();ih.exports=Vx});var Xe=m((KV,sh)=>{"use strict";var Ox=ah();sh.exports=Ox});var ks=m((uO,hh)=>{"use strict";var jx=Ro(),Qx=$o(),ph=jx("keys");hh.exports=function(a){return ph[a]||(ph[a]=Qx(a))}});var mh=m((lO,fh)=>{"use strict";var Gx=de();fh.exports=!Gx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Ls=m((cO,gh)=>{"use strict";var Wx=Ke(),Yx=ee(),zx=Or(),Kx=ks(),Xx=mh(),bh=Kx("IE_PROTO"),Go=Object,Jx=Go.prototype;gh.exports=Xx?Go.getPrototypeOf:function(a){var e=zx(a);if(Wx(e,bh))return e[bh];var t=e.constructor;return Yx(t)&&e instanceof t?t.prototype:e instanceof Go?Jx:null}});var Rs=m((dO,vh)=>{"use strict";vh.exports={}});var Th=m((pO,yh)=>{"use strict";var Zx=ne(),Wo=Ke(),eP=ar(),tP=Ho().indexOf,rP=Rs(),Sh=Zx([].push);yh.exports=function(a,e){var t=eP(a),r=0,i=[],s;for(s in t)!Wo(rP,s)&&Wo(t,s)&&Sh(i,s);for(;e.length>r;)Wo(t,s=e[r++])&&(~tP(i,s)||Sh(i,s));return i}});var Yo=m((hO,Ih)=>{"use strict";Ih.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var zo=m((fO,Eh)=>{"use strict";var iP=Th(),aP=Yo();Eh.exports=Object.keys||function(e){return iP(e,aP)}});var Ko=m((mO,kh)=>{"use strict";var Ph=De(),sP=de(),wh=ne(),nP=Ls(),oP=zo(),uP=ar(),lP=vo().f,Ah=wh(lP),cP=wh([].push),dP=Ph&&sP(function(){var a=Object.create(null);return a[2]=2,!Ah(a,2)}),xh=function(a){return function(e){for(var t=uP(e),r=oP(t),i=dP&&nP(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Ph||(i?u in t:Ah(t,u)))&&cP(o,a?[u,t[u]]:t[u]);return o}};kh.exports={entries:xh(!0),values:xh(!1)}});var Lh=m(()=>{"use strict";var pP=se(),hP=Ko().entries;pP({target:"Object",stat:!0},{entries:function(e){return hP(e)}})});var $h=m((vO,Rh)=>{"use strict";Lh();var fP=Vr();Rh.exports=fP.Object.entries});var Dh=m((SO,Mh)=>{"use strict";var mP=$h();Mh.exports=mP});var Hr=m((yO,Ch)=>{"use strict";var bP=Dh();Ch.exports=bP});var or=m((TO,Vh)=>{"use strict";Vh.exports={}});var _h=m((IO,Bh)=>{"use strict";var gP=re(),vP=ee(),Oh=gP.WeakMap;Bh.exports=vP(Oh)&&/native code/.test(String(Oh))});var eu=m((EO,qh)=>{"use strict";var SP=_h(),Fh=re(),yP=Ve(),TP=Nr(),Xo=Ke(),Jo=ki(),IP=ks(),EP=Rs(),Nh="Object already initialized",Zo=Fh.TypeError,xP=Fh.WeakMap,$s,Di,Ms,PP=function(a){return Ms(a)?Di(a):$s(a,{})},wP=function(a){return function(e){var t;if(!yP(e)||(t=Di(e)).type!==a)throw new Zo("Incompatible receiver, "+a+" required");return t}};SP||Jo.state?(Je=Jo.state||(Jo.state=new xP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,$s=function(a,e){if(Je.has(a))throw new Zo(Nh);return e.facade=a,Je.set(a,e),e},Di=function(a){return Je.get(a)||{}},Ms=function(a){return Je.has(a)}):(ur=IP("state"),EP[ur]=!0,$s=function(a,e){if(Xo(a,ur))throw new Zo(Nh);return e.facade=a,TP(a,ur,e),e},Di=function(a){return Xo(a,ur)?a[ur]:{}},Ms=function(a){return Xo(a,ur)});var Je,ur;qh.exports={set:$s,get:Di,has:Ms,enforce:PP,getterFor:wP}});var iu=m((xO,Hh)=>{"use strict";var tu=De(),AP=Ke(),Uh=Function.prototype,kP=tu&&Object.getOwnPropertyDescriptor,ru=AP(Uh,"name"),LP=ru&&function(){}.name==="something",RP=ru&&(!tu||tu&&kP(Uh,"name").configurable);Hh.exports={EXISTS:ru,PROPER:LP,CONFIGURABLE:RP}});var Qh=m(jh=>{"use strict";var $P=De(),MP=Bo(),DP=nr(),CP=st(),VP=ar(),OP=zo();jh.f=$P&&!MP?Object.defineProperties:function(e,t){CP(e);for(var r=VP(t),i=OP(t),s=i.length,n=0,o;s>n;)DP.f(e,o=i[n++],r[o]);return e}});var au=m((wO,Gh)=>{"use strict";var BP=ht();Gh.exports=BP("document","documentElement")});var uu=m((AO,Zh)=>{"use strict";var _P=st(),NP=Qh(),Wh=Yo(),FP=Rs(),qP=au(),UP=xs(),HP=ks(),Yh=">",zh="<",nu="prototype",ou="script",Xh=HP("IE_PROTO"),su=function(){},Jh=function(a){return zh+ou+Yh+a+zh+"/"+ou+Yh},Kh=function(a){a.write(Jh("")),a.close();var e=a.parentWindow.Object;return a=null,e},jP=function(){var a=UP("iframe"),e="java"+ou+":",t;return a.style.display="none",qP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Jh("document.F=Object")),t.close(),t.F},Ds,Cs=function(){try{Ds=new ActiveXObject("htmlfile")}catch(e){}Cs=typeof document!="undefined"?document.domain&&Ds?Kh(Ds):jP():Kh(Ds);for(var a=Wh.length;a--;)delete Cs[nu][Wh[a]];return Cs()};FP[Xh]=!0;Zh.exports=Object.create||function(e,t){var r;return e!==null?(su[nu]=_P(e),r=new su,su[nu]=null,r[Xh]=e):r=Cs(),t===void 0?r:NP.f(r,t)}});var jr=m((kO,ef)=>{"use strict";var QP=Nr();ef.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:QP(a,e,t),a}});var pu=m((LO,af)=>{"use strict";var GP=de(),WP=ee(),YP=Ve(),zP=uu(),tf=Ls(),KP=jr(),XP=pe(),JP=ze(),du=XP("iterator"),rf=!1,ft,lu,cu;[].keys&&(cu=[].keys(),"next"in cu?(lu=tf(tf(cu)),lu!==Object.prototype&&(ft=lu)):rf=!0);var ZP=!YP(ft)||GP(function(){var a={};return ft[du].call(a)!==a});ZP?ft={}:JP&&(ft=zP(ft));WP(ft[du])||KP(ft,du,function(){return this});af.exports={IteratorPrototype:ft,BUGGY_SAFARI_ITERATORS:rf}});var Vs=m((RO,nf)=>{"use strict";var ew=pe(),tw=ew("toStringTag"),sf={};sf[tw]="z";nf.exports=String(sf)==="[object z]"});var Ci=m(($O,of)=>{"use strict";var rw=Vs(),iw=ee(),Os=ir(),aw=pe(),sw=aw("toStringTag"),nw=Object,ow=Os(function(){return arguments}())==="Arguments",uw=function(a,e){try{return a[e]}catch(t){}};of.exports=rw?Os:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=uw(e=nw(a),sw))=="string"?t:ow?Os(e):(r=Os(e))==="Object"&&iw(e.callee)?"Arguments":r}});var lf=m((MO,uf)=>{"use strict";var lw=Vs(),cw=Ci();uf.exports=lw?{}.toString:function(){return"[object "+cw(this)+"]"}});var Vi=m((DO,df)=>{"use strict";var dw=Vs(),pw=nr().f,hw=Nr(),fw=Ke(),mw=lf(),bw=pe(),cf=bw("toStringTag");df.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(fw(i,cf)||pw(i,cf,{configurable:!0,value:e}),r&&!dw&&hw(i,"toString",mw))}});var hf=m((CO,pf)=>{"use strict";var gw=pu().IteratorPrototype,vw=uu(),Sw=xi(),yw=Vi(),Tw=or(),Iw=function(){return this};pf.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=vw(gw,{next:Sw(+!r,t)}),yw(a,i,!1,!0),Tw[i]=Iw,a}});var mf=m((VO,ff)=>{"use strict";var Ew=ne(),xw=at();ff.exports=function(a,e,t){try{return Ew(xw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var gf=m((OO,bf)=>{"use strict";var Pw=Ve();bf.exports=function(a){return Pw(a)||a===null}});var Sf=m((BO,vf)=>{"use strict";var ww=gf(),Aw=String,kw=TypeError;vf.exports=function(a){if(ww(a))return a;throw new kw("Can't set "+Aw(a)+" as a prototype")}});var hu=m((_O,yf)=>{"use strict";var Lw=mf(),Rw=Ve(),$w=Dt(),Mw=Sf();yf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Lw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return $w(i),Mw(s),Rw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var $f=m((NO,Rf)=>{"use strict";var Dw=se(),Cw=Ce(),Bs=ze(),kf=iu(),Vw=ee(),Ow=hf(),Tf=Ls(),If=hu(),Bw=Vi(),_w=Nr(),fu=jr(),Nw=pe(),Ef=or(),Lf=pu(),Fw=kf.PROPER,qw=kf.CONFIGURABLE,xf=Lf.IteratorPrototype,_s=Lf.BUGGY_SAFARI_ITERATORS,Oi=Nw("iterator"),Pf="keys",Bi="values",wf="entries",Af=function(){return this};Rf.exports=function(a,e,t,r,i,s,n){Ow(t,e,r);var o=function(v){if(v===i&&p)return p;if(!_s&&v&&v in c)return c[v];switch(v){case Pf:return function(){return new t(this,v)};case Bi:return function(){return new t(this,v)};case wf:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Oi]||c["@@iterator"]||i&&c[i],p=!_s&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Tf(h.call(new a)),f!==Object.prototype&&f.next&&(!Bs&&Tf(f)!==xf&&(If?If(f,xf):Vw(f[Oi])||fu(f,Oi,Af)),Bw(f,u,!0,!0),Bs&&(Ef[u]=Af))),Fw&&i===Bi&&d&&d.name!==Bi&&(!Bs&&qw?_w(c,"name",Bi):(l=!0,p=function(){return Cw(d,this)})),i)if(b={values:o(Bi),keys:s?p:o(Pf),entries:o(wf)},n)for(g in b)(_s||l||!(g in c))&&fu(c,g,b[g]);else Dw({target:e,proto:!0,forced:_s||l},b);return(!Bs||n)&&c[Oi]!==p&&fu(c,Oi,p,{name:i}),Ef[e]=p,b}});var Df=m((FO,Mf)=>{"use strict";Mf.exports=function(a,e){return{value:a,done:e}}});var bu=m((qO,_f)=>{"use strict";var Uw=ar(),mu=Mi(),Cf=or(),Of=eu(),Hw=nr().f,jw=$f(),Ns=Df(),Qw=ze(),Gw=De(),Bf="Array Iterator",Ww=Of.set,Yw=Of.getterFor(Bf);_f.exports=jw(Array,"Array",function(a,e){Ww(this,{type:Bf,target:Uw(a),index:0,kind:e})},function(){var a=Yw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ns(void 0,!0);switch(a.kind){case"keys":return Ns(t,!1);case"values":return Ns(e[t],!1)}return Ns([t,e[t]],!1)},"values");var Vf=Cf.Arguments=Cf.Array;mu("keys");mu("values");mu("entries");if(!Qw&&Gw&&Vf.name!=="values")try{Hw(Vf,"name",{value:"values"})}catch(a){}});var Ff=m((UO,Nf)=>{"use strict";var zw=pe(),Kw=or(),Xw=zw("iterator"),Jw=Array.prototype;Nf.exports=function(a){return a!==void 0&&(Kw.Array===a||Jw[Xw]===a)}});var gu=m((HO,Uf)=>{"use strict";var Zw=Ci(),qf=Ai(),eA=Cr(),tA=or(),rA=pe(),iA=rA("iterator");Uf.exports=function(a){if(!eA(a))return qf(a,iA)||qf(a,"@@iterator")||tA[Zw(a)]}});var jf=m((jO,Hf)=>{"use strict";var aA=Ce(),sA=at(),nA=st(),oA=wi(),uA=gu(),lA=TypeError;Hf.exports=function(a,e){var t=arguments.length<2?uA(a):e;if(sA(t))return nA(aA(t,a));throw new lA(oA(a)+" is not iterable")}});var Wf=m((QO,Gf)=>{"use strict";var cA=Ce(),Qf=st(),dA=Ai();Gf.exports=function(a,e,t){var r,i;Qf(a);try{if(r=dA(a,"return"),!r){if(e==="throw")throw t;return t}r=cA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Qf(r),t}});var qs=m((GO,Xf)=>{"use strict";var pA=_r(),hA=Ce(),fA=st(),mA=wi(),bA=Ff(),gA=Ur(),Yf=Pi(),vA=jf(),SA=gu(),zf=Wf(),yA=TypeError,Fs=function(a,e){this.stopped=a,this.result=e},Kf=Fs.prototype;Xf.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=pA(e,r),l,c,d,p,h,f,b,g=function(S){return l&&zf(l,"normal",S),new Fs(!0,S)},v=function(S){return i?(fA(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=SA(a),!c)throw new yA(mA(a)+" is not iterable");if(bA(c)){for(d=0,p=gA(a);p>d;d++)if(h=v(a[d]),h&&Yf(Kf,h))return h;return new Fs(!1)}l=vA(a,c)}for(f=s?a.next:l.next;!(b=hA(f,l)).done;){try{h=v(b.value)}catch(S){zf(l,"throw",S)}if(typeof h=="object"&&h&&Yf(Kf,h))return h}return new Fs(!1)}});var Zf=m((WO,Jf)=>{"use strict";var TA=De(),IA=nr(),EA=xi();Jf.exports=function(a,e,t){TA?IA.f(a,e,EA(0,t)):a[e]=t}});var em=m(()=>{"use strict";var xA=se(),PA=qs(),wA=Zf();xA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return PA(e,function(r,i){wA(t,r,i)},{AS_ENTRIES:!0}),t}})});var rm=m((KO,tm)=>{"use strict";bu();em();var AA=Vr();tm.exports=AA.Object.fromEntries});var am=m((XO,im)=>{"use strict";im.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 nm=m(()=>{"use strict";bu();var kA=am(),LA=re(),RA=Vi(),sm=or();for(Us in kA)RA(LA[Us],Us),sm[Us]=sm.Array;var Us});var um=m((eB,om)=>{"use strict";var $A=rm();nm();om.exports=$A});var vu=m((tB,lm)=>{"use strict";var MA=um();lm.exports=MA});var cm=m(()=>{"use strict"});var Su=m((aB,dm)=>{"use strict";var _i=re(),DA=sr(),CA=ir(),Hs=function(a){return DA.slice(0,a.length)===a};dm.exports=function(){return Hs("Bun/")?"BUN":Hs("Cloudflare-Workers")?"CLOUDFLARE":Hs("Deno/")?"DENO":Hs("Node.js/")?"NODE":_i.Bun&&typeof Bun.version=="string"?"BUN":_i.Deno&&typeof Deno.version=="object"?"DENO":CA(_i.process)==="process"?"NODE":_i.window&&_i.document?"BROWSER":"REST"}()});var js=m((sB,pm)=>{"use strict";var VA=Su();pm.exports=VA==="NODE"});var fm=m((nB,hm)=>{"use strict";var OA=nr();hm.exports=function(a,e,t){return OA.f(a,e,t)}});var gm=m((oB,bm)=>{"use strict";var BA=ht(),_A=fm(),NA=pe(),FA=De(),mm=NA("species");bm.exports=function(a){var e=BA(a);FA&&e&&!e[mm]&&_A(e,mm,{configurable:!0,get:function(){return this}})}});var Sm=m((uB,vm)=>{"use strict";var qA=Pi(),UA=TypeError;vm.exports=function(a,e){if(qA(e,a))return a;throw new UA("Incorrect invocation")}});var Tu=m((lB,ym)=>{"use strict";var HA=ne(),jA=ee(),yu=ki(),QA=HA(Function.toString);jA(yu.inspectSource)||(yu.inspectSource=function(a){return QA(a)});ym.exports=yu.inspectSource});var Eu=m((cB,Pm)=>{"use strict";var GA=ne(),WA=de(),Tm=ee(),YA=Ci(),zA=ht(),KA=Tu(),Im=function(){},Em=zA("Reflect","construct"),Iu=/^\s*(?:class|function)\b/,XA=GA(Iu.exec),JA=!Iu.test(Im),Ni=function(e){if(!Tm(e))return!1;try{return Em(Im,[],e),!0}catch(t){return!1}},xm=function(e){if(!Tm(e))return!1;switch(YA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return JA||!!XA(Iu,KA(e))}catch(t){return!0}};xm.sham=!0;Pm.exports=!Em||WA(function(){var a;return Ni(Ni.call)||!Ni(Object)||!Ni(function(){a=!0})||a})?xm:Ni});var Am=m((dB,wm)=>{"use strict";var ZA=Eu(),ek=wi(),tk=TypeError;wm.exports=function(a){if(ZA(a))return a;throw new tk(ek(a)+" is not a constructor")}});var xu=m((pB,Lm)=>{"use strict";var km=st(),rk=Am(),ik=Cr(),ak=pe(),sk=ak("species");Lm.exports=function(a,e){var t=km(a).constructor,r;return t===void 0||ik(r=km(t)[sk])?e:rk(r)}});var $m=m((hB,Rm)=>{"use strict";var nk=ne();Rm.exports=nk([].slice)});var Dm=m((fB,Mm)=>{"use strict";var ok=TypeError;Mm.exports=function(a,e){if(a<e)throw new ok("Not enough arguments");return a}});var Pu=m((mB,Cm)=>{"use strict";var uk=sr();Cm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(uk)});var Cu=m((bB,Hm)=>{"use strict";var Oe=re(),lk=fo(),ck=_r(),Vm=ee(),dk=Ke(),Um=de(),Om=au(),pk=$m(),Bm=xs(),hk=Dm(),fk=Pu(),mk=js(),$u=Oe.setImmediate,Mu=Oe.clearImmediate,bk=Oe.process,wu=Oe.Dispatch,gk=Oe.Function,_m=Oe.MessageChannel,vk=Oe.String,Au=0,Fi={},Nm="onreadystatechange",qi,lr,ku,Lu;Um(function(){qi=Oe.location});var Du=function(a){if(dk(Fi,a)){var e=Fi[a];delete Fi[a],e()}},Ru=function(a){return function(){Du(a)}},Fm=function(a){Du(a.data)},qm=function(a){Oe.postMessage(vk(a),qi.protocol+"//"+qi.host)};(!$u||!Mu)&&($u=function(e){hk(arguments.length,1);var t=Vm(e)?e:gk(e),r=pk(arguments,1);return Fi[++Au]=function(){lk(t,void 0,r)},lr(Au),Au},Mu=function(e){delete Fi[e]},mk?lr=function(a){bk.nextTick(Ru(a))}:wu&&wu.now?lr=function(a){wu.now(Ru(a))}:_m&&!fk?(ku=new _m,Lu=ku.port2,ku.port1.onmessage=Fm,lr=ck(Lu.postMessage,Lu)):Oe.addEventListener&&Vm(Oe.postMessage)&&!Oe.importScripts&&qi&&qi.protocol!=="file:"&&!Um(qm)?(lr=qm,Oe.addEventListener("message",Fm,!1)):Nm in Bm("script")?lr=function(a){Om.appendChild(Bm("script"))[Nm]=function(){Om.removeChild(this),Du(a)}}:lr=function(a){setTimeout(Ru(a),0)});Hm.exports={set:$u,clear:Mu}});var Gm=m((gB,Qm)=>{"use strict";var jm=re(),Sk=De(),yk=Object.getOwnPropertyDescriptor;Qm.exports=function(a){if(!Sk)return jm[a];var e=yk(jm,a);return e&&e.value}});var Vu=m((vB,Ym)=>{"use strict";var Wm=function(){this.head=null,this.tail=null};Wm.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}}};Ym.exports=Wm});var Km=m((SB,zm)=>{"use strict";var Tk=sr();zm.exports=/ipad|iphone|ipod/i.test(Tk)&&typeof Pebble!="undefined"});var Jm=m((yB,Xm)=>{"use strict";var Ik=sr();Xm.exports=/web0s(?!.*chrome)/i.test(Ik)});var sb=m((TB,ab)=>{"use strict";var Gr=re(),Ek=Gm(),Zm=_r(),Ou=Cu().set,xk=Vu(),Pk=Pu(),wk=Km(),Ak=Jm(),Bu=js(),eb=Gr.MutationObserver||Gr.WebKitMutationObserver,tb=Gr.document,rb=Gr.process,Qs=Gr.Promise,Fu=Ek("queueMicrotask"),Qr,_u,Nu,Gs,ib;Fu||(Ui=new xk,Hi=function(){var a,e;for(Bu&&(a=rb.domain)&&a.exit();e=Ui.get();)try{e()}catch(t){throw Ui.head&&Qr(),t}a&&a.enter()},!Pk&&!Bu&&!Ak&&eb&&tb?(_u=!0,Nu=tb.createTextNode(""),new eb(Hi).observe(Nu,{characterData:!0}),Qr=function(){Nu.data=_u=!_u}):!wk&&Qs&&Qs.resolve?(Gs=Qs.resolve(void 0),Gs.constructor=Qs,ib=Zm(Gs.then,Gs),Qr=function(){ib(Hi)}):Bu?Qr=function(){rb.nextTick(Hi)}:(Ou=Zm(Ou,Gr),Qr=function(){Ou(Hi)}),Fu=function(a){Ui.head||Qr(),Ui.add(a)});var Ui,Hi;ab.exports=Fu});var ob=m((IB,nb)=>{"use strict";nb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ws=m((EB,ub)=>{"use strict";ub.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var cr=m((xB,lb)=>{"use strict";var kk=re();lb.exports=kk.Promise});var Wr=m((PB,hb)=>{"use strict";var Lk=re(),ji=cr(),Rk=ee(),$k=Oo(),Mk=Tu(),Dk=pe(),cb=Su(),Ck=ze(),qu=Eo(),db=ji&&ji.prototype,Vk=Dk("species"),Uu=!1,pb=Rk(Lk.PromiseRejectionEvent),Ok=$k("Promise",function(){var a=Mk(ji),e=a!==String(ji);if(!e&&qu===66||Ck&&!(db.catch&&db.finally))return!0;if(!qu||qu<51||!/native code/.test(a)){var t=new ji(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Vk]=r,Uu=t.then(function(){})instanceof r,!Uu)return!0}return!e&&(cb==="BROWSER"||cb==="DENO")&&!pb});hb.exports={CONSTRUCTOR:Ok,REJECTION_EVENT:pb,SUBCLASSING:Uu}});var Yr=m((wB,mb)=>{"use strict";var fb=at(),Bk=TypeError,_k=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Bk("Bad Promise constructor");e=r,t=i}),this.resolve=fb(e),this.reject=fb(t)};mb.exports.f=function(a){return new _k(a)}});var Cb=m(()=>{"use strict";var Nk=se(),Fk=ze(),Xs=js(),Vt=re(),Jr=Ce(),bb=jr(),gb=hu(),qk=Vi(),Uk=gm(),Hk=at(),Ks=ee(),jk=Ve(),Qk=Sm(),Gk=xu(),Ib=Cu().set,Wu=sb(),Wk=ob(),Yk=Ws(),zk=Vu(),Eb=eu(),Js=cr(),Yu=Wr(),xb=Yr(),Zs="Promise",Pb=Yu.CONSTRUCTOR,Kk=Yu.REJECTION_EVENT,Xk=Yu.SUBCLASSING,Hu=Eb.getterFor(Zs),Jk=Eb.set,zr=Js&&Js.prototype,dr=Js,Ys=zr,wb=Vt.TypeError,ju=Vt.document,zu=Vt.process,Qu=xb.f,Zk=Qu,eL=!!(ju&&ju.createEvent&&Vt.dispatchEvent),Ab="unhandledrejection",tL="rejectionhandled",vb=0,kb=1,rL=2,Ku=1,Lb=2,zs,Sb,iL,yb,Rb=function(a){var e;return jk(a)&&Ks(e=a.then)?e:!1},$b=function(a,e){var t=e.value,r=e.state===kb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Lb&&sL(e),e.rejection=Ku),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new wb("Promise-chain cycle")):(l=Rb(u))?Jr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Mb=function(a,e){a.notified||(a.notified=!0,Wu(function(){for(var t=a.reactions,r;r=t.get();)$b(r,a);a.notified=!1,e&&!a.rejection&&aL(a)}))},Db=function(a,e,t){var r,i;eL?(r=ju.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Vt.dispatchEvent(r)):r={promise:e,reason:t},!Kk&&(i=Vt["on"+a])?i(r):a===Ab&&Wk("Unhandled promise rejection",t)},aL=function(a){Jr(Ib,Vt,function(){var e=a.facade,t=a.value,r=Tb(a),i;if(r&&(i=Yk(function(){Xs?zu.emit("unhandledRejection",t,e):Db(Ab,e,t)}),a.rejection=Xs||Tb(a)?Lb:Ku,i.error))throw i.value})},Tb=function(a){return a.rejection!==Ku&&!a.parent},sL=function(a){Jr(Ib,Vt,function(){var e=a.facade;Xs?zu.emit("rejectionHandled",e):Db(tL,e,a.value)})},Kr=function(a,e,t){return function(r){a(e,r,t)}},Xr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=rL,Mb(a,!0))},Gu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new wb("Promise can't be resolved itself");var r=Rb(e);r?Wu(function(){var i={done:!1};try{Jr(r,e,Kr(Gu,i,a),Kr(Xr,i,a))}catch(s){Xr(i,s,a)}}):(a.value=e,a.state=kb,Mb(a,!1))}catch(i){Xr({done:!1},i,a)}}};if(Pb&&(dr=function(e){Qk(this,Ys),Hk(e),Jr(zs,this);var t=Hu(this);try{e(Kr(Gu,t),Kr(Xr,t))}catch(r){Xr(t,r)}},Ys=dr.prototype,zs=function(e){Jk(this,{type:Zs,done:!1,notified:!1,parent:!1,reactions:new zk,rejection:!1,state:vb,value:void 0})},zs.prototype=bb(Ys,"then",function(e,t){var r=Hu(this),i=Qu(Gk(this,dr));return r.parent=!0,i.ok=Ks(e)?e:!0,i.fail=Ks(t)&&t,i.domain=Xs?zu.domain:void 0,r.state===vb?r.reactions.add(i):Wu(function(){$b(i,r)}),i.promise}),Sb=function(){var a=new zs,e=Hu(a);this.promise=a,this.resolve=Kr(Gu,e),this.reject=Kr(Xr,e)},xb.f=Qu=function(a){return a===dr||a===iL?new Sb(a):Zk(a)},!Fk&&Ks(Js)&&zr!==Object.prototype)){yb=zr.then,Xk||bb(zr,"then",function(e,t){var r=this;return new dr(function(i,s){Jr(yb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete zr.constructor}catch(a){}gb&&gb(zr,Ys)}Nk({global:!0,constructor:!0,wrap:!0,forced:Pb},{Promise:dr});qk(dr,Zs,!1,!0);Uk(Zs)});var Nb=m((LB,_b)=>{"use strict";var nL=pe(),Ob=nL("iterator"),Bb=!1;try{Vb=0,Xu={next:function(){return{done:!!Vb++}},return:function(){Bb=!0}},Xu[Ob]=function(){return this},Array.from(Xu,function(){throw 2})}catch(a){}var Vb,Xu;_b.exports=function(a,e){try{if(!e&&!Bb)return!1}catch(i){return!1}var t=!1;try{var r={};r[Ob]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Ju=m((RB,Fb)=>{"use strict";var oL=cr(),uL=Nb(),lL=Wr().CONSTRUCTOR;Fb.exports=lL||!uL(function(a){oL.all(a).then(void 0,function(){})})});var qb=m(()=>{"use strict";var cL=se(),dL=Ce(),pL=at(),hL=Yr(),fL=Ws(),mL=qs(),bL=Ju();cL({target:"Promise",stat:!0,forced:bL},{all:function(e){var t=this,r=hL.f(t),i=r.resolve,s=r.reject,n=fL(function(){var o=pL(t.resolve),u=[],l=0,c=1;mL(e,function(d){var p=l++,h=!1;c++,dL(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 Hb=m(()=>{"use strict";var gL=se(),vL=ze(),SL=Wr().CONSTRUCTOR,el=cr(),yL=ht(),TL=ee(),IL=jr(),Ub=el&&el.prototype;gL({target:"Promise",proto:!0,forced:SL,real:!0},{catch:function(a){return this.then(void 0,a)}});!vL&&TL(el)&&(Zu=yL("Promise").prototype.catch,Ub.catch!==Zu&&IL(Ub,"catch",Zu,{unsafe:!0}));var Zu});var jb=m(()=>{"use strict";var EL=se(),xL=Ce(),PL=at(),wL=Yr(),AL=Ws(),kL=qs(),LL=Ju();EL({target:"Promise",stat:!0,forced:LL},{race:function(e){var t=this,r=wL.f(t),i=r.reject,s=AL(function(){var n=PL(t.resolve);kL(e,function(o){xL(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Qb=m(()=>{"use strict";var RL=se(),$L=Yr(),ML=Wr().CONSTRUCTOR;RL({target:"Promise",stat:!0,forced:ML},{reject:function(e){var t=$L.f(this),r=t.reject;return r(e),t.promise}})});var tl=m((NB,Gb)=>{"use strict";var DL=st(),CL=Ve(),VL=Yr();Gb.exports=function(a,e){if(DL(a),CL(e)&&e.constructor===a)return e;var t=VL.f(a),r=t.resolve;return r(e),t.promise}});var zb=m(()=>{"use strict";var OL=se(),BL=ht(),Wb=ze(),_L=cr(),Yb=Wr().CONSTRUCTOR,NL=tl(),FL=BL("Promise"),qL=Wb&&!Yb;OL({target:"Promise",stat:!0,forced:Wb||Yb},{resolve:function(e){return NL(qL&&this===FL?_L:this,e)}})});var Kb=m(()=>{"use strict";Cb();qb();Hb();jb();Qb();zb()});var eg=m(()=>{"use strict";var UL=se(),HL=ze(),en=cr(),jL=de(),Jb=ht(),Zb=ee(),QL=xu(),Xb=tl(),GL=jr(),il=en&&en.prototype,WL=!!en&&jL(function(){il.finally.call({then:function(){}},function(){})});UL({target:"Promise",proto:!0,real:!0,forced:WL},{finally:function(a){var e=QL(this,Jb("Promise")),t=Zb(a);return this.then(t?function(r){return Xb(e,a()).then(function(){return r})}:a,t?function(r){return Xb(e,a()).then(function(){throw r})}:a)}});!HL&&Zb(en)&&(rl=Jb("Promise").prototype.finally,il.finally!==rl&&GL(il,"finally",rl,{unsafe:!0}));var rl});var rg=m((GB,tg)=>{"use strict";cm();Kb();eg();var YL=Ct();tg.exports=YL("Promise","finally")});var ag=m((WB,ig)=>{"use strict";var zL=rg();ig.exports=zL});var tn=m((YB,sg)=>{"use strict";var KL=ag();sg.exports=KL});var vg=m(()=>{"use strict";var cR=se(),dR=Ko().values;cR({target:"Object",stat:!0},{values:function(e){return dR(e)}})});var yg=m((M_,Sg)=>{"use strict";vg();var pR=Vr();Sg.exports=pR.Object.values});var Ig=m((D_,Tg)=>{"use strict";var hR=yg();Tg.exports=hR});var ei=m((C_,Eg)=>{"use strict";var fR=Ig();Eg.exports=fR});var Og=m(()=>{"use strict";var RR=se(),$R=Or(),MR=Ur(),DR=$i(),CR=Mi();RR({target:"Array",proto:!0},{at:function(e){var t=$R(this),r=MR(t),i=DR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});CR("at")});var _g=m((uN,Bg)=>{"use strict";Og();var VR=Ct();Bg.exports=VR("Array","at")});var Fg=m((lN,Ng)=>{"use strict";var OR=_g();Ng.exports=OR});var Ft=m((cN,qg)=>{"use strict";var BR=Fg();qg.exports=BR});var wl=m((KF,Iv)=>{"use strict";var y$=ir();Iv.exports=Array.isArray||function(e){return y$(e)==="Array"}});var xv=m((XF,Ev)=>{"use strict";var T$=TypeError,I$=9007199254740991;Ev.exports=function(a){if(a>I$)throw T$("Maximum allowed index exceeded");return a}});var Av=m((JF,wv)=>{"use strict";var E$=wl(),x$=Ur(),P$=xv(),w$=_r(),Pv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?w$(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&E$(d)?(p=x$(d),u=Pv(a,e,d,p,u,s-1)-1):(P$(u+1),a[u]=d),u++),l++;return u};wv.exports=Pv});var $v=m((ZF,Rv)=>{"use strict";var kv=wl(),A$=Eu(),k$=Ve(),L$=pe(),R$=L$("species"),Lv=Array;Rv.exports=function(a){var e;return kv(a)&&(e=a.constructor,A$(e)&&(e===Lv||kv(e.prototype))?e=void 0:k$(e)&&(e=e[R$],e===null&&(e=void 0))),e===void 0?Lv:e}});var Dv=m((eq,Mv)=>{"use strict";var $$=$v();Mv.exports=function(a,e){return new($$(a))(e===0?0:e)}});var Cv=m(()=>{"use strict";var M$=se(),D$=Av(),C$=at(),V$=Or(),O$=Ur(),B$=Dv();M$({target:"Array",proto:!0},{flatMap:function(e){var t=V$(this),r=O$(t),i;return C$(e),i=B$(t,0),i.length=D$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Vv=m(()=>{"use strict";var _$=Mi();_$("flatMap")});var Bv=m((sq,Ov)=>{"use strict";Cv();Vv();var N$=Ct();Ov.exports=N$("Array","flatMap")});var Nv=m((nq,_v)=>{"use strict";var F$=Bv();_v.exports=F$});var Al=m((oq,Fv)=>{"use strict";var q$=Nv();Fv.exports=q$});var na=m((vq,nS)=>{"use strict";var z$=Ci(),K$=String;nS.exports=function(a){if(z$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return K$(a)}});var Ll=m((Sq,oS)=>{"use strict";oS.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 cS=m((yq,lS)=>{"use strict";var X$=ne(),J$=Dt(),Z$=na(),$l=Ll(),uS=X$("".replace),eM=RegExp("^["+$l+"]+"),tM=RegExp("(^|[^"+$l+"])["+$l+"]+$"),Rl=function(a){return function(e){var t=Z$(J$(e));return a&1&&(t=uS(t,eM,"")),a&2&&(t=uS(t,tM,"$1")),t}};lS.exports={start:Rl(1),end:Rl(2),trim:Rl(3)}});var fS=m((Tq,hS)=>{"use strict";var rM=iu().PROPER,iM=de(),dS=Ll(),pS="\u200B\x85\u180E";hS.exports=function(a){return iM(function(){return!!dS[a]()||pS[a]()!==pS||rM&&dS[a].name!==a})}});var Ml=m((Iq,mS)=>{"use strict";var aM=cS().start,sM=fS();mS.exports=sM("trimStart")?function(){return aM(this)}:"".trimStart});var gS=m(()=>{"use strict";var nM=se(),bS=Ml();nM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==bS},{trimLeft:bS})});var SS=m(()=>{"use strict";gS();var oM=se(),vS=Ml();oM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==vS},{trimStart:vS})});var TS=m((Aq,yS)=>{"use strict";SS();var uM=Ct();yS.exports=uM("String","trimLeft")});var ES=m((kq,IS)=>{"use strict";var lM=TS();IS.exports=lM});var PS=m((Lq,xS)=>{"use strict";var cM=ES();xS.exports=cM});var qS=m(()=>{"use strict"});var US=m(()=>{"use strict"});var jS=m((dH,HS)=>{"use strict";var DM=Ve(),CM=ir(),VM=pe(),OM=VM("match");HS.exports=function(a){var e;return DM(a)&&((e=a[OM])!==void 0?!!e:CM(a)==="RegExp")}});var GS=m((pH,QS)=>{"use strict";var BM=st();QS.exports=function(){var a=BM(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 zS=m((hH,YS)=>{"use strict";var _M=Ce(),NM=Ke(),FM=Pi(),qM=GS(),WS=RegExp.prototype;YS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in WS)&&!NM(a,"flags")&&FM(WS,a)?_M(qM,a):e}});var XS=m((fH,KS)=>{"use strict";var ql=ne(),UM=Or(),HM=Math.floor,Nl=ql("".charAt),jM=ql("".replace),Fl=ql("".slice),QM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,GM=/\$([$&'`]|\d{1,2})/g;KS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=GM;return i!==void 0&&(i=UM(i),u=QM),jM(s,u,function(l,c){var d;switch(Nl(c,0)){case"$":return"$";case"&":return a;case"`":return Fl(e,0,t);case"'":return Fl(e,n);case"<":d=i[Fl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=HM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Nl(c,1):r[h-1]+Nl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var ey=m(()=>{"use strict";var WM=se(),YM=Ce(),Hl=ne(),JS=Dt(),zM=ee(),KM=Cr(),XM=jS(),oi=na(),JM=Ai(),ZM=zS(),eD=XS(),tD=pe(),rD=ze(),iD=tD("replace"),aD=TypeError,Ul=Hl("".indexOf),sD=Hl("".replace),ZS=Hl("".slice),nD=Math.max;WM({target:"String",proto:!0},{replaceAll:function(e,t){var r=JS(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!KM(e)){if(i=XM(e),i&&(s=oi(JS(ZM(e))),!~Ul(s,"g")))throw new aD("`.replaceAll` does not allow non-global regexes");if(n=JM(e,iD),n)return YM(n,e,r,t);if(rD&&i)return sD(oi(r),e,t)}for(o=oi(r),u=oi(e),l=zM(t),l||(t=oi(t)),c=u.length,d=nD(1,c),p=Ul(o,u);p!==-1;)h=l?oi(t(u,p,o)):eD(u,o,p,[],void 0,t),b+=ZS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Ul(o,u,p+d);return f<o.length&&(b+=ZS(o,f)),b}})});var ry=m((gH,ty)=>{"use strict";qS();US();ey();var oD=Ct();ty.exports=oD("String","replaceAll")});var ay=m((vH,iy)=>{"use strict";var uD=ry();iy.exports=uD});var ny=m((SH,sy)=>{"use strict";var lD=ay();sy.exports=lD});var uy=m((yH,oy)=>{"use strict";var cD=$i(),dD=na(),pD=Dt(),hD=RangeError;oy.exports=function(e){var t=dD(pD(this)),r="",i=cD(e);if(i<0||i===1/0)throw new hD("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var hy=m((TH,py)=>{"use strict";var dy=ne(),fD=Uo(),ly=na(),mD=uy(),bD=Dt(),gD=dy(mD),vD=dy("".slice),SD=Math.ceil,cy=function(a){return function(e,t,r){var i=ly(bD(e)),s=fD(t),n=i.length,o=r===void 0?" ":ly(r),u,l;return s<=n||o===""?i:(u=s-n,l=gD(o,SD(u/o.length)),l.length>u&&(l=vD(l,0,u)),a?i+l:l+i)}};py.exports={start:cy(!1),end:cy(!0)}});var my=m((IH,fy)=>{"use strict";var yD=sr();fy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(yD)});var by=m(()=>{"use strict";var TD=se(),ID=hy().start,ED=my();TD({target:"String",proto:!0,forced:ED},{padStart:function(e){return ID(this,e,arguments.length>1?arguments[1]:void 0)}})});var vy=m((PH,gy)=>{"use strict";by();var xD=Ct();gy.exports=xD("String","padStart")});var yy=m((wH,Sy)=>{"use strict";var PD=vy();Sy.exports=PD});var Iy=m((AH,Ty)=>{"use strict";var wD=yy();Ty.exports=wD});var hd="2.0.128-dev.1d1cd071.0";var Ee=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Ee||{}),Mt=(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))(Mt||{});var ys=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ys||{}),co=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(co||{});var po=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(po||{}),Ts=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(Ts||{});var eI=O(Xe(),1);import{assertNever as dh,assertNonNullable as Bx,isNonNullable as ws,ValueSubject as jo,Subject as _x,Subscription as Nx,merge as Fx,observableFrom as qx,fromEvent as oh,map as uh,tap as lh,filterChanged as Ux,isNullable as Qo,ErrorCategory as ch}from"@vkontakte/videoplayer-shared/es2015";var nh=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 As=class{constructor(e){this.connection$=new jo(void 0);this.castState$=new jo("NOT_AVAILABLE");this.errorEvent$=new _x;this.realCastState$=new jo("NOT_AVAILABLE");this.subscription=new Nx;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=ws((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||nh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ch.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(){ws(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Qo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Qo(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(oh(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 dh(i.sessionState)}})).add(Fx(oh(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(lh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),uh(i=>i.castState)),qx([r.getCastState()])).pipe(Ux(),uh(Hx),lh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=ws(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Bx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Qo(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"?ws(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:ch.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Hx=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 dh(a)}};var Ec=O(Xe(),1),VT=O(Hr(),1),OT=O(vu(),1);var mg=O(tn(),1);import{assertNever as ng}from"@vkontakte/videoplayer-shared/es2015";var he=(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:ng(t)}return a},rn=(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:ng(e)}};var w=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as XL,Subject as an,merge as og}from"@vkontakte/videoplayer-shared/es2015";var V=class{constructor(e){this.transitionStarted$=new an;this.transitionEnded$=new an;this.transitionUpdated$=new an;this.forceChanged$=new an;this.stateChangeStarted$=og(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=og(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||XL(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 JL}from"@vkontakte/videoplayer-shared/es2015";var ug=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 JL(a)}};import{assertNever as Zr,assertNonNullable as pr,debounce as lg,ErrorCategory as cg,fromEvent as hr,isNonNullable as dg,map as pg,merge as hg,observableFrom as ZL,Subject as eR,Subscription as al,timeout as tR,getHighestQuality as rR}from"@vkontakte/videoplayer-shared/es2015";var iR=5,aR=5,sR=500,fg=7e3,Qi=class{constructor(e){this.subscription=new al;this.loadMediaTimeoutSubscription=new al;this.videoState=new V("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:Zr(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:Zr(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:Zr(e)}break}default:Zr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ug(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 al;this.subscription.add(e),this.subscription.add(hg(this.videoState.stateChangeStarted$.pipe(pg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(pg(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 eR;e.add(i.pipe(lg(sR)).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)>iR)&&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<aR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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:Zr(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=hg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ZL(["init"])).pipe(lg(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"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(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"),w(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"),w(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"&&w(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=rR(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=he(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:cg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Zr(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 dg(o)&&(n.metadata.title=o),dg(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(tR(fg).subscribe(()=>s(`timeout(${fg})`)))});(0,mg.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:cg.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var xl=O(Xe(),1);import{clearVideoElement as gg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as nR}from"@vkontakte/videoplayer-shared/es2015";var bg=a=>{try{a.pause(),a.playbackRate=0,nR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as oR,Subscription as uR}from"@vkontakte/videoplayer-shared/es2015";var sl=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)}},nl=window.WeakMap?new WeakMap:new sl,ol=window.WeakMap?new WeakMap:new Map,lR=(a,e=20)=>{let t=0;return oR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},xe=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?gg(r):(r=document.createElement("video"),a.appendChild(r)),nl.set(r,i);let s=new uR;return s.add(lR(r,e)),ol.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},Pe=a=>{let e=ol.get(a);e==null||e.unsubscribe(),ol.delete(a);let t=nl.get(a);nl.delete(a),t?gg(a):bg(a)};var ll=O(ei(),1);import{assertNonNullable as Gi,isNonNullable as ot,isNullable as gR,fromEvent as ti,merge as xg,observableFrom as Pg,filterChanged as wg,map as Wi,Subject as Ag,Subscription as vR,ValueSubject as SR,ErrorCategory as yR}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as ul,isNullable as mR,Subscription as bR}from"@vkontakte/videoplayer-shared/es2015";var sn=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=mR(i),l=new bR;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},nt=(a,e,t)=>sn(e,()=>a.loop,r=>{ul(r)&&(a.loop=r)},{onError:t}),we=(a,e,t,r)=>sn(e,()=>({muted:a.muted,volume:a.volume}),i=>{ul(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)=>sn(e,()=>a.playbackRate,i=>{ul(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ot=sn;var TR=a=>["__",a.language,a.label].join("|"),IR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},cl=class a{constructor(e){this.available$=new Ag;this.current$=new SR(void 0);this.error$=new Ag;this.subscription=new vR;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:yR.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(Ot(t.internalTextTracks,()=>(0,ll.default)(this.internalTracks),s=>{ot(s)&&this.setInternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Wi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ot(t.externalTextTracks,()=>(0,ll.default)(this.externalTracks),s=>{ot(s)&&this.setExternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Wi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ot(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(Ot(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(ti(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(xg(ti(e,"addtrack"),ti(e,"removetrack"),Pg(["init"])).pipe(Wi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),wg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(xg(ti(e,"change"),Pg(["init"])).pipe(Wi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Wi(r=>r&&this.htmlTextTrackToITextTrack(r).id),wg()).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(ti(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(ti(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;ot(t.align)&&(i.align=t.align),ot(t.position)&&(i.position=t.position),ot(t.size)&&(i.size=t.size),ot(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:TR(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))(gR(e)||!IR(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=cl;var bt=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 kg=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},dl=a=>{let e=kg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Lg=a=>{let e=kg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ue,map as Bt,merge as $g,filterChanged as xR,isNonNullable as Mg,Subject as PR,filter as Dg,mapTo as Cg,combine as wR,once as AR,ErrorCategory as kR,ValueSubject as Vg,clientChecker as LR}from"@vkontakte/videoplayer-shared/es2015";var ER=3,Rg=(a,e,t=ER)=>{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 Ae=a=>{let e=T=>Ue(a,T).pipe(Cg(void 0)),r=$g(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Ue(a,T))).pipe(Bt(T=>T.type==="ended"?a.readyState<2:a.readyState<3),xR()),i=$g(Ue(a,"progress"),Ue(a,"timeupdate")).pipe(Bt(()=>Rg(a.buffered,a.currentTime))),s=LR.isSafari?wR({play:e("play").pipe(AR()),playing:e("playing")}).pipe(Cg(void 0)):e("playing"),n=Ue(a,"volumechange").pipe(Bt(()=>({muted:a.muted,volume:a.volume}))),o=Ue(a,"ratechange").pipe(Bt(()=>a.playbackRate)),u=Ue(a,"error").pipe(Dg(()=>!!(a.error||a.played.length)),Bt(()=>{var I;let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:kR.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=Ue(a,"timeupdate").pipe(Bt(()=>a.currentTime)),c=new PR,d=.3,p;l.subscribe(T=>{a.loop&&Mg(p)&&Mg(T)&&p>=a.duration-d&&T<=d&&c.next(p),p=T});let h=e("pause").pipe(Dg(()=>!a.error&&p!==a.duration)),f=Ue(a,"enterpictureinpicture"),b=Ue(a,"leavepictureinpicture"),g=new Vg(Lg(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Vg(dl(a));return Ue(a,"fullscreenchange").pipe(Bt(()=>dl(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(Bt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as _t}from"@vkontakte/videoplayer-shared/es2015";var Nt=a=>{switch(a){case"mobile":return _t.Q_144P;case"lowest":return _t.Q_240P;case"low":return _t.Q_360P;case"sd":case"medium":return _t.Q_480P;case"hd":case"high":return _t.Q_720P;case"fullhd":case"full":return _t.Q_1080P;case"quadhd":case"quad":return _t.Q_1440P;case"ultrahd":case"ultra":return _t.Q_2160P}};var qt=O(Ft(),1),Xg=O(Xe(),1),un=O(Hr(),1);import{isNonNullable as Be,isNullable as Wg,now as Jg,isHigher as Yg,isHigherOrEqual as ml,isInvariantQuality as zg,isLowerOrEqual as bl,videoSizeToQuality as FR,assertNotEmptyArray as Zg,assertNonNullable as qR}from"@vkontakte/videoplayer-shared/es2015";var pl=!1,gt={},Ug=a=>{pl=a},Hg=()=>{gt={}},jg=a=>{a(gt)},Yi=(a,e)=>{var t;pl&&(gt.meta=(t=gt.meta)!=null?t:{},gt.meta[a]=e)},Se=class{constructor(e){this.name=e}next(e){var r,i;if(!pl)return;gt.series=(r=gt.series)!=null?r:{};let t=(i=gt.series[this.name])!=null?i:[];t.push([Date.now(),e]),gt.series[this.name]=t}};import{isHigher as _R,isHigherOrEqual as bN,isLower as Qg,isLowerOrEqual as gN,isNonNullable as nn,isNullable as NR,videoHeightToQuality as on}from"@vkontakte/videoplayer-shared/es2015";function hl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function fl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&hl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function zi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return NR(a)||nn(a.min)&&nn(a.max)&&Qg(a.max,a.min)||nn(a.min)&&e&&_R(a.min,e)||nn(a.max)&&t&&Qg(a.max,t)}function Gg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return zi({limits:{max:a!=null&&a.max?on(a.max):void 0,min:a!=null&&a.min?on(a.min):void 0},highestAvailableQuality:e?on(e):void 0,lowestAvailableQuality:t?on(t):void 0})}var UR=new Se("best_bitrate"),ev=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var gl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ki=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Jg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},tv='Assertion "ABR Tracks is empty array" failed',ln=(a,e,t,r)=>{var u;let i=[...e].sort(gl(1)),s=[...t].sort(gl(1)),n=s.filter(l=>Be(l.bitrate)&&Be(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,qt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,qt.default)(s,-1);return o&&(0,Xg.default)(n,o)?o:n.length?(0,qt.default)(n,-1):(0,qt.default)(s,0)},Kg=a=>"quality"in a,rv=(a,e,t,r)=>{var n;let i=Be((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&Be(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Jg()-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=Kg(o)?"video":"audio",l=Kg(o)?o.quality:o.bitrate;return e({message:`
6
+ var GT=Object.create;var to=Object.defineProperty,WT=Object.defineProperties,YT=Object.getOwnPropertyDescriptor,zT=Object.getOwnPropertyDescriptors,KT=Object.getOwnPropertyNames,ps=Object.getOwnPropertySymbols,XT=Object.getPrototypeOf,ro=Object.prototype.hasOwnProperty,id=Object.prototype.propertyIsEnumerable;var JT=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,rd=(a,e,t)=>e in a?to(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,P=(a,e)=>{for(var t in e||(e={}))ro.call(e,t)&&rd(a,t,e[t]);if(ps)for(var t of ps(e))id.call(e,t)&&rd(a,t,e[t]);return a},$=(a,e)=>WT(a,zT(e));var ad=(a,e)=>{var t={};for(var r in a)ro.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&ps)for(var r of ps(a))e.indexOf(r)<0&&id.call(a,r)&&(t[r]=a[r]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var ZT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of KT(e))!ro.call(a,i)&&i!==t&&to(a,i,{get:()=>e[i],enumerable:!(r=YT(e,i))||r.enumerable});return a};var _=(a,e,t)=>(t=a!=null?GT(XT(a)):{},ZT(e||!a||!a.__esModule?to(t,"default",{value:a,enumerable:!0}):t,a));var x=(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())}),hs=function(a,e){this[0]=a,this[1]=e},oe=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof hs,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[JT("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var se=f((so,nd)=>{"use strict";var gi=function(a){return a&&a.Math===Math&&a};nd.exports=gi(typeof globalThis=="object"&&globalThis)||gi(typeof window=="object"&&window)||gi(typeof self=="object"&&self)||gi(typeof global=="object"&&global)||gi(typeof so=="object"&&so)||function(){return this}()||Function("return this")()});var me=f((w0,od)=>{"use strict";od.exports=function(a){try{return!!a()}catch(e){return!0}}});var vi=f((A0,ud)=>{"use strict";var eI=me();ud.exports=!eI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var no=f((k0,pd)=>{"use strict";var tI=vi(),dd=Function.prototype,ld=dd.apply,cd=dd.call;pd.exports=typeof Reflect=="object"&&Reflect.apply||(tI?cd.bind(ld):function(){return cd.apply(ld,arguments)})});var le=f((L0,fd)=>{"use strict";var hd=vi(),md=Function.prototype,oo=md.call,rI=hd&&md.bind.bind(oo,oo);fd.exports=hd?rI:function(a){return function(){return oo.apply(a,arguments)}}});var tr=f((R0,gd)=>{"use strict";var bd=le(),iI=bd({}.toString),aI=bd("".slice);gd.exports=function(a){return aI(iI(a),8,-1)}});var uo=f(($0,vd)=>{"use strict";var sI=tr(),nI=le();vd.exports=function(a){if(sI(a)==="Function")return nI(a)}});var ie=f((M0,Sd)=>{"use strict";var lo=typeof document=="object"&&document.all;Sd.exports=typeof lo=="undefined"&&lo!==void 0?function(a){return typeof a=="function"||a===lo}:function(a){return typeof a=="function"}});var Ce=f((C0,yd)=>{"use strict";var oI=me();yd.exports=!oI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var De=f((D0,Td)=>{"use strict";var uI=vi(),bs=Function.prototype.call;Td.exports=uI?bs.bind(bs):function(){return bs.apply(bs,arguments)}});var co=f(xd=>{"use strict";var Id={}.propertyIsEnumerable,Ed=Object.getOwnPropertyDescriptor,lI=Ed&&!Id.call({1:2},1);xd.f=lI?function(e){var t=Ed(this,e);return!!t&&t.enumerable}:Id});var Si=f((_0,Pd)=>{"use strict";Pd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ad=f((O0,wd)=>{"use strict";var cI=le(),dI=me(),pI=tr(),po=Object,hI=cI("".split);wd.exports=dI(function(){return!po("z").propertyIsEnumerable(0)})?function(a){return pI(a)==="String"?hI(a,""):po(a)}:po});var $r=f((B0,kd)=>{"use strict";kd.exports=function(a){return a==null}});var $t=f((N0,Ld)=>{"use strict";var mI=$r(),fI=TypeError;Ld.exports=function(a){if(mI(a))throw new fI("Can't call method on "+a);return a}});var rr=f((F0,Rd)=>{"use strict";var bI=Ad(),gI=$t();Rd.exports=function(a){return bI(gI(a))}});var Ve=f((q0,$d)=>{"use strict";var vI=ie();$d.exports=function(a){return typeof a=="object"?a!==null:vI(a)}});var Mr=f((U0,Md)=>{"use strict";Md.exports={}});var ht=f((H0,Dd)=>{"use strict";var ho=Mr(),mo=se(),SI=ie(),Cd=function(a){return SI(a)?a:void 0};Dd.exports=function(a,e){return arguments.length<2?Cd(ho[a])||Cd(mo[a]):ho[a]&&ho[a][e]||mo[a]&&mo[a][e]}});var yi=f((j0,Vd)=>{"use strict";var yI=le();Vd.exports=yI({}.isPrototypeOf)});var ir=f((Q0,Bd)=>{"use strict";var TI=se(),_d=TI.navigator,Od=_d&&_d.userAgent;Bd.exports=Od?String(Od):""});var bo=f((G0,jd)=>{"use strict";var Hd=se(),fo=ir(),Nd=Hd.process,Fd=Hd.Deno,qd=Nd&&Nd.versions||Fd&&Fd.version,Ud=qd&&qd.v8,Ye,gs;Ud&&(Ye=Ud.split("."),gs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!gs&&fo&&(Ye=fo.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=fo.match(/Chrome\/(\d+)/),Ye&&(gs=+Ye[1])));jd.exports=gs});var go=f((W0,Gd)=>{"use strict";var Qd=bo(),II=me(),EI=se(),xI=EI.String;Gd.exports=!!Object.getOwnPropertySymbols&&!II(function(){var a=Symbol("symbol detection");return!xI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Qd&&Qd<41})});var vo=f((Y0,Wd)=>{"use strict";var PI=go();Wd.exports=PI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var So=f((z0,Yd)=>{"use strict";var wI=ht(),AI=ie(),kI=yi(),LI=vo(),RI=Object;Yd.exports=LI?function(a){return typeof a=="symbol"}:function(a){var e=wI("Symbol");return AI(e)&&kI(e.prototype,RI(a))}});var Ti=f((K0,zd)=>{"use strict";var $I=String;zd.exports=function(a){try{return $I(a)}catch(e){return"Object"}}});var at=f((X0,Kd)=>{"use strict";var MI=ie(),CI=Ti(),DI=TypeError;Kd.exports=function(a){if(MI(a))return a;throw new DI(CI(a)+" is not a function")}});var Ii=f((J0,Xd)=>{"use strict";var VI=at(),_I=$r();Xd.exports=function(a,e){var t=a[e];return _I(t)?void 0:VI(t)}});var Zd=f((Z0,Jd)=>{"use strict";var yo=De(),To=ie(),Io=Ve(),OI=TypeError;Jd.exports=function(a,e){var t,r;if(e==="string"&&To(t=a.toString)&&!Io(r=yo(t,a))||To(t=a.valueOf)&&!Io(r=yo(t,a))||e!=="string"&&To(t=a.toString)&&!Io(r=yo(t,a)))return r;throw new OI("Can't convert object to primitive value")}});var ze=f((eV,ep)=>{"use strict";ep.exports=!0});var ip=f((tV,rp)=>{"use strict";var tp=se(),BI=Object.defineProperty;rp.exports=function(a,e){try{BI(tp,a,{value:e,configurable:!0,writable:!0})}catch(t){tp[a]=e}return e}});var Ei=f((rV,np)=>{"use strict";var NI=ze(),FI=se(),qI=ip(),ap="__core-js_shared__",sp=np.exports=FI[ap]||qI(ap,{});(sp.versions||(sp.versions=[])).push({version:"3.38.0",mode:NI?"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 Eo=f((iV,up)=>{"use strict";var op=Ei();up.exports=function(a,e){return op[a]||(op[a]=e||{})}});var Cr=f((aV,lp)=>{"use strict";var UI=$t(),HI=Object;lp.exports=function(a){return HI(UI(a))}});var Ke=f((sV,cp)=>{"use strict";var jI=le(),QI=Cr(),GI=jI({}.hasOwnProperty);cp.exports=Object.hasOwn||function(e,t){return GI(QI(e),t)}});var xo=f((nV,dp)=>{"use strict";var WI=le(),YI=0,zI=Math.random(),KI=WI(1 .toString);dp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+KI(++YI+zI,36)}});var fe=f((oV,hp)=>{"use strict";var XI=se(),JI=Eo(),pp=Ke(),ZI=xo(),eE=go(),tE=vo(),Dr=XI.Symbol,Po=JI("wks"),rE=tE?Dr.for||Dr:Dr&&Dr.withoutSetter||ZI;hp.exports=function(a){return pp(Po,a)||(Po[a]=eE&&pp(Dr,a)?Dr[a]:rE("Symbol."+a)),Po[a]}});var gp=f((uV,bp)=>{"use strict";var iE=De(),mp=Ve(),fp=So(),aE=Ii(),sE=Zd(),nE=fe(),oE=TypeError,uE=nE("toPrimitive");bp.exports=function(a,e){if(!mp(a)||fp(a))return a;var t=aE(a,uE),r;if(t){if(e===void 0&&(e="default"),r=iE(t,a,e),!mp(r)||fp(r))return r;throw new oE("Can't convert object to primitive value")}return e===void 0&&(e="number"),sE(a,e)}});var wo=f((lV,vp)=>{"use strict";var lE=gp(),cE=So();vp.exports=function(a){var e=lE(a,"string");return cE(e)?e:e+""}});var vs=f((cV,yp)=>{"use strict";var dE=se(),Sp=Ve(),Ao=dE.document,pE=Sp(Ao)&&Sp(Ao.createElement);yp.exports=function(a){return pE?Ao.createElement(a):{}}});var ko=f((dV,Tp)=>{"use strict";var hE=Ce(),mE=me(),fE=vs();Tp.exports=!hE&&!mE(function(){return Object.defineProperty(fE("div"),"a",{get:function(){return 7}}).a!==7})});var xp=f(Ep=>{"use strict";var bE=Ce(),gE=De(),vE=co(),SE=Si(),yE=rr(),TE=wo(),IE=Ke(),EE=ko(),Ip=Object.getOwnPropertyDescriptor;Ep.f=bE?Ip:function(e,t){if(e=yE(e),t=TE(t),EE)try{return Ip(e,t)}catch(r){}if(IE(e,t))return SE(!gE(vE.f,e,t),e[t])}});var Lo=f((hV,Pp)=>{"use strict";var xE=me(),PE=ie(),wE=/#|\.prototype\./,xi=function(a,e){var t=kE[AE(a)];return t===RE?!0:t===LE?!1:PE(e)?xE(e):!!e},AE=xi.normalize=function(a){return String(a).replace(wE,".").toLowerCase()},kE=xi.data={},LE=xi.NATIVE="N",RE=xi.POLYFILL="P";Pp.exports=xi});var Vr=f((mV,Ap)=>{"use strict";var wp=uo(),$E=at(),ME=vi(),CE=wp(wp.bind);Ap.exports=function(a,e){return $E(a),e===void 0?a:ME?CE(a,e):function(){return a.apply(e,arguments)}}});var Ro=f((fV,kp)=>{"use strict";var DE=Ce(),VE=me();kp.exports=DE&&VE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=f((bV,Lp)=>{"use strict";var _E=Ve(),OE=String,BE=TypeError;Lp.exports=function(a){if(_E(a))return a;throw new BE(OE(a)+" is not an object")}});var ar=f($p=>{"use strict";var NE=Ce(),FE=ko(),qE=Ro(),Ss=st(),Rp=wo(),UE=TypeError,$o=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,Mo="enumerable",Co="configurable",Do="writable";$p.f=NE?qE?function(e,t,r){if(Ss(e),t=Rp(t),Ss(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Do in r&&!r[Do]){var i=HE(e,t);i&&i[Do]&&(e[t]=r.value,r={configurable:Co in r?r[Co]:i[Co],enumerable:Mo in r?r[Mo]:i[Mo],writable:!1})}return $o(e,t,r)}:$o:function(e,t,r){if(Ss(e),t=Rp(t),Ss(r),FE)try{return $o(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new UE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=f((vV,Mp)=>{"use strict";var jE=Ce(),QE=ar(),GE=Si();Mp.exports=jE?function(a,e,t){return QE.f(a,e,GE(1,t))}:function(a,e,t){return a[e]=t,a}});var ue=f((SV,Dp)=>{"use strict";var Pi=se(),WE=no(),YE=uo(),zE=ie(),KE=xp().f,XE=Lo(),Or=Mr(),JE=Vr(),Br=_r(),Cp=Ke();Ei();var ZE=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 WE(a,this,arguments)};return e.prototype=a.prototype,e};Dp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Pi:i?Pi[t]:Pi[t]&&Pi[t].prototype,o=r?Or:Or[t]||Br(Or,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=XE(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Cp(n,p),m=o[p],c&&(a.dontCallGetSet?(v=KE(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?g=JE(h,Pi):a.wrap&&c?g=ZE(h):s&&zE(h)?g=YE(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Br(g,"sham",!0),Br(o,p,g),s&&(d=t+"Prototype",Cp(Or,d)||Br(Or,d,{}),Br(Or[d],p,h),a.real&&u&&(l||!u[p])&&Br(u,p,h)))}});var _p=f((yV,Vp)=>{"use strict";var ex=Math.ceil,tx=Math.floor;Vp.exports=Math.trunc||function(e){var t=+e;return(t>0?tx:ex)(t)}});var wi=f((TV,Op)=>{"use strict";var rx=_p();Op.exports=function(a){var e=+a;return e!==e||e===0?0:rx(e)}});var Np=f((IV,Bp)=>{"use strict";var ix=wi(),ax=Math.max,sx=Math.min;Bp.exports=function(a,e){var t=ix(a);return t<0?ax(t+e,0):sx(t,e)}});var Vo=f((EV,Fp)=>{"use strict";var nx=wi(),ox=Math.min;Fp.exports=function(a){var e=nx(a);return e>0?ox(e,9007199254740991):0}});var Nr=f((xV,qp)=>{"use strict";var ux=Vo();qp.exports=function(a){return ux(a.length)}});var _o=f((PV,Hp)=>{"use strict";var lx=rr(),cx=Np(),dx=Nr(),Up=function(a){return function(e,t,r){var i=lx(e),s=dx(i);if(s===0)return!a&&-1;var n=cx(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}};Hp.exports={includes:Up(!0),indexOf:Up(!1)}});var Ai=f((wV,jp)=>{"use strict";jp.exports=function(){}});var Qp=f(()=>{"use strict";var px=ue(),hx=_o().includes,mx=me(),fx=Ai(),bx=mx(function(){return!Array(1).includes()});px({target:"Array",proto:!0,forced:bx},{includes:function(e){return hx(this,e,arguments.length>1?arguments[1]:void 0)}});fx("includes")});var Mt=f((LV,Gp)=>{"use strict";var gx=ht();Gp.exports=gx});var Yp=f((RV,Wp)=>{"use strict";Qp();var vx=Mt();Wp.exports=vx("Array","includes")});var Kp=f(($V,zp)=>{"use strict";var Sx=Yp();zp.exports=Sx});var Fe=f((MV,Xp)=>{"use strict";var yx=Kp();Xp.exports=yx});var Is=f((jV,sh)=>{"use strict";var kx=Eo(),Lx=xo(),ah=kx("keys");sh.exports=function(a){return ah[a]||(ah[a]=Lx(a))}});var oh=f((QV,nh)=>{"use strict";var Rx=me();nh.exports=!Rx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Es=f((GV,lh)=>{"use strict";var $x=Ke(),Mx=ie(),Cx=Cr(),Dx=Is(),Vx=oh(),uh=Dx("IE_PROTO"),No=Object,_x=No.prototype;lh.exports=Vx?No.getPrototypeOf:function(a){var e=Cx(a);if($x(e,uh))return e[uh];var t=e.constructor;return Mx(t)&&e instanceof t?t.prototype:e instanceof No?_x:null}});var xs=f((WV,ch)=>{"use strict";ch.exports={}});var hh=f((YV,ph)=>{"use strict";var Ox=le(),Fo=Ke(),Bx=rr(),Nx=_o().indexOf,Fx=xs(),dh=Ox([].push);ph.exports=function(a,e){var t=Bx(a),r=0,i=[],s;for(s in t)!Fo(Fx,s)&&Fo(t,s)&&dh(i,s);for(;e.length>r;)Fo(t,s=e[r++])&&(~Nx(i,s)||dh(i,s));return i}});var qo=f((zV,mh)=>{"use strict";mh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Uo=f((KV,fh)=>{"use strict";var qx=hh(),Ux=qo();fh.exports=Object.keys||function(e){return qx(e,Ux)}});var Ho=f((XV,yh)=>{"use strict";var gh=Ce(),Hx=me(),vh=le(),jx=Es(),Qx=Uo(),Gx=rr(),Wx=co().f,Sh=vh(Wx),Yx=vh([].push),zx=gh&&Hx(function(){var a=Object.create(null);return a[2]=2,!Sh(a,2)}),bh=function(a){return function(e){for(var t=Gx(e),r=Qx(t),i=zx&&jx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!gh||(i?u in t:Sh(t,u)))&&Yx(o,a?[u,t[u]]:t[u]);return o}};yh.exports={entries:bh(!0),values:bh(!1)}});var Th=f(()=>{"use strict";var Kx=ue(),Xx=Ho().entries;Kx({target:"Object",stat:!0},{entries:function(e){return Xx(e)}})});var Eh=f((e_,Ih)=>{"use strict";Th();var Jx=Mr();Ih.exports=Jx.Object.entries});var Ph=f((t_,xh)=>{"use strict";var Zx=Eh();xh.exports=Zx});var Fr=f((r_,wh)=>{"use strict";var eP=Ph();wh.exports=eP});var sr=f((i_,Ah)=>{"use strict";Ah.exports={}});var Rh=f((a_,Lh)=>{"use strict";var tP=se(),rP=ie(),kh=tP.WeakMap;Lh.exports=rP(kh)&&/native code/.test(String(kh))});var Wo=f((s_,Ch)=>{"use strict";var iP=Rh(),Mh=se(),aP=Ve(),sP=_r(),jo=Ke(),Qo=Ei(),nP=Is(),oP=xs(),$h="Object already initialized",Go=Mh.TypeError,uP=Mh.WeakMap,Ps,ki,ws,lP=function(a){return ws(a)?ki(a):Ps(a,{})},cP=function(a){return function(e){var t;if(!aP(e)||(t=ki(e)).type!==a)throw new Go("Incompatible receiver, "+a+" required");return t}};iP||Qo.state?(Xe=Qo.state||(Qo.state=new uP),Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,Ps=function(a,e){if(Xe.has(a))throw new Go($h);return e.facade=a,Xe.set(a,e),e},ki=function(a){return Xe.get(a)||{}},ws=function(a){return Xe.has(a)}):(nr=nP("state"),oP[nr]=!0,Ps=function(a,e){if(jo(a,nr))throw new Go($h);return e.facade=a,sP(a,nr,e),e},ki=function(a){return jo(a,nr)?a[nr]:{}},ws=function(a){return jo(a,nr)});var Xe,nr;Ch.exports={set:Ps,get:ki,has:ws,enforce:lP,getterFor:cP}});var Ko=f((n_,Vh)=>{"use strict";var Yo=Ce(),dP=Ke(),Dh=Function.prototype,pP=Yo&&Object.getOwnPropertyDescriptor,zo=dP(Dh,"name"),hP=zo&&function(){}.name==="something",mP=zo&&(!Yo||Yo&&pP(Dh,"name").configurable);Vh.exports={EXISTS:zo,PROPER:hP,CONFIGURABLE:mP}});var Oh=f(_h=>{"use strict";var fP=Ce(),bP=Ro(),gP=ar(),vP=st(),SP=rr(),yP=Uo();_h.f=fP&&!bP?Object.defineProperties:function(e,t){vP(e);for(var r=SP(t),i=yP(t),s=i.length,n=0,o;s>n;)gP.f(e,o=i[n++],r[o]);return e}});var Xo=f((u_,Bh)=>{"use strict";var TP=ht();Bh.exports=TP("document","documentElement")});var tu=f((l_,Qh)=>{"use strict";var IP=st(),EP=Oh(),Nh=qo(),xP=xs(),PP=Xo(),wP=vs(),AP=Is(),Fh=">",qh="<",Zo="prototype",eu="script",Hh=AP("IE_PROTO"),Jo=function(){},jh=function(a){return qh+eu+Fh+a+qh+"/"+eu+Fh},Uh=function(a){a.write(jh("")),a.close();var e=a.parentWindow.Object;return a=null,e},kP=function(){var a=wP("iframe"),e="java"+eu+":",t;return a.style.display="none",PP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(jh("document.F=Object")),t.close(),t.F},As,ks=function(){try{As=new ActiveXObject("htmlfile")}catch(e){}ks=typeof document!="undefined"?document.domain&&As?Uh(As):kP():Uh(As);for(var a=Nh.length;a--;)delete ks[Zo][Nh[a]];return ks()};xP[Hh]=!0;Qh.exports=Object.create||function(e,t){var r;return e!==null?(Jo[Zo]=IP(e),r=new Jo,Jo[Zo]=null,r[Hh]=e):r=ks(),t===void 0?r:EP.f(r,t)}});var qr=f((c_,Gh)=>{"use strict";var LP=_r();Gh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:LP(a,e,t),a}});var su=f((d_,zh)=>{"use strict";var RP=me(),$P=ie(),MP=Ve(),CP=tu(),Wh=Es(),DP=qr(),VP=fe(),_P=ze(),au=VP("iterator"),Yh=!1,mt,ru,iu;[].keys&&(iu=[].keys(),"next"in iu?(ru=Wh(Wh(iu)),ru!==Object.prototype&&(mt=ru)):Yh=!0);var OP=!MP(mt)||RP(function(){var a={};return mt[au].call(a)!==a});OP?mt={}:_P&&(mt=CP(mt));$P(mt[au])||DP(mt,au,function(){return this});zh.exports={IteratorPrototype:mt,BUGGY_SAFARI_ITERATORS:Yh}});var Ls=f((p_,Xh)=>{"use strict";var BP=fe(),NP=BP("toStringTag"),Kh={};Kh[NP]="z";Xh.exports=String(Kh)==="[object z]"});var Li=f((h_,Jh)=>{"use strict";var FP=Ls(),qP=ie(),Rs=tr(),UP=fe(),HP=UP("toStringTag"),jP=Object,QP=Rs(function(){return arguments}())==="Arguments",GP=function(a,e){try{return a[e]}catch(t){}};Jh.exports=FP?Rs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=GP(e=jP(a),HP))=="string"?t:QP?Rs(e):(r=Rs(e))==="Object"&&qP(e.callee)?"Arguments":r}});var em=f((m_,Zh)=>{"use strict";var WP=Ls(),YP=Li();Zh.exports=WP?{}.toString:function(){return"[object "+YP(this)+"]"}});var Ri=f((f_,rm)=>{"use strict";var zP=Ls(),KP=ar().f,XP=_r(),JP=Ke(),ZP=em(),ew=fe(),tm=ew("toStringTag");rm.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(JP(i,tm)||KP(i,tm,{configurable:!0,value:e}),r&&!zP&&XP(i,"toString",ZP))}});var am=f((b_,im)=>{"use strict";var tw=su().IteratorPrototype,rw=tu(),iw=Si(),aw=Ri(),sw=sr(),nw=function(){return this};im.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=rw(tw,{next:iw(+!r,t)}),aw(a,i,!1,!0),sw[i]=nw,a}});var nm=f((g_,sm)=>{"use strict";var ow=le(),uw=at();sm.exports=function(a,e,t){try{return ow(uw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var um=f((v_,om)=>{"use strict";var lw=Ve();om.exports=function(a){return lw(a)||a===null}});var cm=f((S_,lm)=>{"use strict";var cw=um(),dw=String,pw=TypeError;lm.exports=function(a){if(cw(a))return a;throw new pw("Can't set "+dw(a)+" as a prototype")}});var nu=f((y_,dm)=>{"use strict";var hw=nm(),mw=Ve(),fw=$t(),bw=cm();dm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=hw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return fw(i),bw(s),mw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Im=f((T_,Tm)=>{"use strict";var gw=ue(),vw=De(),$s=ze(),Sm=Ko(),Sw=ie(),yw=am(),pm=Es(),hm=nu(),Tw=Ri(),Iw=_r(),ou=qr(),Ew=fe(),mm=sr(),ym=su(),xw=Sm.PROPER,Pw=Sm.CONFIGURABLE,fm=ym.IteratorPrototype,Ms=ym.BUGGY_SAFARI_ITERATORS,$i=Ew("iterator"),bm="keys",Mi="values",gm="entries",vm=function(){return this};Tm.exports=function(a,e,t,r,i,s,n){yw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ms&&v&&v in c)return c[v];switch(v){case bm:return function(){return new t(this,v)};case Mi:return function(){return new t(this,v)};case gm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[$i]||c["@@iterator"]||i&&c[i],p=!Ms&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=pm(h.call(new a)),m!==Object.prototype&&m.next&&(!$s&&pm(m)!==fm&&(hm?hm(m,fm):Sw(m[$i])||ou(m,$i,vm)),Tw(m,u,!0,!0),$s&&(mm[u]=vm))),xw&&i===Mi&&d&&d.name!==Mi&&(!$s&&Pw?Iw(c,"name",Mi):(l=!0,p=function(){return vw(d,this)})),i)if(b={values:o(Mi),keys:s?p:o(bm),entries:o(gm)},n)for(g in b)(Ms||l||!(g in c))&&ou(c,g,b[g]);else gw({target:e,proto:!0,forced:Ms||l},b);return(!$s||n)&&c[$i]!==p&&ou(c,$i,p,{name:i}),mm[e]=p,b}});var xm=f((I_,Em)=>{"use strict";Em.exports=function(a,e){return{value:a,done:e}}});var lu=f((E_,Lm)=>{"use strict";var ww=rr(),uu=Ai(),Pm=sr(),Am=Wo(),Aw=ar().f,kw=Im(),Cs=xm(),Lw=ze(),Rw=Ce(),km="Array Iterator",$w=Am.set,Mw=Am.getterFor(km);Lm.exports=kw(Array,"Array",function(a,e){$w(this,{type:km,target:ww(a),index:0,kind:e})},function(){var a=Mw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Cs(void 0,!0);switch(a.kind){case"keys":return Cs(t,!1);case"values":return Cs(e[t],!1)}return Cs([t,e[t]],!1)},"values");var wm=Pm.Arguments=Pm.Array;uu("keys");uu("values");uu("entries");if(!Lw&&Rw&&wm.name!=="values")try{Aw(wm,"name",{value:"values"})}catch(a){}});var $m=f((x_,Rm)=>{"use strict";var Cw=fe(),Dw=sr(),Vw=Cw("iterator"),_w=Array.prototype;Rm.exports=function(a){return a!==void 0&&(Dw.Array===a||_w[Vw]===a)}});var cu=f((P_,Cm)=>{"use strict";var Ow=Li(),Mm=Ii(),Bw=$r(),Nw=sr(),Fw=fe(),qw=Fw("iterator");Cm.exports=function(a){if(!Bw(a))return Mm(a,qw)||Mm(a,"@@iterator")||Nw[Ow(a)]}});var Vm=f((w_,Dm)=>{"use strict";var Uw=De(),Hw=at(),jw=st(),Qw=Ti(),Gw=cu(),Ww=TypeError;Dm.exports=function(a,e){var t=arguments.length<2?Gw(a):e;if(Hw(t))return jw(Uw(t,a));throw new Ww(Qw(a)+" is not iterable")}});var Bm=f((A_,Om)=>{"use strict";var Yw=De(),_m=st(),zw=Ii();Om.exports=function(a,e,t){var r,i;_m(a);try{if(r=zw(a,"return"),!r){if(e==="throw")throw t;return t}r=Yw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return _m(r),t}});var Vs=f((k_,Um)=>{"use strict";var Kw=Vr(),Xw=De(),Jw=st(),Zw=Ti(),eA=$m(),tA=Nr(),Nm=yi(),rA=Vm(),iA=cu(),Fm=Bm(),aA=TypeError,Ds=function(a,e){this.stopped=a,this.result=e},qm=Ds.prototype;Um.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=Kw(e,r),l,c,d,p,h,m,b,g=function(S){return l&&Fm(l,"normal",S),new Ds(!0,S)},v=function(S){return i?(Jw(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=iA(a),!c)throw new aA(Zw(a)+" is not iterable");if(eA(c)){for(d=0,p=tA(a);p>d;d++)if(h=v(a[d]),h&&Nm(qm,h))return h;return new Ds(!1)}l=rA(a,c)}for(m=s?a.next:l.next;!(b=Xw(m,l)).done;){try{h=v(b.value)}catch(S){Fm(l,"throw",S)}if(typeof h=="object"&&h&&Nm(qm,h))return h}return new Ds(!1)}});var jm=f((L_,Hm)=>{"use strict";var sA=Ce(),nA=ar(),oA=Si();Hm.exports=function(a,e,t){sA?nA.f(a,e,oA(0,t)):a[e]=t}});var Qm=f(()=>{"use strict";var uA=ue(),lA=Vs(),cA=jm();uA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return lA(e,function(r,i){cA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Wm=f((M_,Gm)=>{"use strict";lu();Qm();var dA=Mr();Gm.exports=dA.Object.fromEntries});var zm=f((C_,Ym)=>{"use strict";Ym.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 Xm=f(()=>{"use strict";lu();var pA=zm(),hA=se(),mA=Ri(),Km=sr();for(_s in pA)mA(hA[_s],_s),Km[_s]=Km.Array;var _s});var Zm=f((__,Jm)=>{"use strict";var fA=Wm();Xm();Jm.exports=fA});var du=f((O_,ef)=>{"use strict";var bA=Zm();ef.exports=bA});var tf=f(()=>{"use strict"});var pu=f((F_,rf)=>{"use strict";var Ci=se(),gA=ir(),vA=tr(),Os=function(a){return gA.slice(0,a.length)===a};rf.exports=function(){return Os("Bun/")?"BUN":Os("Cloudflare-Workers")?"CLOUDFLARE":Os("Deno/")?"DENO":Os("Node.js/")?"NODE":Ci.Bun&&typeof Bun.version=="string"?"BUN":Ci.Deno&&typeof Deno.version=="object"?"DENO":vA(Ci.process)==="process"?"NODE":Ci.window&&Ci.document?"BROWSER":"REST"}()});var Bs=f((q_,af)=>{"use strict";var SA=pu();af.exports=SA==="NODE"});var nf=f((U_,sf)=>{"use strict";var yA=ar();sf.exports=function(a,e,t){return yA.f(a,e,t)}});var lf=f((H_,uf)=>{"use strict";var TA=ht(),IA=nf(),EA=fe(),xA=Ce(),of=EA("species");uf.exports=function(a){var e=TA(a);xA&&e&&!e[of]&&IA(e,of,{configurable:!0,get:function(){return this}})}});var df=f((j_,cf)=>{"use strict";var PA=yi(),wA=TypeError;cf.exports=function(a,e){if(PA(e,a))return a;throw new wA("Incorrect invocation")}});var mu=f((Q_,pf)=>{"use strict";var AA=le(),kA=ie(),hu=Ei(),LA=AA(Function.toString);kA(hu.inspectSource)||(hu.inspectSource=function(a){return LA(a)});pf.exports=hu.inspectSource});var bu=f((G_,gf)=>{"use strict";var RA=le(),$A=me(),hf=ie(),MA=Li(),CA=ht(),DA=mu(),mf=function(){},ff=CA("Reflect","construct"),fu=/^\s*(?:class|function)\b/,VA=RA(fu.exec),_A=!fu.test(mf),Di=function(e){if(!hf(e))return!1;try{return ff(mf,[],e),!0}catch(t){return!1}},bf=function(e){if(!hf(e))return!1;switch(MA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return _A||!!VA(fu,DA(e))}catch(t){return!0}};bf.sham=!0;gf.exports=!ff||$A(function(){var a;return Di(Di.call)||!Di(Object)||!Di(function(){a=!0})||a})?bf:Di});var Sf=f((W_,vf)=>{"use strict";var OA=bu(),BA=Ti(),NA=TypeError;vf.exports=function(a){if(OA(a))return a;throw new NA(BA(a)+" is not a constructor")}});var gu=f((Y_,Tf)=>{"use strict";var yf=st(),FA=Sf(),qA=$r(),UA=fe(),HA=UA("species");Tf.exports=function(a,e){var t=yf(a).constructor,r;return t===void 0||qA(r=yf(t)[HA])?e:FA(r)}});var Ef=f((z_,If)=>{"use strict";var jA=le();If.exports=jA([].slice)});var Pf=f((K_,xf)=>{"use strict";var QA=TypeError;xf.exports=function(a,e){if(a<e)throw new QA("Not enough arguments");return a}});var vu=f((X_,wf)=>{"use strict";var GA=ir();wf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(GA)});var Au=f((J_,Vf)=>{"use strict";var _e=se(),WA=no(),YA=Vr(),Af=ie(),zA=Ke(),Df=me(),kf=Xo(),KA=Ef(),Lf=vs(),XA=Pf(),JA=vu(),ZA=Bs(),xu=_e.setImmediate,Pu=_e.clearImmediate,ek=_e.process,Su=_e.Dispatch,tk=_e.Function,Rf=_e.MessageChannel,rk=_e.String,yu=0,Vi={},$f="onreadystatechange",_i,or,Tu,Iu;Df(function(){_i=_e.location});var wu=function(a){if(zA(Vi,a)){var e=Vi[a];delete Vi[a],e()}},Eu=function(a){return function(){wu(a)}},Mf=function(a){wu(a.data)},Cf=function(a){_e.postMessage(rk(a),_i.protocol+"//"+_i.host)};(!xu||!Pu)&&(xu=function(e){XA(arguments.length,1);var t=Af(e)?e:tk(e),r=KA(arguments,1);return Vi[++yu]=function(){WA(t,void 0,r)},or(yu),yu},Pu=function(e){delete Vi[e]},ZA?or=function(a){ek.nextTick(Eu(a))}:Su&&Su.now?or=function(a){Su.now(Eu(a))}:Rf&&!JA?(Tu=new Rf,Iu=Tu.port2,Tu.port1.onmessage=Mf,or=YA(Iu.postMessage,Iu)):_e.addEventListener&&Af(_e.postMessage)&&!_e.importScripts&&_i&&_i.protocol!=="file:"&&!Df(Cf)?(or=Cf,_e.addEventListener("message",Mf,!1)):$f in Lf("script")?or=function(a){kf.appendChild(Lf("script"))[$f]=function(){kf.removeChild(this),wu(a)}}:or=function(a){setTimeout(Eu(a),0)});Vf.exports={set:xu,clear:Pu}});var Bf=f((Z_,Of)=>{"use strict";var _f=se(),ik=Ce(),ak=Object.getOwnPropertyDescriptor;Of.exports=function(a){if(!ik)return _f[a];var e=ak(_f,a);return e&&e.value}});var ku=f((eO,Ff)=>{"use strict";var Nf=function(){this.head=null,this.tail=null};Nf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Ff.exports=Nf});var Uf=f((tO,qf)=>{"use strict";var sk=ir();qf.exports=/ipad|iphone|ipod/i.test(sk)&&typeof Pebble!="undefined"});var jf=f((rO,Hf)=>{"use strict";var nk=ir();Hf.exports=/web0s(?!.*chrome)/i.test(nk)});var Xf=f((iO,Kf)=>{"use strict";var Hr=se(),ok=Bf(),Qf=Vr(),Lu=Au().set,uk=ku(),lk=vu(),ck=Uf(),dk=jf(),Ru=Bs(),Gf=Hr.MutationObserver||Hr.WebKitMutationObserver,Wf=Hr.document,Yf=Hr.process,Ns=Hr.Promise,Cu=ok("queueMicrotask"),Ur,$u,Mu,Fs,zf;Cu||(Oi=new uk,Bi=function(){var a,e;for(Ru&&(a=Yf.domain)&&a.exit();e=Oi.get();)try{e()}catch(t){throw Oi.head&&Ur(),t}a&&a.enter()},!lk&&!Ru&&!dk&&Gf&&Wf?($u=!0,Mu=Wf.createTextNode(""),new Gf(Bi).observe(Mu,{characterData:!0}),Ur=function(){Mu.data=$u=!$u}):!ck&&Ns&&Ns.resolve?(Fs=Ns.resolve(void 0),Fs.constructor=Ns,zf=Qf(Fs.then,Fs),Ur=function(){zf(Bi)}):Ru?Ur=function(){Yf.nextTick(Bi)}:(Lu=Qf(Lu,Hr),Ur=function(){Lu(Bi)}),Cu=function(a){Oi.head||Ur(),Oi.add(a)});var Oi,Bi;Kf.exports=Cu});var Zf=f((aO,Jf)=>{"use strict";Jf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var qs=f((sO,eb)=>{"use strict";eb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ur=f((nO,tb)=>{"use strict";var pk=se();tb.exports=pk.Promise});var jr=f((oO,sb)=>{"use strict";var hk=se(),Ni=ur(),mk=ie(),fk=Lo(),bk=mu(),gk=fe(),rb=pu(),vk=ze(),Du=bo(),ib=Ni&&Ni.prototype,Sk=gk("species"),Vu=!1,ab=mk(hk.PromiseRejectionEvent),yk=fk("Promise",function(){var a=bk(Ni),e=a!==String(Ni);if(!e&&Du===66||vk&&!(ib.catch&&ib.finally))return!0;if(!Du||Du<51||!/native code/.test(a)){var t=new Ni(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Sk]=r,Vu=t.then(function(){})instanceof r,!Vu)return!0}return!e&&(rb==="BROWSER"||rb==="DENO")&&!ab});sb.exports={CONSTRUCTOR:yk,REJECTION_EVENT:ab,SUBCLASSING:Vu}});var Qr=f((uO,ob)=>{"use strict";var nb=at(),Tk=TypeError,Ik=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Tk("Bad Promise constructor");e=r,t=i}),this.resolve=nb(e),this.reject=nb(t)};ob.exports.f=function(a){return new Ik(a)}});var wb=f(()=>{"use strict";var Ek=ue(),xk=ze(),Qs=Bs(),Ct=se(),zr=De(),ub=qr(),lb=nu(),Pk=Ri(),wk=lf(),Ak=at(),js=ie(),kk=Ve(),Lk=df(),Rk=gu(),mb=Au().set,Fu=Xf(),$k=Zf(),Mk=qs(),Ck=ku(),fb=Wo(),Gs=ur(),qu=jr(),bb=Qr(),Ws="Promise",gb=qu.CONSTRUCTOR,Dk=qu.REJECTION_EVENT,Vk=qu.SUBCLASSING,_u=fb.getterFor(Ws),_k=fb.set,Gr=Gs&&Gs.prototype,lr=Gs,Us=Gr,vb=Ct.TypeError,Ou=Ct.document,Uu=Ct.process,Bu=bb.f,Ok=Bu,Bk=!!(Ou&&Ou.createEvent&&Ct.dispatchEvent),Sb="unhandledrejection",Nk="rejectionhandled",cb=0,yb=1,Fk=2,Hu=1,Tb=2,Hs,db,qk,pb,Ib=function(a){var e;return kk(a)&&js(e=a.then)?e:!1},Eb=function(a,e){var t=e.value,r=e.state===yb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Tb&&Hk(e),e.rejection=Hu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new vb("Promise-chain cycle")):(l=Ib(u))?zr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},xb=function(a,e){a.notified||(a.notified=!0,Fu(function(){for(var t=a.reactions,r;r=t.get();)Eb(r,a);a.notified=!1,e&&!a.rejection&&Uk(a)}))},Pb=function(a,e,t){var r,i;Bk?(r=Ou.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Ct.dispatchEvent(r)):r={promise:e,reason:t},!Dk&&(i=Ct["on"+a])?i(r):a===Sb&&$k("Unhandled promise rejection",t)},Uk=function(a){zr(mb,Ct,function(){var e=a.facade,t=a.value,r=hb(a),i;if(r&&(i=Mk(function(){Qs?Uu.emit("unhandledRejection",t,e):Pb(Sb,e,t)}),a.rejection=Qs||hb(a)?Tb:Hu,i.error))throw i.value})},hb=function(a){return a.rejection!==Hu&&!a.parent},Hk=function(a){zr(mb,Ct,function(){var e=a.facade;Qs?Uu.emit("rejectionHandled",e):Pb(Nk,e,a.value)})},Wr=function(a,e,t){return function(r){a(e,r,t)}},Yr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Fk,xb(a,!0))},Nu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new vb("Promise can't be resolved itself");var r=Ib(e);r?Fu(function(){var i={done:!1};try{zr(r,e,Wr(Nu,i,a),Wr(Yr,i,a))}catch(s){Yr(i,s,a)}}):(a.value=e,a.state=yb,xb(a,!1))}catch(i){Yr({done:!1},i,a)}}};if(gb&&(lr=function(e){Lk(this,Us),Ak(e),zr(Hs,this);var t=_u(this);try{e(Wr(Nu,t),Wr(Yr,t))}catch(r){Yr(t,r)}},Us=lr.prototype,Hs=function(e){_k(this,{type:Ws,done:!1,notified:!1,parent:!1,reactions:new Ck,rejection:!1,state:cb,value:void 0})},Hs.prototype=ub(Us,"then",function(e,t){var r=_u(this),i=Bu(Rk(this,lr));return r.parent=!0,i.ok=js(e)?e:!0,i.fail=js(t)&&t,i.domain=Qs?Uu.domain:void 0,r.state===cb?r.reactions.add(i):Fu(function(){Eb(i,r)}),i.promise}),db=function(){var a=new Hs,e=_u(a);this.promise=a,this.resolve=Wr(Nu,e),this.reject=Wr(Yr,e)},bb.f=Bu=function(a){return a===lr||a===qk?new db(a):Ok(a)},!xk&&js(Gs)&&Gr!==Object.prototype)){pb=Gr.then,Vk||ub(Gr,"then",function(e,t){var r=this;return new lr(function(i,s){zr(pb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Gr.constructor}catch(a){}lb&&lb(Gr,Us)}Ek({global:!0,constructor:!0,wrap:!0,forced:gb},{Promise:lr});Pk(lr,Ws,!1,!0);wk(Ws)});var $b=f((dO,Rb)=>{"use strict";var jk=fe(),kb=jk("iterator"),Lb=!1;try{Ab=0,ju={next:function(){return{done:!!Ab++}},return:function(){Lb=!0}},ju[kb]=function(){return this},Array.from(ju,function(){throw 2})}catch(a){}var Ab,ju;Rb.exports=function(a,e){try{if(!e&&!Lb)return!1}catch(i){return!1}var t=!1;try{var r={};r[kb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Qu=f((pO,Mb)=>{"use strict";var Qk=ur(),Gk=$b(),Wk=jr().CONSTRUCTOR;Mb.exports=Wk||!Gk(function(a){Qk.all(a).then(void 0,function(){})})});var Cb=f(()=>{"use strict";var Yk=ue(),zk=De(),Kk=at(),Xk=Qr(),Jk=qs(),Zk=Vs(),eL=Qu();Yk({target:"Promise",stat:!0,forced:eL},{all:function(e){var t=this,r=Xk.f(t),i=r.resolve,s=r.reject,n=Jk(function(){var o=Kk(t.resolve),u=[],l=0,c=1;Zk(e,function(d){var p=l++,h=!1;c++,zk(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Vb=f(()=>{"use strict";var tL=ue(),rL=ze(),iL=jr().CONSTRUCTOR,Wu=ur(),aL=ht(),sL=ie(),nL=qr(),Db=Wu&&Wu.prototype;tL({target:"Promise",proto:!0,forced:iL,real:!0},{catch:function(a){return this.then(void 0,a)}});!rL&&sL(Wu)&&(Gu=aL("Promise").prototype.catch,Db.catch!==Gu&&nL(Db,"catch",Gu,{unsafe:!0}));var Gu});var _b=f(()=>{"use strict";var oL=ue(),uL=De(),lL=at(),cL=Qr(),dL=qs(),pL=Vs(),hL=Qu();oL({target:"Promise",stat:!0,forced:hL},{race:function(e){var t=this,r=cL.f(t),i=r.reject,s=dL(function(){var n=lL(t.resolve);pL(e,function(o){uL(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Ob=f(()=>{"use strict";var mL=ue(),fL=Qr(),bL=jr().CONSTRUCTOR;mL({target:"Promise",stat:!0,forced:bL},{reject:function(e){var t=fL.f(this),r=t.reject;return r(e),t.promise}})});var Yu=f((TO,Bb)=>{"use strict";var gL=st(),vL=Ve(),SL=Qr();Bb.exports=function(a,e){if(gL(a),vL(e)&&e.constructor===a)return e;var t=SL.f(a),r=t.resolve;return r(e),t.promise}});var qb=f(()=>{"use strict";var yL=ue(),TL=ht(),Nb=ze(),IL=ur(),Fb=jr().CONSTRUCTOR,EL=Yu(),xL=TL("Promise"),PL=Nb&&!Fb;yL({target:"Promise",stat:!0,forced:Nb||Fb},{resolve:function(e){return EL(PL&&this===xL?IL:this,e)}})});var Ub=f(()=>{"use strict";wb();Cb();Vb();_b();Ob();qb()});var Gb=f(()=>{"use strict";var wL=ue(),AL=ze(),Ys=ur(),kL=me(),jb=ht(),Qb=ie(),LL=gu(),Hb=Yu(),RL=qr(),Ku=Ys&&Ys.prototype,$L=!!Ys&&kL(function(){Ku.finally.call({then:function(){}},function(){})});wL({target:"Promise",proto:!0,real:!0,forced:$L},{finally:function(a){var e=LL(this,jb("Promise")),t=Qb(a);return this.then(t?function(r){return Hb(e,a()).then(function(){return r})}:a,t?function(r){return Hb(e,a()).then(function(){throw r})}:a)}});!AL&&Qb(Ys)&&(zu=jb("Promise").prototype.finally,Ku.finally!==zu&&RL(Ku,"finally",zu,{unsafe:!0}));var zu});var Yb=f((kO,Wb)=>{"use strict";tf();Ub();Gb();var ML=Mt();Wb.exports=ML("Promise","finally")});var Kb=f((LO,zb)=>{"use strict";var CL=Yb();zb.exports=CL});var zs=f((RO,Xb)=>{"use strict";var DL=Kb();Xb.exports=DL});var cg=f(()=>{"use strict";var YL=ue(),zL=Ho().values;YL({target:"Object",stat:!0},{values:function(e){return zL(e)}})});var pg=f((mB,dg)=>{"use strict";cg();var KL=Mr();dg.exports=KL.Object.values});var mg=f((fB,hg)=>{"use strict";var XL=pg();hg.exports=XL});var Xr=f((bB,fg)=>{"use strict";var JL=mg();fg.exports=JL});var Vg=f(()=>{"use strict";var yR=ue(),TR=Cr(),IR=Nr(),ER=wi(),xR=Ai();yR({target:"Array",proto:!0},{at:function(e){var t=TR(this),r=IR(t),i=ER(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});xR("at")});var Og=f((AN,_g)=>{"use strict";Vg();var PR=Mt();_g.exports=PR("Array","at")});var Ng=f((kN,Bg)=>{"use strict";var wR=Og();Bg.exports=wR});var Bt=f((LN,Fg)=>{"use strict";var AR=Ng();Fg.exports=AR});var yl=f((gq,Tv)=>{"use strict";var c$=tr();Tv.exports=Array.isArray||function(e){return c$(e)==="Array"}});var Ev=f((vq,Iv)=>{"use strict";var d$=TypeError,p$=9007199254740991;Iv.exports=function(a){if(a>p$)throw d$("Maximum allowed index exceeded");return a}});var wv=f((Sq,Pv)=>{"use strict";var h$=yl(),m$=Nr(),f$=Ev(),b$=Vr(),xv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?b$(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&h$(d)?(p=m$(d),u=xv(a,e,d,p,u,s-1)-1):(f$(u+1),a[u]=d),u++),l++;return u};Pv.exports=xv});var Rv=f((yq,Lv)=>{"use strict";var Av=yl(),g$=bu(),v$=Ve(),S$=fe(),y$=S$("species"),kv=Array;Lv.exports=function(a){var e;return Av(a)&&(e=a.constructor,g$(e)&&(e===kv||Av(e.prototype))?e=void 0:v$(e)&&(e=e[y$],e===null&&(e=void 0))),e===void 0?kv:e}});var Mv=f((Tq,$v)=>{"use strict";var T$=Rv();$v.exports=function(a,e){return new(T$(a))(e===0?0:e)}});var Cv=f(()=>{"use strict";var I$=ue(),E$=wv(),x$=at(),P$=Cr(),w$=Nr(),A$=Mv();I$({target:"Array",proto:!0},{flatMap:function(e){var t=P$(this),r=w$(t),i;return x$(e),i=A$(t,0),i.length=E$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Dv=f(()=>{"use strict";var k$=Ai();k$("flatMap")});var _v=f((wq,Vv)=>{"use strict";Cv();Dv();var L$=Mt();Vv.exports=L$("Array","flatMap")});var Bv=f((Aq,Ov)=>{"use strict";var R$=_v();Ov.exports=R$});var Tl=f((kq,Nv)=>{"use strict";var $$=Bv();Nv.exports=$$});var ta=f((Lq,Fv)=>{"use strict";var M$=Li(),C$=String;Fv.exports=function(a){if(M$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return C$(a)}});var Il=f((Rq,qv)=>{"use strict";qv.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=f(($q,Hv)=>{"use strict";var D$=le(),V$=$t(),_$=ta(),xl=Il(),Uv=D$("".replace),O$=RegExp("^["+xl+"]+"),B$=RegExp("(^|[^"+xl+"])["+xl+"]+$"),El=function(a){return function(e){var t=_$(V$(e));return a&1&&(t=Uv(t,O$,"")),a&2&&(t=Uv(t,B$,"$1")),t}};Hv.exports={start:El(1),end:El(2),trim:El(3)}});var Yv=f((Mq,Wv)=>{"use strict";var N$=Ko().PROPER,F$=me(),Qv=Il(),Gv="\u200B\x85\u180E";Wv.exports=function(a){return F$(function(){return!!Qv[a]()||Gv[a]()!==Gv||N$&&Qv[a].name!==a})}});var Pl=f((Cq,zv)=>{"use strict";var q$=jv().start,U$=Yv();zv.exports=U$("trimStart")?function(){return q$(this)}:"".trimStart});var Xv=f(()=>{"use strict";var H$=ue(),Kv=Pl();H$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Kv},{trimLeft:Kv})});var Zv=f(()=>{"use strict";Xv();var j$=ue(),Jv=Pl();j$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Jv},{trimStart:Jv})});var tS=f((Bq,eS)=>{"use strict";Zv();var Q$=Mt();eS.exports=Q$("String","trimLeft")});var iS=f((Nq,rS)=>{"use strict";var G$=tS();rS.exports=G$});var sS=f((Fq,aS)=>{"use strict";var W$=iS();aS.exports=W$});var TS=f(()=>{"use strict"});var IS=f(()=>{"use strict"});var xS=f((EH,ES)=>{"use strict";var bM=Ve(),gM=tr(),vM=fe(),SM=vM("match");ES.exports=function(a){var e;return bM(a)&&((e=a[SM])!==void 0?!!e:gM(a)==="RegExp")}});var wS=f((xH,PS)=>{"use strict";var yM=st();PS.exports=function(){var a=yM(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 LS=f((PH,kS)=>{"use strict";var TM=De(),IM=Ke(),EM=yi(),xM=wS(),AS=RegExp.prototype;kS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in AS)&&!IM(a,"flags")&&EM(AS,a)?TM(xM,a):e}});var $S=f((wH,RS)=>{"use strict";var Cl=le(),PM=Cr(),wM=Math.floor,$l=Cl("".charAt),AM=Cl("".replace),Ml=Cl("".slice),kM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,LM=/\$([$&'`]|\d{1,2})/g;RS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=LM;return i!==void 0&&(i=PM(i),u=kM),AM(s,u,function(l,c){var d;switch($l(c,0)){case"$":return"$";case"&":return a;case"`":return Ml(e,0,t);case"'":return Ml(e,n);case"<":d=i[Ml(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=wM(p/10);return h===0?l:h<=o?r[h-1]===void 0?$l(c,1):r[h-1]+$l(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var DS=f(()=>{"use strict";var RM=ue(),$M=De(),Vl=le(),MS=$t(),MM=ie(),CM=$r(),DM=xS(),ri=ta(),VM=Ii(),_M=LS(),OM=$S(),BM=fe(),NM=ze(),FM=BM("replace"),qM=TypeError,Dl=Vl("".indexOf),UM=Vl("".replace),CS=Vl("".slice),HM=Math.max;RM({target:"String",proto:!0},{replaceAll:function(e,t){var r=MS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!CM(e)){if(i=DM(e),i&&(s=ri(MS(_M(e))),!~Dl(s,"g")))throw new qM("`.replaceAll` does not allow non-global regexes");if(n=VM(e,FM),n)return $M(n,e,r,t);if(NM&&i)return UM(ri(r),e,t)}for(o=ri(r),u=ri(e),l=MM(t),l||(t=ri(t)),c=u.length,d=HM(1,c),p=Dl(o,u);p!==-1;)h=l?ri(t(u,p,o)):OM(u,o,p,[],void 0,t),b+=CS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Dl(o,u,p+d);return m<o.length&&(b+=CS(o,m)),b}})});var _S=f((LH,VS)=>{"use strict";TS();IS();DS();var jM=Mt();VS.exports=jM("String","replaceAll")});var BS=f((RH,OS)=>{"use strict";var QM=_S();OS.exports=QM});var FS=f(($H,NS)=>{"use strict";var GM=BS();NS.exports=GM});var US=f((MH,qS)=>{"use strict";var WM=wi(),YM=ta(),zM=$t(),KM=RangeError;qS.exports=function(e){var t=YM(zM(this)),r="",i=WM(e);if(i<0||i===1/0)throw new KM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var WS=f((CH,GS)=>{"use strict";var QS=le(),XM=Vo(),HS=ta(),JM=US(),ZM=$t(),eC=QS(JM),tC=QS("".slice),rC=Math.ceil,jS=function(a){return function(e,t,r){var i=HS(ZM(e)),s=XM(t),n=i.length,o=r===void 0?" ":HS(r),u,l;return s<=n||o===""?i:(u=s-n,l=eC(o,rC(u/o.length)),l.length>u&&(l=tC(l,0,u)),a?i+l:l+i)}};GS.exports={start:jS(!1),end:jS(!0)}});var zS=f((DH,YS)=>{"use strict";var iC=ir();YS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(iC)});var KS=f(()=>{"use strict";var aC=ue(),sC=WS().start,nC=zS();aC({target:"String",proto:!0,forced:nC},{padStart:function(e){return sC(this,e,arguments.length>1?arguments[1]:void 0)}})});var JS=f((OH,XS)=>{"use strict";KS();var oC=Mt();XS.exports=oC("String","padStart")});var ey=f((BH,ZS)=>{"use strict";var uC=JS();ZS.exports=uC});var ry=f((NH,ty)=>{"use strict";var lC=ey();ty.exports=lC});var sd="2.0.128-dev.3a6dea1e.0";var Pe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Pe||{}),pt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(pt||{});var ms=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ms||{}),io=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(io||{});var ao=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ao||{}),fs=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(fs||{});var BT=_(Fe(),1);import{assertNever as ih,assertNonNullable as Tx,isNonNullable as ys,ValueSubject as Oo,Subject as Ix,Subscription as Ex,merge as xx,observableFrom as Px,fromEvent as Zp,map as eh,tap as th,filterChanged as wx,isNullable as Bo,ErrorCategory as rh}from"@vkontakte/videoplayer-shared/es2015";var Jp=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 Ts=class{constructor(e){this.connection$=new Oo(void 0);this.castState$=new Oo("NOT_AVAILABLE");this.errorEvent$=new Ix;this.realCastState$=new Oo("NOT_AVAILABLE");this.subscription=new Ex;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=ys((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||Jp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:rh.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(){ys(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Bo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Bo(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(Zp(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 ih(i.sessionState)}})).add(xx(Zp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(th(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),eh(i=>i.castState)),Px([r.getCastState()])).pipe(wx(),eh(Ax),th(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=ys(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Tx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Bo(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"?ys(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:rh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Ax=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 ih(a)}};var fc=_(Fe(),1),ST=_(Fr(),1),yT=_(du(),1);var og=_(zs(),1);import{assertNever as Jb}from"@vkontakte/videoplayer-shared/es2015";var be=(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:Jb(t)}return a},Ks=(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:Jb(e)}};var w=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as VL,Subject as Xs,merge as Zb}from"@vkontakte/videoplayer-shared/es2015";var O=class{constructor(e){this.transitionStarted$=new Xs;this.transitionEnded$=new Xs;this.transitionUpdated$=new Xs;this.forceChanged$=new Xs;this.stateChangeStarted$=Zb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Zb(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||VL(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 _L}from"@vkontakte/videoplayer-shared/es2015";var eg=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 _L(a)}};import{assertNever as Kr,assertNonNullable as cr,debounce as tg,ErrorCategory as rg,fromEvent as dr,isNonNullable as ig,map as ag,merge as sg,observableFrom as OL,Subject as BL,Subscription as Xu,timeout as NL,getHighestQuality as FL}from"@vkontakte/videoplayer-shared/es2015";var qL=5,UL=5,HL=500,ng=7e3,Fi=class{constructor(e){this.subscription=new Xu;this.loadMediaTimeoutSubscription=new Xu;this.videoState=new O("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:Kr(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:Kr(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:Kr(e)}break}default:Kr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(eg(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 Xu;this.subscription.add(e),this.subscription.add(sg(this.videoState.stateChangeStarted$.pipe(ag(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(ag(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 BL;e.add(i.pipe(tg(HL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(dr(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)>qL)&&i.next(o),s=o})),e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(dr(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<UL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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:Kr(n)}}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=sg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,OL(["init"])).pipe(tg(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"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(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"),w(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"),w(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"&&w(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];cr(c);let d=FL(Object.keys(c));cr(d);let p=c[d];cr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];cr(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];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];cr(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];cr(c),r=be(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:rg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Kr(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 ig(o)&&(n.metadata.title=o),ig(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(NL(ng).subscribe(()=>s(`timeout(${ng})`)))});(0,og.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:rg.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var vl=_(Fe(),1);import{clearVideoElement as lg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as jL}from"@vkontakte/videoplayer-shared/es2015";var ug=a=>{try{a.pause(),a.playbackRate=0,jL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as QL,Subscription as GL}from"@vkontakte/videoplayer-shared/es2015";var Ju=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)}},Zu=window.WeakMap?new WeakMap:new Ju,el=window.WeakMap?new WeakMap:new Map,WL=(a,e=20)=>{let t=0;return QL(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},we=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?lg(r):(r=document.createElement("video"),a.appendChild(r)),Zu.set(r,i);let s=new GL;return s.add(WL(r,e)),el.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},Ae=a=>{let e=el.get(a);e==null||e.unsubscribe(),el.delete(a);let t=Zu.get(a);Zu.delete(a),t?lg(a):ug(a)};var rl=_(Xr(),1);import{assertNonNullable as qi,isNonNullable as ot,isNullable as tR,fromEvent as Jr,merge as bg,observableFrom as gg,filterChanged as vg,map as Ui,Subject as Sg,Subscription as rR,ValueSubject as iR,ErrorCategory as aR}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as tl,isNullable as ZL,Subscription as eR}from"@vkontakte/videoplayer-shared/es2015";var Js=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=ZL(i),l=new eR;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},nt=(a,e,t)=>Js(e,()=>a.loop,r=>{tl(r)&&(a.loop=r)},{onError:t}),ke=(a,e,t,r)=>Js(e,()=>({muted:a.muted,volume:a.volume}),i=>{tl(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}),qe=(a,e,t,r)=>Js(e,()=>a.playbackRate,i=>{tl(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Dt=Js;var sR=a=>["__",a.language,a.label].join("|"),nR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},il=class a{constructor(e){this.available$=new Sg;this.current$=new iR(void 0);this.error$=new Sg;this.subscription=new rR;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:aR.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(Dt(t.internalTextTracks,()=>(0,rl.default)(this.internalTracks),s=>{ot(s)&&this.setInternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Dt(t.externalTextTracks,()=>(0,rl.default)(this.externalTracks),s=>{ot(s)&&this.setExternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Dt(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(Dt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qi(this.video);let{textTracks:e}=this.video;this.subscription.add(Jr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(bg(Jr(e,"addtrack"),Jr(e,"removetrack"),gg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),vg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(bg(Jr(e,"change"),gg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ui(r=>r&&this.htmlTextTrackToITextTrack(r).id),vg()).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(Jr(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(Jr(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;ot(t.align)&&(i.align=t.align),ot(t.position)&&(i.position=t.position),ot(t.size)&&(i.size=t.size),ot(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){qi(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:sR(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){qi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(tR(e)||!nR(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){qi(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){qi(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)}},Ue=il;var bt=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 yg=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},al=a=>{let e=yg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Tg=a=>{let e=yg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as He,map as Vt,merge as Rg,filterChanged as fR,isNonNullable as $g,Subject as bR,filter as Mg,mapTo as Cg,combine as gR,once as vR,ErrorCategory as SR,ValueSubject as Dg}from"@vkontakte/videoplayer-shared/es2015";var oR=3,Ig=(a,e,t=oR)=>{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 Zs=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,r=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,i=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||r||n||u||l||i||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let r=t[1],i=parseInt(r,10);if(isNaN(i))return;this._safariVersion=i}catch(e){console.error(e)}}};var Eg=_(Fe(),1);var Hi=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var en=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Eg.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Hi()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return x(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,r=/iphone/i.test(e)?"iPhone":void 0,i=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||r||i||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let r=t[1].replace(/_/g,".");if(!r)return;let i=parseFloat(r);if(isNaN(i))return;this._iosVersion=i}catch(e){console.error(e)}}};var tn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(r){console.error(r)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(r){console.error(r)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,rn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},xg=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Pg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var uR=document.createElement("video"),wg,lR=()=>x(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo($(P({},a),{video:$(P({},a.video),{contentType:kg})})),window.navigator.mediaCapabilities.decodingInfo($(P({},a),{video:$(P({},a.video),{contentType:Ag})}))]);wg={DASH_WEBM_AV1:e,DASH_WEBM:t}});lR().catch(a=>{console.log(uR),console.error(a)});var cR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',dR='video/mp4; codecs="hev1.1.6.L93.B0"',Ag='video/webm; codecs="vp09.00.10.08"',kg='video/webm; codecs="av01.0.00M.08"',pR='audio/mp4; codecs="mp4a.40.2"',hR='audio/webm; codecs="opus"',an=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return wg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,r,i,s,n,o,u,l,c,d,p,h,m,b,g,v,S,y,E;this._video=document.createElement("video");try{this._protocols={mms:rn(),mse:xg(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(i=(r=this._video).canPlayType)!=null&&i.call(r,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let I=!!((c=(l=Je())==null?void 0:l.isTypeSupported)!=null&&c.call(l,cR)),L=!!((p=(d=Je())==null?void 0:d.isTypeSupported)!=null&&p.call(d,dR)),M=!!((m=(h=Je())==null?void 0:h.isTypeSupported)!=null&&m.call(h,pR));this._codecs={h264:I,h265:L,vp9:!!((g=(b=Je())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Ag)),av1:!!((S=(v=Je())==null?void 0:v.isTypeSupported)!=null&&S.call(v,kg)),aac:M,opus:!!((E=(y=Je())==null?void 0:y.isTypeSupported)!=null&&E.call(y,hR)),mpeg:(I||L)&&M},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(I){console.error(I)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Lg="audio/mpeg",sn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,r,i;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Lg))},this._codecs={mp3:!!((i=(r=Je())==null?void 0:r.isTypeSupported)!=null&&i.call(r,Lg))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as mR}from"@vkontakte/videoplayer-shared/es2015";var sl=class{constructor(){this.isInited$=new mR(!1);this._displayChecker=new tn,this._deviceChecker=new en(this._displayChecker),this._browserChecker=new Zs,this._videoChecker=new an(this._deviceChecker,this._browserChecker),this._audioChecker=new sn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return x(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},N=new sl;var Le=a=>{let e=y=>He(a,y).pipe(Cg(void 0)),r=Rg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>He(a,y))).pipe(Vt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),fR()),i=Rg(He(a,"progress"),He(a,"timeupdate")).pipe(Vt(()=>Ig(a.buffered,a.currentTime))),s=N.browser.isSafari?gR({play:e("play").pipe(vR()),playing:e("playing")}).pipe(Cg(void 0)):e("playing"),n=He(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=He(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=He(a,"error").pipe(Mg(()=>!!(a.error||a.played.length)),Vt(()=>{var E;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:SR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=He(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new bR,d=.3,p;l.subscribe(y=>{a.loop&&$g(p)&&$g(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(Mg(()=>!a.error&&p!==a.duration)),m=He(a,"enterpictureinpicture"),b=He(a,"leavepictureinpicture"),g=new Dg(Tg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Dg(al(a));return He(a,"fullscreenchange").pipe(Vt(()=>al(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$:He(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as _t}from"@vkontakte/videoplayer-shared/es2015";var Ot=a=>{switch(a){case"mobile":return _t.Q_144P;case"lowest":return _t.Q_240P;case"low":return _t.Q_360P;case"sd":case"medium":return _t.Q_480P;case"hd":case"high":return _t.Q_720P;case"fullhd":case"full":return _t.Q_1080P;case"quadhd":case"quad":return _t.Q_1440P;case"ultrahd":case"ultra":return _t.Q_2160P}};var Nt=_(Bt(),1),Kg=_(Fe(),1),un=_(Fr(),1);import{isNonNullable as Oe,isNullable as Gg,now as Xg,isHigher as Wg,isHigherOrEqual as ll,isInvariantQuality as Yg,isLowerOrEqual as cl,videoSizeToQuality as RR,assertNotEmptyArray as Jg,assertNonNullable as $R}from"@vkontakte/videoplayer-shared/es2015";var nl=!1,gt={},qg=a=>{nl=a},Ug=()=>{gt={}},Hg=a=>{a(gt)},ji=(a,e)=>{var t;nl&&(gt.meta=(t=gt.meta)!=null?t:{},gt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var r,i;if(!nl)return;gt.series=(r=gt.series)!=null?r:{};let t=(i=gt.series[this.name])!=null?i:[];t.push([Date.now(),e]),gt.series[this.name]=t}};import{isHigher as kR,isHigherOrEqual as VN,isLower as jg,isLowerOrEqual as _N,isNonNullable as nn,isNullable as LR,videoHeightToQuality as on}from"@vkontakte/videoplayer-shared/es2015";function ol({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function ul({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&ol({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Qi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return LR(a)||nn(a.min)&&nn(a.max)&&jg(a.max,a.min)||nn(a.min)&&e&&kR(a.min,e)||nn(a.max)&&t&&jg(a.max,t)}function Qg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Qi({limits:{max:a!=null&&a.max?on(a.max):void 0,min:a!=null&&a.min?on(a.min):void 0},highestAvailableQuality:e?on(e):void 0,lowestAvailableQuality:t?on(t):void 0})}var MR=new Ie("best_bitrate"),Zg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var dl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Gi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Xg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ev='Assertion "ABR Tracks is empty array" failed',ln=(a,e,t,r)=>{var u;let i=[...e].sort(dl(1)),s=[...t].sort(dl(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,Kg.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},zg=a=>"quality"in a,tv=(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]&&Xg()-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=zg(o)?"video":"audio",l=zg(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return r==null||r.recordSwitch(t),t},HR=(a,e)=>Math.log(e)/Math.log(a),jR=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&window.devicePixelRatio){let i=window.devicePixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=HR(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return fl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Ut=(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,L,H,_,z,k;Zg(a,tv);let{containerSizeFactor:b,containerSizeLimit:g}=jR({container:e,tuning:r,limits:i}),v=r.considerPlaybackRate&&Be(o)?o:1,S=a.filter(y=>!zg(y.quality)).sort((y,C)=>Yg(y.quality,C.quality)?-1:1),T=(U=(0,qt.default)(S,-1))==null?void 0:U.quality,I=(L=(0,qt.default)(S,0))==null?void 0:L.quality,x=zi({limits:i,lowestAvailableQuality:T,highestAvailableQuality:I}),$=v*ev(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),D={},M=S.filter(y=>{let C=!0;if(g)if(y.size)C=y.size.width<=g.width&&y.size.height<=g.height;else{let ge=g&&FR(g);C=ge?bl(y.quality,ge):!0}if(!C)return D[y.quality]="FitsContainer",!1;let Q=h||t,N=Be(Q)&&isFinite(Q)&&Be(y.bitrate)?Q-s>=y.bitrate*$:!0,Me=fl({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===y.quality;if(!N&&!Me)return D[y.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Be(r.minBufferToSwitchUp)&&u&&!zg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Yg(y.quality,u.quality))return D[y.quality]="Buffer",!1;if(!!d&&ml(y.quality,d)&&!Me)return D[y.quality]="DroppedFramesLimit",!1;if(!!p&&ml(y.quality,p)&&!Me)return D[y.quality]="StallsLimit",!1;let ce=x||(Wg(i==null?void 0:i.max)||bl(y.quality,i.max))&&(Wg(i==null?void 0:i.min)||ml(y.quality,i.min)),be=Be(c)&&!c?bl(y.quality,r.backgroundVideoQualityLimit):!0;return!ce||!be?(D[y.quality]="FitsQualityLimits",!1):!0})[0];M&&M.bitrate&&UR.next(M.bitrate);let q=(H=M!=null?M:(0,qt.default)(S,-1))!=null?H:a[0];return q.quality!==((_=l==null?void 0:l.last)==null?void 0:_.quality)&&f({message:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},CR=(a,e)=>Math.log(e)/Math.log(a),DR=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&N.display.pixelRatio){let i=N.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=CR(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return ul({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},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:m})=>{var Q,R,G,q,J,k;Jg(a,ev);let{containerSizeFactor:b,containerSizeLimit:g}=DR({container:e,tuning:r,limits:i}),v=r.considerPlaybackRate&&Oe(o)?o:1,S=a.filter(T=>!Yg(T.quality)).sort((T,V)=>Wg(T.quality,V.quality)?-1:1),y=(Q=(0,Nt.default)(S,-1))==null?void 0:Q.quality,E=(R=(0,Nt.default)(S,0))==null?void 0:R.quality,I=Qi({limits:i,lowestAvailableQuality:y,highestAvailableQuality:E}),L=v*Zg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),M={},C=S.filter(T=>{let V=!0;if(g)if(T.size)V=T.size.width<=g.width&&T.size.height<=g.height;else{let ye=g&&RR(g);V=ye?cl(T.quality,ye):!0}if(!V)return M[T.quality]="FitsContainer",!1;let Y=h||t,U=Oe(Y)&&isFinite(Y)&&Oe(T.bitrate)?Y-s>=T.bitrate*L:!0,Me=ul({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===T.quality;if(!U&&!Me)return M[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Oe(r.minBufferToSwitchUp)&&u&&!Yg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Wg(T.quality,u.quality))return M[T.quality]="Buffer",!1;if(!!d&&ll(T.quality,d)&&!Me)return M[T.quality]="DroppedFramesLimit",!1;if(!!p&&ll(T.quality,p)&&!Me)return M[T.quality]="StallsLimit",!1;let he=I||(Gg(i==null?void 0:i.max)||cl(T.quality,i.max))&&(Gg(i==null?void 0:i.min)||ll(T.quality,i.min)),Se=Oe(c)&&!c?cl(T.quality,r.backgroundVideoQualityLimit):!0;return!he||!Se?(M[T.quality]="FitsQualityLimits",!1):!0})[0];C&&C.bitrate&&MR.next(C.bitrate);let j=(G=C!=null?C:(0,Nt.default)(S,-1))!=null?G:a[0];return j.quality!==((q=l==null?void 0:l.last)==null?void 0:q.quality)&&m({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(y=>{var C,Q;return`{ id: ${y.id}, quality: ${y.quality}, bitrate: ${y.bitrate}, size: ${(C=y.size)==null?void 0:C.width}:${(Q=y.size)==null?void 0:Q.height} }`}).join(`
12
+ ${a.map(T=>{var V,Y;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${(V=T.size)==null?void 0:V.width}:${(Y=T.size)==null?void 0:Y.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,un.default)(r!=null?r:{}).map(([y,C])=>`${y}: ${C}`).join(`
16
+ ${(0,un.default)(r!=null?r:{}).map(([T,V])=>`${T}: ${V}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
20
  containerSizeFactor: ${b},
21
- containerSizeLimit: ${(z=g==null?void 0:g.width)!=null?z:0} x ${(k=g==null?void 0:g.height)!=null?k:0},
21
+ containerSizeLimit: ${(J=g==null?void 0:g.width)!=null?J:0} x ${(k=g==null?void 0:g.height)!=null?k:0},
22
22
  estimatedThroughput: ${t},
23
23
  stallsPredictedThroughput: ${h},
24
24
  reserve: ${s},
25
25
  playbackRate: ${o},
26
26
  playbackRateFactor: ${v},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${$},
28
+ bitrateFactor: ${L},
29
29
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
30
30
  droppedVideoMaxQualityLimit: ${d},
31
31
  stallsVideoMaxQualityLimit: ${p},
32
- limitsAreInvalid: ${x},
32
+ limitsAreInvalid: ${I},
33
33
  maxQualityLimit: ${i==null?void 0:i.max},
34
34
  minQualityLimit: ${i==null?void 0:i.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,un.default)(D).map(([y,C])=>`${y}: ${C}`).join(`
37
+ ${(0,un.default)(M).map(([T,V])=>`${T}: ${V}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
- [best video track] ${M==null?void 0:M.quality}
41
- [selected video track] ${q==null?void 0:q.quality}
42
- `}),rv(r,f,q,l)},iv=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Zg(t,tv);let c=i.considerPlaybackRate&&Be(s)?s:1,d=[...t].sort(gl(-1)),p=a.bitrate;qR(p);let h=c*ev(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=ln(a,e,t,i.minVideoAudioRatio),g=l||r;return Be(g)&&isFinite(g)&&(f=d.find(S=>Be(S.bitrate)&&Be(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),f||(f=b),(f==null?void 0:f.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
40
+ [best video track] ${C==null?void 0:C.quality}
41
+ [selected video track] ${j==null?void 0:j.quality}
42
+ `}),tv(r,m,j,l)},rv=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Jg(t,ev);let c=i.considerPlaybackRate&&Oe(s)?s:1,d=[...t].sort(dl(-1)),p=a.bitrate;$R(p);let h=c*Zg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,b=ln(a,e,t,i.minVideoAudioRatio),g=l||r;return Oe(g)&&isFinite(g)&&(m=d.find(S=>Oe(S.bitrate)&&Oe(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),m||(m=b),(m==null?void 0:m.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
43
43
  [AUDIO TRACKS ABR]
44
44
  [available audio tracks]
45
45
  ${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,un.default)(i!=null?i:{}).map(([S,T])=>`${S}: ${T}`).join(`
49
+ ${(0,un.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
@@ -59,15 +59,15 @@ var uI=Object.create;var uo=Object.defineProperty,lI=Object.defineProperties,cI=
59
59
  bitrateFactor: ${h},
60
60
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
61
61
 
62
- [selected audio track] ${f==null?void 0:f.id}
63
- `}),f&&rv(i,u,f,o)};var oe=a=>new URL(a).hostname;import{assertNever as fv,assertNonNullable as mv,combine as d$,debounce as p$,ErrorCategory as bv,filter as gv,filterChanged as h$,isNonNullable as Il,map as fn,merge as vv,observableFrom as f$,once as m$,Subscription as b$,ValueSubject as El,videoQualityToHeight as Sv,videoSizeToQuality as g$}from"@vkontakte/videoplayer-shared/es2015";var cv=O(Ft(),1);var sv=O(Xe(),1);var av=a=>{if(a instanceof DOMException&&(0,sv.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},ke=(a,e)=>P(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!av(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return av(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as dn,isNullable as WR,assertNonNullable as Zi}from"@vkontakte/videoplayer-shared/es2015";var ov=O(ei(),1);import{isNonNullable as nv,assertNonNullable as cn,now as QR}from"@vkontakte/videoplayer-shared/es2015";function ue(){return QR()}function vl(a){return ue()-a}function Sl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function uv(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ri(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;cn(c);let L=vl(c),H;if(L<b){H=b-L,setTimeout(g,H);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},v=L=>(s=L,U),S=L=>(d=L,U),T=()=>(h="json",U),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},x=L=>(p=L,U),$=()=>{c=ue(),n=new i,n.open("get",a);let L=0,H,_=0,z=()=>(cn(c),Math.max(c,Math.max(H||0,_||0)));if(s&&n.addEventListener("progress",k=>{let y=ue();s.updateChunk&&k.loaded>L&&(s.updateChunk(z(),k.loaded-L),L=k.loaded,H=y)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;cn(n);let k=n.status;if(k>=200&&k<300){let{response:y,responseType:C}=n,Q=y==null?void 0:y.byteLength;if(typeof Q=="number"&&s){let N=Q-L;N&&s.updateChunk&&s.updateChunk(z(),N)}C==="json"&&(!y||!(0,ov.default)(y).length)?I():(d&&d(),e(y))}else I()}),n.addEventListener("error",()=>{I()}),p){let k=()=>{cn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(_=ue(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),U},U={withBitrateReporting:v,withParallel:x,withJSONResponse:T,withRetryCount:L=>(l=L,U),withRetryInterval:(L,H)=>(nv(L)&&(b=L),nv(H)&&(f=H),U),withTimeout:L=>(o=L,U),withFinally:S,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return U}var Xi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var lv=O(ei(),1);var Ji=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ue(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ue()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ri(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ue()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ue();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,lv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as YR}from"@vkontakte/videoplayer-shared/es2015";var pn=1e4,yl=3;var zR=6e4,KR=10,XR=1,JR=500,ea=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new YR,this.chunkRateEstimator=new Xi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Sl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Sl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Gg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,cv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s))}return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||dn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{uv(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ji(yl,pn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},p=(I,x,$)=>{u&&u.abort(),u=ri(this.urlResolver.resolve(I,!1),x,$,()=>this._retryCallback()).withTimeout(pn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(yl).withFinally(()=>{u=null}).send()},h=(I,x,$)=>{Zi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),x,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let x=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${x}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=ue()-1e4,D=0;for(let M=0;M<this.bufferStates.length;M++){let q=this.bufferStates[M];I=Math.min(I,q.buf),q.ts<$&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${I} drop=${D} jitter=${this.sourceJitter}`);let Z=I-XR;this.sourceJitter>=0?Z-=this.sourceJitter/2:this.sourceJitter-=1,Z>3?f(1.15):Z>1?f(1.1):Z>.3?f(1.05):f(1)}},v=I=>{let x,$=()=>x&&x.start?x.start.length:0,D=k=>x.start[k]/1e3,Z=k=>x.dur[k]/1e3,M=k=>x.fragIndex+k,q=(k,y)=>({chunkIdx:M(k),startTS:D(k),dur:Z(k),discontinuity:y}),U=()=>{let k=0;if(x&&x.dur){let y=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,C=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=y;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let N=x.dur.length-1;for(;N>=0&&(Q-=x.dur[N],!(Q<=0));--N);k=Math.min(N,x.dur.length-1-C),k=Math.max(k,0)}return q(k,!0)},L=k=>{let y=$();if(!(y<=0)){if(dn(k)){for(let C=0;C<y;C++)if(D(C)>k)return q(C)}return U()}},H=k=>{let y=$(),C=k?k.chunkIdx+1:0,Q=C-x.fragIndex;if(!(y<=0)){if(!k||Q<0||Q-y>KR)return t(`Resync: offset=${Q} bChunks=${y} chunk=`+JSON.stringify(k)),U();if(!(Q>=y))return q(C-x.fragIndex,!1)}},_=(k,y,C)=>{l&&l.abort(),l=ri(this.urlResolver.resolve(k,!0,this.lowLatency),y,C,()=>this._retryCallback()).withTimeout(pn).withRetryCount(yl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,y)=>{_(I,C=>{if(!d())return;x=C;let Q=!!x.lowLatency;Q!==this.lowLatency&&b(Q);let N=0;for(let Me=0;Me<x.dur.length;++Me)N+=x.dur[Me];N>0&&(Zi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(N/x.dur.length)),i({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,k(L(y))},()=>this._handleNetworkError())},nextChunk:H}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Zi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:x,logger:$}=this.params,D=v(e.jidxUrl),Z,M,q,U,L=0,H,_,z,k=()=>{H&&(clearTimeout(H),H=void 0);let G=Math.max(JR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=L+G,be=ue(),ge=Math.min(1e4,ce-be);L=be;let xt=()=>{l||d()&&D.seek(()=>{d()&&(L=ue(),y(),k())})};ge>0?H=window.setTimeout(()=>{this.paused?k():xt()},ge):xt()},y=()=>{let G;for(;G=D.nextChunk(U);)U=G,fi(G);let ce=D.nextChunk(q);if(ce){if(q&&ce.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}Me(ce)}else k()},C=(G,ce)=>{if(!d()||!this.sourceBuffer)return;let be,ge,xt,wr=Pt=>{window.setTimeout(()=>{d()&&C(G,ce)},Pt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),wr(100);else{let Pt=ue(),Kt=x.currentTime;!this.paused&&x.buffered.length>1&&_===Kt&&Pt-z>500&&($("Stall suspected; trying to fix"),this._fixupStall()),_!==Kt&&(_=Kt,z=Pt);let Ar=this._getBufferSizeSec();if(Ar>30)$(`Buffered ${Ar} seconds; delaying appendBuffer`),wr(2e3);else try{this.sourceBuffer.appendBuffer(G),this.videoPlayStarted?(this.bufferStates.push({ts:Pt,buf:Ar}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(mi){if(mi.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),xt=this.sourceBuffer.buffered.length,xt!==0&&(be=this.sourceBuffer.buffered.start(0),ge=Kt,ge-be>4&&this.sourceBuffer.remove(be,ge-3)),wr(1e3);else throw mi}}},Q=()=>{M&&Z&&($([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(q)]),C(M,function(){M=null,y()}))},N=G=>e.fragUrlTemplate.replace("%%id%%",G.chunkIdx),Me=G=>{d()&&h(N(G),(ce,be)=>{if(d()){if(be/=1e3,M=ce,q=G,n=G.startTS,be){let ge=Math.min(10,G.dur/be);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ge:ge}Q()}},()=>this._handleNetworkError())},fi=G=>{d()&&(Zi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(N(G),!1)))},Pr=G=>{d()&&(e.cachedHeader=G,C(G,()=>{Z=!0,Q()}))};s=!0,D.seek(G=>{if(d()){if(L=ue(),!G){k();return}U=G,!WR(I)||G.startTS>I?Me(G):(q=G,y())}},I),e.cachedHeader?Pr(e.cachedHeader):p(e.headerUrl,Pr,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),dn(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Zi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return dn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ue();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&vl(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ue();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ri(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(pn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ke(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},zR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var hv=O(Hr(),1);import{debounce as ZR,filter as dv,fromEvent as e$,interval as t$,isHigher as r$,isInvariantQuality as i$,isLower as a$,merge as s$,Subject as pv,Subscription as n$}from"@vkontakte/videoplayer-shared/es2015";var Tl=class{constructor(){this.onDroopedVideoFramesLimit$=new pv;this.subscription=new n$;this.playing=!1;this.tracks=[];this.forceChecker$=new pv;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!i$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&r$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(e$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=t$(this.droppedFramesChecker.checkTime).pipe(dv(()=>this.playing),dv(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(ZR(this.droppedFramesChecker.checkTime)),r=s$(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,hv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>a$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},hn=Tl;import{map as o$,Observable as u$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as l$}from"@vkontakte/videoplayer-shared/es2015";var ta=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var c$=(a,e)=>new u$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||ta()))},E(E({},r),e));i.observe(a);let s=l$(document,"visibilitychange").pipe(o$(n=>!document.hidden||ta())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),He=c$;var v$=["paused","playing","ready"],S$=["paused","playing","ready"],ra=class{constructor(e){this.subscription=new b$;this.videoState=new V("stopped");this.representations$=new El([]);this.droppedFramesManager=new hn;this.maxSeekBackTime$=new El(1/0);this.zeroTime$=new El(void 0);this.liveOffset=new bt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:bv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Nt(u.name))!=null?r:g$(u.video),d=u.bitrate/1e3,p=E({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Il(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,xl.default)(S$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,xl.default)(v$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(he(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(he(this.params.source.url,u))}return;default:return fv(e)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:bv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};vv(this.videoState.stateChangeStarted$.pipe(fn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=xe(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Ae(this.video);this.subscription.add(this.representations$.pipe(fn(i=>i.map(({track:s})=>s)),gv(i=>!!i.length),m$()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(h$(),fn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(d$({zeroTime:this.zeroTime$.pipe(gv(Il)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(we(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Fe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(He(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&Sv(i),min:s&&Sv(s)}),this.params.output.autoVideoTrackLimits$.next({max:i,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return fv(i.to)}},t)).add(vv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,f$(["init"])).pipe(p$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}createLiveDashPlayer(){let e=new ea({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Il(t)?t:Ut(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;mv(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;mv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(he(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var yv=ra;var sT=O(Xe(),1);var ut=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as oC,assertNonNullable as uC,debounce as lC,ErrorCategory as tT,filter as rT,filterChanged as Qa,fromEvent as cC,isNonNullable as iT,map as dc,merge as Ga,observableFrom as pc,once as aT,Subscription as dC}from"@vkontakte/videoplayer-shared/es2015";var mn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ii=class extends mn{constructor(){super(),this.listeners||mn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},ia=class{constructor(){Object.defineProperty(this,"signal",{value:new ii,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ia.prototype[Symbol.toStringTag]="AbortController",ii.prototype[Symbol.toStringTag]="AbortSignal");function bn(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Pl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!bn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var aa=bn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Tv=aa?Pl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=aa?Tv.fetch:window.fetch,WF=aa?Tv.Request:window.Request,fe=aa?ia:window.AbortController,YF=aa?ii:window.AbortSignal;var oc=O(Al(),1);var Pn=O(Ft(),1);var vt=()=>window.ManagedMediaSource||window.MediaSource,gn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},qv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Uv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as An,clientChecker as wn}from"@vkontakte/videoplayer-shared/es2015";var je=document.createElement("video"),j$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Q$='video/mp4; codecs="hev1.1.6.L93.B0"',Zv='video/webm; codecs="vp09.00.10.08"',eS='video/webm; codecs="av01.0.00M.08"',G$='audio/mp4; codecs="mp4a.40.2"',W$='audio/webm; codecs="opus"',Hv,jv,sa={mms:gn(),mse:qv(),hls:!!((Hv=je.canPlayType)!=null&&Hv.call(je,"application/x-mpegurl")||(jv=je.canPlayType)!=null&&jv.call(je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Qv,Gv,Le={mp4:!!((Qv=je.canPlayType)!=null&&Qv.call(je,"video/mp4")),webm:!!((Gv=je.canPlayType)!=null&&Gv.call(je,"video/webm")),cmaf:!0},Sn,Wv,yn,Yv,Tn,zv,In,Kv,En,Xv,xn,Jv,Re={h264:!!((Wv=(Sn=vt())==null?void 0:Sn.isTypeSupported)!=null&&Wv.call(Sn,j$)),h265:!!((Yv=(yn=vt())==null?void 0:yn.isTypeSupported)!=null&&Yv.call(yn,Q$)),vp9:!!((zv=(Tn=vt())==null?void 0:Tn.isTypeSupported)!=null&&zv.call(Tn,Zv)),av1:!!((Kv=(In=vt())==null?void 0:In.isTypeSupported)!=null&&Kv.call(In,eS)),aac:!!((Xv=(En=vt())==null?void 0:En.isTypeSupported)!=null&&Xv.call(En,G$)),opus:!!((Jv=(xn=vt())==null?void 0:xn.isTypeSupported)!=null&&Jv.call(xn,W$))},ai=(Re.h264||Re.h265)&&Re.aac,fr,Y$=()=>P(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(R(E({},a),{video:R(E({},a.video),{contentType:eS})})),window.navigator.mediaCapabilities.decodingInfo(R(E({},a),{video:R(E({},a.video),{contentType:Zv})}))]);fr={DASH_WEBM_AV1:e,DASH_WEBM:t}});Y$().catch(a=>{console.error(a)});var si=sa.hls&&Le.mp4,tS=()=>Object.keys(Re).filter(a=>Re[a]),rS=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=sa.mse&&(!r||!!window.MediaStreamTrack)||sa.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Le.mp4&&ai;case"DASH_WEBM":return i&&Le.webm&&Re.vp9&&Re.opus;case"DASH_WEBM_AV1":return i&&Le.webm&&Re.av1&&Re.opus;case"DASH_STREAMS":return i&&(Le.mp4&&ai||Le.webm&&(Re.vp9||Re.av1)&&(Re.opus||Re.aac));case"DASH_LIVE":return i&&Le.mp4&&ai;case"DASH_LIVE_CMAF":return i&&Le.mp4&&ai&&Le.cmaf;case"DASH_ONDEMAND":return i&&Le.mp4&&ai;case"HLS":case"HLS_ONDEMAND":return si||e&&i&&Le.mp4&&ai;case"HLS_LIVE":case"HLS_LIVE_CMAF":return si;case"MPEG":return Le.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return sa.webrtc&&sa.ws&&Re.h264&&(Le.mp4||Le.webm);default:return An(s)}})},vn=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return fr?fr[t].smooth?[t,e]:fr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return fr?fr[t].powerEfficient?[t,e]:fr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:An(a)}return[e,t]},iS=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...vn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(wn.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...vn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...vn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...vn(a),...i,"HLS","HLS_ONDEMAND"];default:An(e)}return si?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},aS=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=wn.isMac&&wn.isSafari;if(wn.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:An(a)}else si&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},kl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],sS=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Pn.default)(t.value.split("."),0)}for(let t of a){let r=(0,Pn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,Pn.default)(e.value.split("."),0)};var wS=O(PS(),1);import{ErrorCategory as oa}from"@vkontakte/videoplayer-shared/es2015";var AS=a=>{if(!a)return{id:"EmptyResponse",category:oa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:oa.NETWORK,message:`UV Error ${a}`};let e=(0,wS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:oa.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:oa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:oa.PARSER,message:"Response is valid XML, but parser failed"}};var Ht=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as ac,assertNonNullable as yr,clientChecker as qD,combine as Tr,ErrorCategory as ct,filter as Ua,filterChanged as sc,flattenObject as Ha,fromEvent as Ir,getTraceSubscriptionMethod as UD,interval as nc,isNonNullable as Wy,isNullable as Yy,map as di,merge as Er,now as HD,Subject as On,Subscription as zy,tap as jD,throttle as QD,ValueSubject as ie}from"@vkontakte/videoplayer-shared/es2015";var Ln=O(Xe(),1),li=O(Ft(),1),Rn=O(Al(),1);var dM=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},pM=a=>window.clearTimeout(a),kS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),LS=!kS(window.requestIdleCallback)||!kS(window.cancelIdleCallback),Dl=LS?dM:window.requestIdleCallback,ua=LS?pM:window.cancelIdleCallback;var _y=O(tn(),1);import{assertNever as hM,ErrorCategory as RS,clientChecker as Cl,Subject as $S}from"@vkontakte/videoplayer-shared/es2015";var fM=18,MS=!1;try{MS=Cl.isSafari&&!!Cl.macVersion&&Cl.macVersion<=fM}catch(a){console.error(a)}var Vl=class{constructor(e){this.bufferFull$=new $S;this.error$=new $S;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:RS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return P(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return P(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return P(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};MS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:RS.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:hM(t)}}},DS=Vl;var Ol=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Qt,assertNonNullable as $e,clientChecker as RD,ErrorCategory as Tt,fromEvent as Zl,getExponentialDelay as ec,isNonNullable as ui,isNullable as me,now as kn,once as $D,Subject as MD,Subscription as DD,ValueSubject as gr}from"@vkontakte/videoplayer-shared/es2015";var F=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ni=class extends F{};var la=class extends F{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ca=class extends F{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var da=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends F{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var pa=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ha=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var mr=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ma=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends J{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var va=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Sa=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ya=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Ia=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xa=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Pa=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends J{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Aa=class extends J{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ka=class extends J{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var La=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ra=class extends J{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var $a=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var bM={ftyp:ca,moov:da,mvhd:pa,moof:ha,mdat:fa,sidx:mr,trak:ma,mdia:ya,mfhd:xa,tkhd:Ta,traf:Pa,tfhd:wa,tfdt:Aa,trun:ka,minf:Ia,sv3d:ba,st3d:ga,prhd:va,proj:Ea,equi:Sa,uuid:la,stbl:La,stsd:Ra,avc1:$a,unknown:ni},St=class a{constructor(e={}){this.options=E({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=bM[e];return r?new r(t,new a):new ni(t,new a)}};var jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var vM=new TextDecoder("ascii"),SM=a=>vM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",yM=a=>{let e=new mr(a,new St),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},TM=(a,e)=>{let r=new St().parse(a),i=new jt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},IM=a=>{let t=new St().parse(a),r=new jt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},EM=a=>{var i;let t=new St().parse(a);return(i=new jt(t).find("sidx"))==null?void 0:i.timescale},xM=(a,e)=>{let r=new St().parse(a),s=new jt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},PM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new St().parse(a),i=new jt(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},CS={validateData:SM,parseInit:PM,getIndexRange:()=>{},parseSegments:yM,parseFeedableSegmentChunk:TM,getChunkEndTime:xM,getServerLatencyTimestamps:IM,getTimescaleFromIndex:EM};var Da=O(Xe(),1);import{assertNonNullable as _l,isNonNullable as _S,isNullable as AM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as wM}from"@vkontakte/videoplayer-shared/es2015";var VS={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},OS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Ma(a,t),i=r in VS,s=i?VS[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Ma(u),d=l*it(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Ma=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ma(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:wM(e)}},br=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=OS(r);if(!e(i))return;i.type==="master"&&br(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},BS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=OS(a);return br(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(r=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var NS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],kM=[231,22612,22743,167,171,163,160,175],LM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return br(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ze(f,h);l=Ma(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ze(f,h):p===17545?i=Ze(f,h):p===21420&&l===475249515?u=Ze(f,h):p===374648427?br(f,({tag:g,type:v,value:S})=>g===30321?(c=Ze(S,v)===1,!1):!0):s&&n&&(0,Da.default)(NS,p)&&(o=!0),!o}),_l(e,"Failed to parse webm Segment start"),_l(t,"Failed to parse webm Segment end"),_l(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},RM=a=>{if(AM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},$M=(a,e)=>{let t=!1,r=!1,i=o=>_S(o.time)&&_S(o.position),s=[],n;return br(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,Da.default)(NS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},MM=a=>{let e=0,t=!1;try{br(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Da.default)(kM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Da.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},FS={validateData:BS,parseInit:LM,getIndexRange:RM,parseSegments:$M,parseFeedableSegmentChunk:MM};var Ca=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return FS;case"mp4":return CS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Kl=O(ny(),1),My=O(Hr(),1),Dy=O(Iy(),1),Cy=O(Ft(),1),Xl=O(ei(),1);var Ey=O(Xe(),1),jl=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,Ey.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as LD,isNullable as Ry}from"@vkontakte/videoplayer-shared/es2015";var xy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Py=a=>{var e;try{let t=AD(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function AD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
62
+ [selected audio track] ${m==null?void 0:m.id}
63
+ `}),m&&tv(i,u,m,o)};var ce=a=>new URL(a).hostname;import{assertNever as hv,assertNonNullable as mv,combine as t$,debounce as r$,ErrorCategory as fv,filter as bv,filterChanged as i$,isNonNullable as bl,map as mn,merge as gv,observableFrom as a$,once as s$,Subscription as n$,ValueSubject as gl,videoQualityToHeight as vv,videoSizeToQuality as o$}from"@vkontakte/videoplayer-shared/es2015";var lv=_(Bt(),1);var av=_(Fe(),1);var iv=a=>{if(a instanceof DOMException&&(0,av.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Re=(a,e)=>x(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!iv(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return iv(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as dn,isNullable as OR,assertNonNullable as zi}from"@vkontakte/videoplayer-shared/es2015";var nv=_(Xr(),1);import{isNonNullable as sv,assertNonNullable as cn,now as VR}from"@vkontakte/videoplayer-shared/es2015";function de(){return VR()}function pl(a){return de()-a}function hl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ov(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Zr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;cn(c);let R=pl(c),G;if(R<b){G=b-R,setTimeout(g,G);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,L()},v=R=>(s=R,Q),S=R=>(d=R,Q),y=()=>(h="json",Q),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=R=>(p=R,Q),L=()=>{c=de(),n=new i,n.open("get",a);let R=0,G,q=0,J=()=>(cn(c),Math.max(c,Math.max(G||0,q||0)));if(s&&n.addEventListener("progress",k=>{let T=de();s.updateChunk&&k.loaded>R&&(s.updateChunk(J(),k.loaded-R),R=k.loaded,G=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;cn(n);let k=n.status;if(k>=200&&k<300){let{response:T,responseType:V}=n,Y=T==null?void 0:T.byteLength;if(typeof Y=="number"&&s){let U=Y-R;U&&s.updateChunk&&s.updateChunk(J(),U)}V==="json"&&(!T||!(0,nv.default)(T).length)?E():(d&&d(),e(T))}else E()}),n.addEventListener("error",()=>{E()}),p){let k=()=>{cn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=de(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),Q},Q={withBitrateReporting:v,withParallel:I,withJSONResponse:y,withRetryCount:R=>(l=R,Q),withRetryInterval:(R,G)=>(sv(R)&&(b=R),sv(G)&&(m=G),Q),withTimeout:R=>(o=R,Q),withFinally:S,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Q}var Wi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var uv=_(Xr(),1);var Yi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=de(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=de()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Zr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=de()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=de();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,uv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as BR}from"@vkontakte/videoplayer-shared/es2015";var pn=1e4,ml=3;var NR=6e4,FR=10,qR=1,UR=500,Ki=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new BR,this.chunkRateEstimator=new Wi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=hl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=hl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(N.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Qg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,lv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s))}return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||dn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ov(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Yi(ml,pn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let E=s&&(!c||c===this.rep);return E||t("Not running!"),E},p=(E,I,L)=>{u&&u.abort(),u=Zr(this.urlResolver.resolve(E,!1),I,L,()=>this._retryCallback()).withTimeout(pn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ml).withFinally(()=>{u=null}).send()},h=(E,I,L)=>{zi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let I=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),r.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let L=de()-1e4,M=0;for(let C=0;C<this.bufferStates.length;C++){let j=this.bufferStates[C];E=Math.min(E,j.buf),j.ts<L&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${E} drop=${M} jitter=${this.sourceJitter}`);let re=E-qR;this.sourceJitter>=0?re-=this.sourceJitter/2:this.sourceJitter-=1,re>3?m(1.15):re>1?m(1.1):re>.3?m(1.05):m(1)}},v=E=>{let I,L=()=>I&&I.start?I.start.length:0,M=k=>I.start[k]/1e3,re=k=>I.dur[k]/1e3,C=k=>I.fragIndex+k,j=(k,T)=>({chunkIdx:C(k),startTS:M(k),dur:re(k),discontinuity:T}),Q=()=>{let k=0;if(I&&I.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,V=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=T;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let U=I.dur.length-1;for(;U>=0&&(Y-=I.dur[U],!(Y<=0));--U);k=Math.min(U,I.dur.length-1-V),k=Math.max(k,0)}return j(k,!0)},R=k=>{let T=L();if(!(T<=0)){if(dn(k)){for(let V=0;V<T;V++)if(M(V)>k)return j(V)}return Q()}},G=k=>{let T=L(),V=k?k.chunkIdx+1:0,Y=V-I.fragIndex;if(!(T<=0)){if(!k||Y<0||Y-T>FR)return t(`Resync: offset=${Y} bChunks=${T} chunk=`+JSON.stringify(k)),Q();if(!(Y>=T))return j(V-I.fragIndex,!1)}},q=(k,T,V)=>{l&&l.abort(),l=Zr(this.urlResolver.resolve(k,!0,this.lowLatency),T,V,()=>this._retryCallback()).withTimeout(pn).withRetryCount(ml).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,T)=>{q(E,V=>{if(!d())return;I=V;let Y=!!I.lowLatency;Y!==this.lowLatency&&b(Y);let U=0;for(let Me=0;Me<I.dur.length;++Me)U+=I.dur[Me];U>0&&(zi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(U/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,k(R(T))},()=>this._handleNetworkError())},nextChunk:G}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),zi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:I,logger:L}=this.params,M=v(e.jidxUrl),re,C,j,Q,R=0,G,q,J,k=()=>{G&&(clearTimeout(G),G=void 0);let z=Math.max(UR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=R+z,Se=de(),ye=Math.min(1e4,he-Se);R=Se;let Et=()=>{l||d()&&M.seek(()=>{d()&&(R=de(),T(),k())})};ye>0?G=window.setTimeout(()=>{this.paused?k():Et()},ye):Et()},T=()=>{let z;for(;z=M.nextChunk(Q);)Q=z,li(z);let he=M.nextChunk(j);if(he){if(j&&he.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}Me(he)}else k()},V=(z,he)=>{if(!d()||!this.sourceBuffer)return;let Se,ye,Et,Er=xt=>{window.setTimeout(()=>{d()&&V(z,he)},xt)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Er(100);else{let xt=de(),Yt=I.currentTime;!this.paused&&I.buffered.length>1&&q===Yt&&xt-J>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),q!==Yt&&(q=Yt,J=xt);let xr=this._getBufferSizeSec();if(xr>30)L(`Buffered ${xr} seconds; delaying appendBuffer`),Er(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:xt,buf:xr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch(ci){if(ci.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(Se=this.sourceBuffer.buffered.start(0),ye=Yt,ye-Se>4&&this.sourceBuffer.remove(Se,ye-3)),Er(1e3);else throw ci}}},Y=()=>{C&&re&&(L([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(j)]),V(C,function(){C=null,T()}))},U=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),Me=z=>{d()&&h(U(z),(he,Se)=>{if(d()){if(Se/=1e3,C=he,j=z,n=z.startTS,Se){let ye=Math.min(10,z.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ye:ye}Y()}},()=>this._handleNetworkError())},li=z=>{d()&&(zi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(U(z),!1)))},Ir=z=>{d()&&(e.cachedHeader=z,V(z,()=>{re=!0,Y()}))};s=!0,M.seek(z=>{if(d()){if(R=de(),!z){k();return}Q=z,!OR(E)||z.startTS>E?Me(z):(j=z,T())}},E),e.cachedHeader?Ir(e.cachedHeader):p(e.headerUrl,Ir,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),dn(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,zi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return dn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=de();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&pl(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=de();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Zr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(pn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Re(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},NR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var pv=_(Fr(),1);import{debounce as HR,filter as cv,fromEvent as jR,interval as QR,isHigher as GR,isInvariantQuality as WR,isLower as YR,merge as zR,Subject as dv,Subscription as KR}from"@vkontakte/videoplayer-shared/es2015";var fl=class{constructor(){this.onDroopedVideoFramesLimit$=new dv;this.subscription=new KR;this.playing=!1;this.tracks=[];this.forceChecker$=new dv;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!WR(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&GR(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(jR(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=QR(this.droppedFramesChecker.checkTime).pipe(cv(()=>this.playing),cv(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(HR(this.droppedFramesChecker.checkTime)),r=zR(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,pv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>YR(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},hn=fl;import{map as XR,Observable as JR}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as ZR}from"@vkontakte/videoplayer-shared/es2015";var Xi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var e$=(a,e)=>new JR(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Xi()))},P(P({},r),e));i.observe(a);let s=ZR(document,"visibilitychange").pipe(XR(n=>!document.hidden||Xi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),je=e$;var u$=["paused","playing","ready"],l$=["paused","playing","ready"],Ji=class{constructor(e){this.subscription=new n$;this.videoState=new O("stopped");this.representations$=new gl([]);this.droppedFramesManager=new hn;this.maxSeekBackTime$=new gl(1/0);this.zeroTime$=new gl(void 0);this.liveOffset=new bt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:fv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Ot(u.name))!=null?r:o$(u.video),d=u.bitrate/1e3,p=P({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),bl(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,vl.default)(l$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,vl.default)(u$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(be(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(be(this.params.source.url,u))}return;default:return hv(e)}};this.textTracksManager=new Ue(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:fv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};gv(this.videoState.stateChangeStarted$.pipe(mn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(mn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Le(this.video);this.subscription.add(this.representations$.pipe(mn(i=>i.map(({track:s})=>s)),bv(i=>!!i.length),s$()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(i$(),mn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(t$({zeroTime:this.zeroTime$.pipe(bv(bl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(ke(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(qe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&vv(i),min:s&&vv(s)}),this.params.output.autoVideoTrackLimits$.next({max:i,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return hv(i.to)}},t)).add(gv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a$(["init"])).pipe(r$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}createLiveDashPlayer(){let e=new Ki({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&bl(t)?t:Ft(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;mv(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;mv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(be(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Sv=Ji;var Hy=_(Fe(),1);var ut=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as jC,assertNonNullable as QC,debounce as GC,ErrorCategory as Ny,filter as Fy,filterChanged as Fa,fromEvent as WC,isNonNullable as qy,map as ac,merge as Dn,observableFrom as sc,once as Uy,Subscription as YC}from"@vkontakte/videoplayer-shared/es2015";var fn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ei=class extends fn{constructor(){super(),this.listeners||fn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Zi=class{constructor(){Object.defineProperty(this,"signal",{value:new ei,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Zi.prototype[Symbol.toStringTag]="AbortController",ei.prototype[Symbol.toStringTag]="AbortSignal");function bn(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Sl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!bn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ea=bn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),yv=ea?Sl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ea?yv.fetch:window.fetch,mq=ea?yv.Request:window.Request,ge=ea?Zi:window.AbortController,fq=ea?ei:window.AbortSignal;var ec=_(Tl(),1);var nS=_(sS(),1);import{ErrorCategory as ra}from"@vkontakte/videoplayer-shared/es2015";var oS=a=>{if(!a)return{id:"EmptyResponse",category:ra.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ra.NETWORK,message:`UV Error ${a}`};let e=(0,nS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ra.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ra.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ra.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as Xl,assertNonNullable as gr,combine as vr,ErrorCategory as ct,filter as Oa,filterChanged as Jl,flattenObject as Ba,fromEvent as Sr,getTraceSubscriptionMethod as PC,interval as Zl,isNonNullable as $y,isNullable as My,map as ni,merge as yr,now as wC,Subject as kn,Subscription as Cy,tap as AC,throttle as kC,ValueSubject as ne}from"@vkontakte/videoplayer-shared/es2015";var vn=_(Fe(),1),ai=_(Bt(),1),Sn=_(Tl(),1);var Y$=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},z$=a=>window.clearTimeout(a),uS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),lS=!uS(window.requestIdleCallback)||!uS(window.cancelIdleCallback),wl=lS?Y$:window.requestIdleCallback,ia=lS?z$:window.cancelIdleCallback;var vy=_(zs(),1);import{assertNever as K$,ErrorCategory as cS,Subject as dS}from"@vkontakte/videoplayer-shared/es2015";var X$=18,pS=!1;try{pS=N.browser.isSafari&&!!N.browser.safariVersion&&N.browser.safariVersion<=X$}catch(a){console.error(a)}var Al=class{constructor(e){this.bufferFull$=new dS;this.error$=new dS;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:cS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return x(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return x(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return x(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};pS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:cS.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:K$(t)}}},hS=Al;var kl=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Ht,assertNonNullable as $e,ErrorCategory as yt,fromEvent as Ql,getExponentialDelay as Gl,isNonNullable as ii,isNullable as ve,now as gn,once as hC,Subject as mC,Subscription as fC,ValueSubject as mr}from"@vkontakte/videoplayer-shared/es2015";var H=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ti=class extends H{};var aa=class extends H{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var sa=class extends H{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var na=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var te=class extends H{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var oa=class extends te{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ua=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var la=class extends H{constructor(e,t){super(e,t),this.data=this.content}};var pr=class extends te{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ca=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends te{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ha=class extends te{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ma=class extends te{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var fa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends te{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ga=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends te{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ya=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends te{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ia=class extends te{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ea=class extends te{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var xa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends te{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var wa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Z$={ftyp:sa,moov:na,mvhd:oa,moof:ua,mdat:la,sidx:pr,trak:ca,mdia:fa,mfhd:Sa,tkhd:ba,traf:ya,tfhd:Ta,tfdt:Ia,trun:Ea,minf:ga,sv3d:da,st3d:pa,prhd:ha,proj:va,equi:ma,uuid:aa,stbl:xa,stsd:Pa,avc1:wa,unknown:ti},vt=class a{constructor(e={}){this.options=P({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Z$[e];return r?new r(t,new a):new ti(t,new a)}};var Ut=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var tM=new TextDecoder("ascii"),rM=a=>tM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",iM=a=>{let e=new pr(a,new vt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},aM=(a,e)=>{let r=new vt().parse(a),i=new Ut(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},sM=a=>{let t=new vt().parse(a),r=new Ut(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},nM=a=>{var i;let t=new vt().parse(a);return(i=new Ut(t).find("sidx"))==null?void 0:i.timescale},oM=(a,e)=>{let r=new vt().parse(a),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},uM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new vt().parse(a),i=new Ut(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},mS={validateData:rM,parseInit:uM,getIndexRange:()=>{},parseSegments:iM,parseFeedableSegmentChunk:aM,getChunkEndTime:oM,getServerLatencyTimestamps:sM,getTimescaleFromIndex:nM};var ka=_(Fe(),1);import{assertNonNullable as Rl,isNonNullable as vS,isNullable as cM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as lM}from"@vkontakte/videoplayer-shared/es2015";var fS={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},bS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Aa(a,t),i=r in fS,s=i?fS[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Aa(u),d=l*it(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Aa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Aa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:lM(e)}},hr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=bS(r);if(!e(i))return;i.type==="master"&&hr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},gS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=bS(a);return hr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(r=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var SS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],dM=[231,22612,22743,167,171,163,160,175],pM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return hr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=Ze(m,h);l=Aa(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ze(m,h):p===17545?i=Ze(m,h):p===21420&&l===475249515?u=Ze(m,h):p===374648427?hr(m,({tag:g,type:v,value:S})=>g===30321?(c=Ze(S,v)===1,!1):!0):s&&n&&(0,ka.default)(SS,p)&&(o=!0),!o}),Rl(e,"Failed to parse webm Segment start"),Rl(t,"Failed to parse webm Segment end"),Rl(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},hM=a=>{if(cM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},mM=(a,e)=>{let t=!1,r=!1,i=o=>vS(o.time)&&vS(o.position),s=[],n;return hr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,ka.default)(SS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},fM=a=>{let e=0,t=!1;try{hr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ka.default)(dM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ka.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},yS={validateData:gS,parseInit:pM,getIndexRange:hM,parseSegments:mM,parseFeedableSegmentChunk:fM};var La=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return yS;case"mp4":return mS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ul=_(FS(),1),py=_(Fr(),1),hy=_(ry(),1),my=_(Bt(),1),Hl=_(Xr(),1);var iy=_(Fe(),1),_l=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,iy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as pC,isNullable as cy}from"@vkontakte/videoplayer-shared/es2015";var ay=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var sy=a=>{var e;try{let t=cC(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function cC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
64
64
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
65
65
  (-(?<script>[a-z]{4}))?
66
66
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
67
67
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
68
68
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
69
69
  (?:-(?<privateuse>(?:${e})))?
70
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Gl=O(Ft(),1);import{videoSizeToQuality as kD}from"@vkontakte/videoplayer-shared/es2015";var wy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Nt(s):void 0)!=null?u:kD({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Ay=({id:a,bitrate:e})=>({id:a,bitrate:e}),ky=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Ly=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Wl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Gl.default)(r.split("."),0),isDefault:i}),Yl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Gl.default)(i.split("."),0)}),zl=a=>"url"in a,ye=a=>a.type==="template",Va=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var $y=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},yt=(a,e)=>{let t=a;t=(0,Kl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,My.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Kl.default)(t,n,(o,u)=>Ry(s)?o:Ry(u)?s:(0,Dy.default)(s,parseInt(u,10),"0"))}return t},Vy=(a,e)=>{var x,$,D,Z,M,q,U,L,H,_,z,k,y,C,Q,N,Me,fi,Pr,G,ce,be,ge,xt,wr,Pt,Kt,Ar,mi,Rc,$c,Mc,Dc,Cc,Vc,Oc,Bc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,rd,id,ad,sd,nd,od;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Qe=>{var X,Xt;return(Xt=(X=Qe.textContent)==null?void 0:X.trim())!=null?Xt:""}),o=(x=(0,Cy.default)(n,0))!=null?x:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],f=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((Qe,X)=>R(E({},Qe),{[X.id]:X.children}),{}),v=b.reduce((Qe,X)=>R(E({},Qe),{[X.id]:X.getAttribute("duration")}),{});p?d=$y(p):(0,Xl.default)(v).filter(Qe=>Qe).length&&!u?d=(0,Xl.default)(v).reduce((Qe,X)=>{var Xt;return Qe+((Xt=$y(X))!=null?Xt:0)},0):f&&(d=parseInt(f,10));let S=0,T=(D=($=s.getAttribute("profiles"))==null?void 0:$.split(","))!=null?D:[];for(let Qe of b.map(X=>X.id))for(let X of g[Qe]){let Xt=(Z=X.getAttribute("id"))!=null?Z:"id"+(S++).toString(10),bi=(M=X.getAttribute("mimeType"))!=null?M:"",io=(q=X.getAttribute("codecs"))!=null?q:"",ao=(U=X.getAttribute("contentType"))!=null?U:bi==null?void 0:bi.split("/")[0],tI=(H=(L=X.getAttribute("profiles"))==null?void 0:L.split(","))!=null?H:[],ud=(z=Py((_=X.getAttribute("lang"))!=null?_:""))!=null?z:{},ss=(C=(y=(k=X.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:y.trim())!=null?C:void 0,rI=X.querySelectorAll("Representation"),iI=X.querySelector("SegmentTemplate"),aI=(N=(Q=X.querySelector("Role"))==null?void 0:Q.getAttribute("value"))!=null?N:void 0,kr=ao,te={id:Xt,language:ud.language,isDefault:aI==="main",label:ss,codecs:io,hdr:kr==="video"&&jl(io),mime:bi,representations:[]};for(let K of rI){let wt=(Me=K.getAttribute("lang"))!=null?Me:void 0,gi=(Pr=(fi=ss!=null?ss:X.getAttribute("label"))!=null?fi:K.getAttribute("label"))!=null?Pr:void 0,ns=(be=(ce=(G=K.querySelector("BaseURL"))==null?void 0:G.textContent)==null?void 0:ce.trim())!=null?be:"",Jt=new URL(ns||o,e).toString(),At=(ge=K.getAttribute("mimeType"))!=null?ge:bi,os=(wr=(xt=K.getAttribute("codecs"))!=null?xt:io)!=null?wr:"",us;if(ao==="text"){let kt=K.getAttribute("id")||"",ls=((Pt=ud.privateuse)==null?void 0:Pt.includes("x-auto"))||kt.includes("_auto"),Zt=K.querySelector("SegmentTemplate");if(Zt){let vi={representationId:(Kt=K.getAttribute("id"))!=null?Kt:void 0,bandwidth:(Ar=K.getAttribute("bandwidth"))!=null?Ar:void 0},cs=parseInt((mi=K.getAttribute("bandwidth"))!=null?mi:"",10)/1e3,ds=($c=parseInt((Rc=Zt.getAttribute("startNumber"))!=null?Rc:"",10))!=null?$c:1,Lr=parseInt((Mc=Zt.getAttribute("timescale"))!=null?Mc:"",10),so=(Dc=Zt.querySelectorAll("SegmentTimeline S"))!=null?Dc:[],Rr=Zt.getAttribute("media");if(!Rr)continue;let ps=[],hs=0,fs="",$r=0,Si=ds,ve=0;for(let Ge of so){let er=parseInt((Cc=Ge.getAttribute("d"))!=null?Cc:"",10),Ne=parseInt((Vc=Ge.getAttribute("r"))!=null?Vc:"",10)||0,Lt=parseInt((Oc=Ge.getAttribute("t"))!=null?Oc:"",10);ve=Number.isFinite(Lt)?Lt:ve;let tr=er/Lr*1e3,Rt=ve/Lr*1e3;for(let tt=0;tt<Ne+1;tt++){let $t=yt(Rr,R(E({},vi),{segmentNumber:Si.toString(10),segmentTime:(ve+tt*er).toString(10)})),Mr=(Rt!=null?Rt:0)+tt*tr,Ti=Mr+tr;Si++,ps.push({time:{from:Mr,to:Ti},url:$t})}ve+=(Ne+1)*er,hs+=(Ne+1)*tr}$r=ve/Lr*1e3,fs=yt(Rr,R(E({},vi),{segmentNumber:Si.toString(10),segmentTime:ve.toString(10)}));let yi={time:{from:$r,to:1/0},url:fs},pt={type:"template",baseUrl:Jt,segmentTemplateUrl:Rr,initUrl:"",totalSegmentsDurationMs:hs,segments:ps,nextSegmentBeyondManifest:yi,timescale:Lr};us={id:kt,kind:"text",segmentReference:pt,profiles:[],duration:d,bitrate:cs,mime:"",codecs:"",width:0,height:0,isAuto:ls}}else us={id:kt,isAuto:ls,kind:"text",url:Jt}}else{let kt=(_c=(Bc=K.getAttribute("contentType"))!=null?Bc:At==null?void 0:At.split("/")[0])!=null?_c:ao,ls=(Fc=(Nc=X.getAttribute("profiles"))==null?void 0:Nc.split(","))!=null?Fc:[],Zt=parseInt((qc=K.getAttribute("width"))!=null?qc:"",10),vi=parseInt((Uc=K.getAttribute("height"))!=null?Uc:"",10),cs=parseInt((Hc=K.getAttribute("bandwidth"))!=null?Hc:"",10)/1e3,ds=(jc=K.getAttribute("frameRate"))!=null?jc:"",Lr=(Qc=K.getAttribute("quality"))!=null?Qc:void 0,so=ds?xy(ds):void 0,Rr=(Gc=K.getAttribute("id"))!=null?Gc:"id"+(S++).toString(10),ps=kt==="video"?`${vi}p`:kt==="audio"?`${cs}Kbps`:os,hs=`${Rr}@${ps}`,fs=[...T,...tI,...ls],$r,Si=K.querySelector("SegmentBase"),ve=(Wc=K.querySelector("SegmentTemplate"))!=null?Wc:iI;if(Si){let pt=(zc=(Yc=K.querySelector("SegmentBase Initialization"))==null?void 0:Yc.getAttribute("range"))!=null?zc:"",[Ge,er]=pt.split("-").map($t=>parseInt($t,10)),Ne={from:Ge,to:er},Lt=(Kc=K.querySelector("SegmentBase"))==null?void 0:Kc.getAttribute("indexRange"),[tr,Rt]=Lt?Lt.split("-").map($t=>parseInt($t,10)):[],tt=Lt?{from:tr,to:Rt}:void 0;$r={type:"byteRange",url:Jt,initRange:Ne,indexRange:tt}}else if(ve){let pt={representationId:(Xc=K.getAttribute("id"))!=null?Xc:void 0,bandwidth:(Jc=K.getAttribute("bandwidth"))!=null?Jc:void 0},Ge=parseInt((Zc=ve.getAttribute("timescale"))!=null?Zc:"",10),er=(ed=ve.getAttribute("initialization"))!=null?ed:"",Ne=ve.getAttribute("media"),Lt=(rd=parseInt((td=ve.getAttribute("startNumber"))!=null?td:"",10))!=null?rd:1,tr=yt(er,pt);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Rt=(id=ve.querySelectorAll("SegmentTimeline S"))!=null?id:[],tt=[],$t=0,Mr="",Ti=0;if(Rt.length){let ms=Lt,We=0;for(let Dr of Rt){let rt=parseInt((ad=Dr.getAttribute("d"))!=null?ad:"",10),rr=parseInt((sd=Dr.getAttribute("r"))!=null?sd:"",10)||0,bs=parseInt((nd=Dr.getAttribute("t"))!=null?nd:"",10);We=Number.isFinite(bs)?bs:We;let no=rt/Ge*1e3,oo=We/Ge*1e3;for(let gs=0;gs<rr+1;gs++){let nI=yt(Ne,R(E({},pt),{segmentNumber:ms.toString(10),segmentTime:(We+gs*rt).toString(10)})),ld=(oo!=null?oo:0)+gs*no,oI=ld+no;ms++,tt.push({time:{from:ld,to:oI},url:nI})}We+=(rr+1)*rt,$t+=(rr+1)*no}Ti=We/Ge*1e3,Mr=yt(Ne,R(E({},pt),{segmentNumber:ms.toString(10),segmentTime:We.toString(10)}))}else if(LD(d)){let We=parseInt((od=ve.getAttribute("duration"))!=null?od:"",10)/Ge*1e3,Dr=Math.ceil(d/We),rt=0;for(let rr=1;rr<Dr;rr++){let bs=yt(Ne,R(E({},pt),{segmentNumber:rr.toString(10),segmentTime:rt.toString(10)}));tt.push({time:{from:rt,to:rt+We},url:bs}),rt+=We}Ti=rt,Mr=yt(Ne,R(E({},pt),{segmentNumber:Dr.toString(10),segmentTime:rt.toString(10)}))}let sI={time:{from:Ti,to:1/0},url:Mr};$r={type:"template",baseUrl:Jt,segmentTemplateUrl:Ne,initUrl:tr,totalSegmentsDurationMs:$t,segments:tt,nextSegmentBeyondManifest:sI,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!kt||!At)continue;let yi={video:"video",audio:"audio",text:"text"}[kt];if(!yi)continue;kr||(kr=yi),us={id:hs,kind:yi,segmentReference:$r,profiles:fs,duration:d,bitrate:cs,mime:At,codecs:os,width:Zt,height:vi,fps:so,quality:Lr}}te.language||(te.language=wt),te.label||(te.label=gi),te.mime||(te.mime=At),te.codecs||(te.codecs=os),te.hdr||(te.hdr=kr==="video"&&jl(os)),te.representations.push(us)}if(kr){let K=i[kr].find(wt=>wt.id===te.id);if(K&&te.representations.every(wt=>ye(wt.segmentReference)))for(let wt of K.representations){let gi=te.representations.find(At=>At.id===wt.id),ns=gi==null?void 0:gi.segmentReference,Jt=wt.segmentReference;Jt.segments.push(...ns.segments),Jt.nextSegmentBeyondManifest=ns.nextSegmentBeyondManifest}else i[kr].push(te)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var By=O(Xe(),1);import{isNonNullable as Oy}from"@vkontakte/videoplayer-shared/es2015";var Te=(a,e)=>Oy(a)&&Oy(e)&&a.readyState==="open"&&(0,By.default)([...a.activeSourceBuffers],e);var Oa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gr(0);this.currentLowLatencySegmentLength$=new gr(0);this.currentSegmentLength$=new gr(0);this.onLastSegment$=new gr(!1);this.fullyBuffered$=new gr(!1);this.playingRepresentation$=new gr(void 0);this.playingRepresentationInit$=new gr(void 0);this.error$=new MD;this.gaps=[];this.subscription=new DD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new fe;this.switchAbortController=new fe;this.destroyAbortController=new fe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Qt(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){let t=this.representations.get(e);$e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new DS(this.sourceBuffer),this.subscription.add(Zl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Tt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Tt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Zl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Tt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Te(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ol(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ut(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);$e(r,"No init buffer for starting representation"),$e(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=Qt(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(me(s)||me(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ui(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Ss(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Qt(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(me(s)||me(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ui(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Ss(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Qt(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){var u,l;let t=(u=(0,Rn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!ye(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);$e(i);let s=this.segments.get(r);$e(s,"No segments for starting representation");let n=this.initData.get(r);if($e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new fe,Qt(this.switchAbortController.signal,function(r,i=!1){return ae(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);$e(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(me(o)||me(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),$e(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();ui(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!me(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return P(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new fe,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(me(e)||me(this.downloadingRepresentationId)||me(this.playingRepresentationId)||me(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||ui(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if($e(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);ui(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ut(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Ol(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ut(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,Ln.default)(o,i))l="high";else{let c=(0,li.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&ut(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,li.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;ui(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,Rn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,Rn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!ye(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>R(E({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,li.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;$e(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!ye(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=yt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&ua&&ua(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ua&&ua(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&Te(this.mediaSource,this.sourceBuffer)&&!(Ht(this.sourceBuffer.buffered,p)&&Ht(this.sourceBuffer.buffered,h)))&&g&&S});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return P(this,null,function*(){ye(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return P(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Qt(o,function(){return ae(this,null,function*(){let c=ec(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=kn(),!c)return;let d=new DataView(c),p=Ca(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Va(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ye(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return P(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Qt(n,function(){return ae(this,null,function*(){let u=ec(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Zl(window,"online").pipe($D()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=kn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Va(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ye(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,li.default)(e,0).byte.from,to:(0,li.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>P(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=kn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Tt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ye(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=kn();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Tt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Ln.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return P(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ca(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return P(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(!f)continue;let g=Ca(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(me(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer))){!this.isLive&&RD.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ht(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ht(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Tt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",zl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Dl(()=>(0,_y.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return P(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Qt(this.destroyAbortController.signal,function(){return ae(this,null,function*(){let o=ec(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ca(e.mime),i)).then(o=>P(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&ye(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Tt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return P(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return P(this,null,function*(){if(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||me(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(E({},u.time)),i=n(i);let l=zl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Ln.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return P(this,null,function*(){if(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||me(e)?0:ut(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Dl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Tt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(me(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||me(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Tt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ba=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ny=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as _a,assertNever as qy,fromEvent as Uy,merge as CD,now as Na,Subscription as VD,Subject as Hy,ValueSubject as tc,flattenObject as ci,ErrorCategory as Fa}from"@vkontakte/videoplayer-shared/es2015";var Fy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Mn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new tc(void 0);this.lastConnectionReused$=new tc(void 0);this.lastRequestFirstBytes$=new tc(void 0);this.recoverableError$=new Hy;this.error$=new Hy;this.abortAllController=new fe;this.subscription=new VD;this.fetchManifest=_a(this.abortAllController.signal,function(e){return ae(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ba(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Fy(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch($n);return i?(t.log("success",ci({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ci({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=_a(this.abortAllController.signal,function(l){return ae(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,H;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(c,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),c=_.toString();break}default:qy(t)}this.requestQuic&&(c=Ba(c));let h=this.abortAllController.signal,f;if(n){let _=new fe;if(f=CD(Uy(this.abortAllController.signal,"abort"),Uy(n,"abort")).subscribe(()=>{try{_.abort()}catch(z){$n(z)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(z){$n(z)}h=_.signal}let b=Na();p.log("startRequest",ci({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:h}),v=Na();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(v-b),!g.ok||!g.body){f==null||f.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:_}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let _=Na(),z={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",ci(z)),p.end(),g.arrayBuffer()}let[S,T]=g.body.tee(),I=S.getReader();o&&((H=this.throughputEstimator)==null||H.trackStream(T,u));let x=0,$=new Uint8Array(0),D=!1,Z=_=>{f==null||f.unsubscribe(),D=!0,$n(_)},M=_a(h,function(k){return ae(this,arguments,function*({done:_,value:z}){if(x===0&&this.lastRequestFirstBytes$.next(Na()-b),h.aborted){f==null||f.unsubscribe();return}if(!_&&z){let y=new Uint8Array($.length+z.length);y.set($),y.set(z,$.length),$=y,x+=z.byteLength,i==null||i(new DataView($.buffer),x),yield I==null?void 0:I.read().then(M,Z)}})}.bind(this));yield I==null?void 0:I.read().then(M,Z),f==null||f.unsubscribe();let q=Na(),U={failed:D,requestStartedAt:b,requestEndedAt:q,duration:q-b};return D?(p.error("endRequest",ci(U)),p.end(),null):(p.log("endRequest",ci(U)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=_a(this.abortAllController.signal,function(e,t,r){return ae(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=_a(this.abortAllController.signal,function(e,t){return ae(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>R(E({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=Ny(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return P(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:qy(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return P(this,null,function*(){let r=yield lt(e,t);if(r.ok)return r;let i=yield r.text(),s=parseInt(i);switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Fa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Fa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Fa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Fa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Fa.FATAL})}})}},$n=a=>{if(!Va(a))throw a};var vr=(a,e,t)=>t*e+(1-t)*a,rc=(a,e)=>a.reduce((t,r)=>t+r,0)/e,jy=(a,e,t,r)=>{let i=0,s=t,n=rc(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as OD,ValueSubject as Qy}from"@vkontakte/videoplayer-shared/es2015";var Gt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Qy(e.initial),this.debounced$=new Qy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Se(`raw_${t}`),this.smoothedSeries$=new Se(`smoothed_${t}`),this.reportedSeries$=new Se(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=it(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(OD(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var Dn=class extends Gt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vr(this.slow,e,this.params.emaAlphaSlow),this.fast=vr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Cn=class extends Gt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=rc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vr(this.emaSmoothed,e,this.params.emaAlpha);let r=jy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Vn=class extends Gt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?vr(this.smoothed,t,this.params.emaAlpha):t}};var Sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Dn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Cn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Vn(E({initial:e,label:"liveEdgeDelay"},t))}};var ic=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as BD,ValueSubject as _D}from"@vkontakte/videoplayer-shared/es2015";var qa=class a{constructor(e,t){this.currentRepresentation$=new _D(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!BD(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(R(E({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ye(t.segmentReference))}};var GD=["timeupdate","progress","play","seeked","stalled","waiting"],WD=["timeupdate","progress","loadeddata","playing","seeked"];var Bn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new zy;this.representationSubscription=new zy;this.state$=new V("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new On;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.currentLiveTextRepresentation$=new ie(null);this.isLive$=new ie(!1);this.isActiveLive$=new ie(!1);this.isLowLatency$=new ie(!1);this.liveDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLatency$=new ie(void 0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.currentStallDuration$=new ie(0);this.videoLastDataObtainedTimestamp$=new ie(0);this.fetcherRecoverableError$=new On;this.fetcherError$=new On;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new On;this.gapWatchdogActive=!1;this.destroyController=new fe;this.initManifest=ac(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=he(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ac(this.destroyController.signal,function(){return ae(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Vy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=AS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=vt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=sS(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);qD.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=R(E({},t),{streams:i});return this.tracer.log("updateManifestEnd",Ha(s)),s})}.bind(this));this.initRepresentations=ac(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",Ha({initialVideo:e,initialAudio:t,sourceHls:r})),yr(this.manifest),yr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Ir(p,"error").pipe(Ua(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Uv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&gn())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Oa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Wy(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Oa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}qa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new qa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(nc(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=rn(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,f+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Er(...WD.map(p=>Ir(this.element,p))).pipe(di(p=>this.element?ut(this.element.buffered,this.element.currentTime*1e3):0),sc(),jD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Er(Ir(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(Tr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(di(({isActiveLive:h,isLowLatency:f})=>h&&f),sc()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ic(this.element,1)})),this.representationSubscription.add(Tr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ua(({bufferLength:h,isActiveLive:f,isLowLatency:b})=>f&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(Tr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$,currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Ua(({isActiveLive:h,isLowLatency:f,currentLowLatencySegmentLength:b})=>h&&f&&!!b)).subscribe(({currentLowLatencySegmentLength:h})=>{let f=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(f,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(Tr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ua(({isLive:h})=>h),di(h=>E({},h)),sc((h,f)=>f.bufferLength<h.bufferLength),di(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=rn(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Tr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:b})=>{if(!b||!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-g;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(T)>v&&(I=1+Math.sign(T)*S),ic(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(T=>{var I,x;return(x=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?x:v}))-v}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Tr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(QD(1e3)).subscribe(b=>P(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(yr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=rn(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(h)?h:f,D=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),Z=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLive$.next(Z);let M="none";if(D?M="active_low_latency":this.isLowLatency$.getValue()&&Z?(this.bufferManagers.forEach(q=>q.proceedLowLatencyLive()),M="active_low_latency"):v!==0&&$<T?M="live_forward_buffering":$<T+x&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let q=p-(T+I),U=this.normolizeLiveOffset(Math.trunc(v+q/g)),L=Math.abs(U-v),H;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?H=v:U>0&&L>this.tuning.dashCmafLive.offsetCalculationError?H=U:H=0,this.manifestUrlString=he(this.manifestUrlString,H,2)}M!=="none"&&M!=="active_low_latency"&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Er(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(di(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Er(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(di(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(Er(this.forceEnded$,Tr({allBuffersFull:l,someBufferEnded:c}).pipe(Ua(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Er(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,oc.default)((0,oc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),ye(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Wy(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=nc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Mn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Sr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return P(this,null,function*(){var r,i,s;yr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLive$.next(t===0),this.liveLastSeekOffset=t,this.manifestUrlString=he(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){yr(this.element),this.state$.setState("running"),this.subscription.add(Er(...GD.map(e=>Ir(this.element,e)),Ir(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ir(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ir(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ht(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,v,S,T,I,x,$;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=HD(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(I=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset).catch(D=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:D})}),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let D=this.element.currentTime*1e3;(x=this.videoBufferManager)==null||x.maintain(D),($=this.audioBufferManager)==null||$.maintain(D),i.position=D}this.tracer.log("stallIntervalCallback",Ha(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=nc(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return P(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)})}seek(e,t){return P(this,null,function*(){var i,s,n,o,u;yr(this.element),yr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Ht(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Yy(this.element)||Yy(this.videoBufferManager))&&(this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Ha({requestedPosition:e,forcePrecise:t,position:r})))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=UD(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return P(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),r={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=i&&u.to+n>i&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,r=R(E({},r),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Ha(r)))}}};var _n=class{constructor(e,t){this.fov=e,this.orientation=t}};var Nn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/it(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=E({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*it(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Ky=`attribute vec2 a_vertex;
70
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Bl=_(Bt(),1);import{videoSizeToQuality as dC}from"@vkontakte/videoplayer-shared/es2015";var ny=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ot(s):void 0)!=null?u:dC({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},oy=({id:a,bitrate:e})=>({id:a,bitrate:e}),uy=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ly=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Nl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Bl.default)(r.split("."),0),isDefault:i}),Fl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Bl.default)(i.split("."),0)}),ql=a=>"url"in a,Ee=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var dy=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},St=(a,e)=>{let t=a;t=(0,Ul.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,py.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ul.default)(t,n,(o,u)=>cy(s)?o:cy(u)?s:(0,hy.default)(s,parseInt(u,10),"0"))}return t},fy=(a,e)=>{var I,L,M,re,C,j,Q,R,G,q,J,k,T,V,Y,U,Me,li,Ir,z,he,Se,ye,Et,Er,xt,Yt,xr,ci,Ic,Ec,xc,Pc,wc,Ac,kc,Lc,Rc,$c,Mc,Cc,Dc,Vc,_c,Oc,Bc,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Qe=>{var ee,zt;return(zt=(ee=Qe.textContent)==null?void 0:ee.trim())!=null?zt:""}),o=(I=(0,my.default)(n,0))!=null?I:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],m=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((Qe,ee)=>$(P({},Qe),{[ee.id]:ee.children}),{}),v=b.reduce((Qe,ee)=>$(P({},Qe),{[ee.id]:ee.getAttribute("duration")}),{});p?d=dy(p):(0,Hl.default)(v).filter(Qe=>Qe).length&&!u?d=(0,Hl.default)(v).reduce((Qe,ee)=>{var zt;return Qe+((zt=dy(ee))!=null?zt:0)},0):m&&(d=parseInt(m,10));let S=0,y=(M=(L=s.getAttribute("profiles"))==null?void 0:L.split(","))!=null?M:[];for(let Qe of b.map(ee=>ee.id))for(let ee of g[Qe]){let zt=(re=ee.getAttribute("id"))!=null?re:"id"+(S++).toString(10),di=(C=ee.getAttribute("mimeType"))!=null?C:"",Kn=(j=ee.getAttribute("codecs"))!=null?j:"",Xn=(Q=ee.getAttribute("contentType"))!=null?Q:di==null?void 0:di.split("/")[0],NT=(G=(R=ee.getAttribute("profiles"))==null?void 0:R.split(","))!=null?G:[],ed=(J=sy((q=ee.getAttribute("lang"))!=null?q:""))!=null?J:{},Za=(V=(T=(k=ee.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:T.trim())!=null?V:void 0,FT=ee.querySelectorAll("Representation"),qT=ee.querySelector("SegmentTemplate"),UT=(U=(Y=ee.querySelector("Role"))==null?void 0:Y.getAttribute("value"))!=null?U:void 0,Pr=Xn,ae={id:zt,language:ed.language,isDefault:UT==="main",label:Za,codecs:Kn,hdr:Pr==="video"&&_l(Kn),mime:di,representations:[]};for(let Z of FT){let Pt=(Me=Z.getAttribute("lang"))!=null?Me:void 0,pi=(Ir=(li=Za!=null?Za:ee.getAttribute("label"))!=null?li:Z.getAttribute("label"))!=null?Ir:void 0,es=(Se=(he=(z=Z.querySelector("BaseURL"))==null?void 0:z.textContent)==null?void 0:he.trim())!=null?Se:"",Kt=new URL(es||o,e).toString(),wt=(ye=Z.getAttribute("mimeType"))!=null?ye:di,ts=(Er=(Et=Z.getAttribute("codecs"))!=null?Et:Kn)!=null?Er:"",rs;if(Xn==="text"){let At=Z.getAttribute("id")||"",is=((xt=ed.privateuse)==null?void 0:xt.includes("x-auto"))||At.includes("_auto"),Xt=Z.querySelector("SegmentTemplate");if(Xt){let hi={representationId:(Yt=Z.getAttribute("id"))!=null?Yt:void 0,bandwidth:(xr=Z.getAttribute("bandwidth"))!=null?xr:void 0},as=parseInt((ci=Z.getAttribute("bandwidth"))!=null?ci:"",10)/1e3,ss=(Ec=parseInt((Ic=Xt.getAttribute("startNumber"))!=null?Ic:"",10))!=null?Ec:1,wr=parseInt((xc=Xt.getAttribute("timescale"))!=null?xc:"",10),Jn=(Pc=Xt.querySelectorAll("SegmentTimeline S"))!=null?Pc:[],Ar=Xt.getAttribute("media");if(!Ar)continue;let ns=[],os=0,us="",kr=0,mi=ss,Te=0;for(let Ge of Jn){let Jt=parseInt((wc=Ge.getAttribute("d"))!=null?wc:"",10),Ne=parseInt((Ac=Ge.getAttribute("r"))!=null?Ac:"",10)||0,kt=parseInt((kc=Ge.getAttribute("t"))!=null?kc:"",10);Te=Number.isFinite(kt)?kt:Te;let Zt=Jt/wr*1e3,Lt=Te/wr*1e3;for(let tt=0;tt<Ne+1;tt++){let Rt=St(Ar,$(P({},hi),{segmentNumber:mi.toString(10),segmentTime:(Te+tt*Jt).toString(10)})),Lr=(Lt!=null?Lt:0)+tt*Zt,bi=Lr+Zt;mi++,ns.push({time:{from:Lr,to:bi},url:Rt})}Te+=(Ne+1)*Jt,os+=(Ne+1)*Zt}kr=Te/wr*1e3,us=St(Ar,$(P({},hi),{segmentNumber:mi.toString(10),segmentTime:Te.toString(10)}));let fi={time:{from:kr,to:1/0},url:us},dt={type:"template",baseUrl:Kt,segmentTemplateUrl:Ar,initUrl:"",totalSegmentsDurationMs:os,segments:ns,nextSegmentBeyondManifest:fi,timescale:wr};rs={id:At,kind:"text",segmentReference:dt,profiles:[],duration:d,bitrate:as,mime:"",codecs:"",width:0,height:0,isAuto:is}}else rs={id:At,isAuto:is,kind:"text",url:Kt}}else{let At=(Rc=(Lc=Z.getAttribute("contentType"))!=null?Lc:wt==null?void 0:wt.split("/")[0])!=null?Rc:Xn,is=(Mc=($c=ee.getAttribute("profiles"))==null?void 0:$c.split(","))!=null?Mc:[],Xt=parseInt((Cc=Z.getAttribute("width"))!=null?Cc:"",10),hi=parseInt((Dc=Z.getAttribute("height"))!=null?Dc:"",10),as=parseInt((Vc=Z.getAttribute("bandwidth"))!=null?Vc:"",10)/1e3,ss=(_c=Z.getAttribute("frameRate"))!=null?_c:"",wr=(Oc=Z.getAttribute("quality"))!=null?Oc:void 0,Jn=ss?ay(ss):void 0,Ar=(Bc=Z.getAttribute("id"))!=null?Bc:"id"+(S++).toString(10),ns=At==="video"?`${hi}p`:At==="audio"?`${as}Kbps`:ts,os=`${Ar}@${ns}`,us=[...y,...NT,...is],kr,mi=Z.querySelector("SegmentBase"),Te=(Nc=Z.querySelector("SegmentTemplate"))!=null?Nc:qT;if(mi){let dt=(qc=(Fc=Z.querySelector("SegmentBase Initialization"))==null?void 0:Fc.getAttribute("range"))!=null?qc:"",[Ge,Jt]=dt.split("-").map(Rt=>parseInt(Rt,10)),Ne={from:Ge,to:Jt},kt=(Uc=Z.querySelector("SegmentBase"))==null?void 0:Uc.getAttribute("indexRange"),[Zt,Lt]=kt?kt.split("-").map(Rt=>parseInt(Rt,10)):[],tt=kt?{from:Zt,to:Lt}:void 0;kr={type:"byteRange",url:Kt,initRange:Ne,indexRange:tt}}else if(Te){let dt={representationId:(Hc=Z.getAttribute("id"))!=null?Hc:void 0,bandwidth:(jc=Z.getAttribute("bandwidth"))!=null?jc:void 0},Ge=parseInt((Qc=Te.getAttribute("timescale"))!=null?Qc:"",10),Jt=(Gc=Te.getAttribute("initialization"))!=null?Gc:"",Ne=Te.getAttribute("media"),kt=(Yc=parseInt((Wc=Te.getAttribute("startNumber"))!=null?Wc:"",10))!=null?Yc:1,Zt=St(Jt,dt);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Lt=(zc=Te.querySelectorAll("SegmentTimeline S"))!=null?zc:[],tt=[],Rt=0,Lr="",bi=0;if(Lt.length){let ls=kt,We=0;for(let Rr of Lt){let rt=parseInt((Kc=Rr.getAttribute("d"))!=null?Kc:"",10),er=parseInt((Xc=Rr.getAttribute("r"))!=null?Xc:"",10)||0,cs=parseInt((Jc=Rr.getAttribute("t"))!=null?Jc:"",10);We=Number.isFinite(cs)?cs:We;let Zn=rt/Ge*1e3,eo=We/Ge*1e3;for(let ds=0;ds<er+1;ds++){let jT=St(Ne,$(P({},dt),{segmentNumber:ls.toString(10),segmentTime:(We+ds*rt).toString(10)})),td=(eo!=null?eo:0)+ds*Zn,QT=td+Zn;ls++,tt.push({time:{from:td,to:QT},url:jT})}We+=(er+1)*rt,Rt+=(er+1)*Zn}bi=We/Ge*1e3,Lr=St(Ne,$(P({},dt),{segmentNumber:ls.toString(10),segmentTime:We.toString(10)}))}else if(pC(d)){let We=parseInt((Zc=Te.getAttribute("duration"))!=null?Zc:"",10)/Ge*1e3,Rr=Math.ceil(d/We),rt=0;for(let er=1;er<Rr;er++){let cs=St(Ne,$(P({},dt),{segmentNumber:er.toString(10),segmentTime:rt.toString(10)}));tt.push({time:{from:rt,to:rt+We},url:cs}),rt+=We}bi=rt,Lr=St(Ne,$(P({},dt),{segmentNumber:Rr.toString(10),segmentTime:rt.toString(10)}))}let HT={time:{from:bi,to:1/0},url:Lr};kr={type:"template",baseUrl:Kt,segmentTemplateUrl:Ne,initUrl:Zt,totalSegmentsDurationMs:Rt,segments:tt,nextSegmentBeyondManifest:HT,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!At||!wt)continue;let fi={video:"video",audio:"audio",text:"text"}[At];if(!fi)continue;Pr||(Pr=fi),rs={id:os,kind:fi,segmentReference:kr,profiles:us,duration:d,bitrate:as,mime:wt,codecs:ts,width:Xt,height:hi,fps:Jn,quality:wr}}ae.language||(ae.language=Pt),ae.label||(ae.label=pi),ae.mime||(ae.mime=wt),ae.codecs||(ae.codecs=ts),ae.hdr||(ae.hdr=Pr==="video"&&_l(ts)),ae.representations.push(rs)}if(Pr){let Z=i[Pr].find(Pt=>Pt.id===ae.id);if(Z&&ae.representations.every(Pt=>Ee(Pt.segmentReference)))for(let Pt of Z.representations){let pi=ae.representations.find(wt=>wt.id===Pt.id),es=pi==null?void 0:pi.segmentReference,Kt=Pt.segmentReference;Kt.segments.push(...es.segments),Kt.nextSegmentBeyondManifest=es.nextSegmentBeyondManifest}else i[Pr].push(ae)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var gy=_(Fe(),1);import{isNonNullable as by}from"@vkontakte/videoplayer-shared/es2015";var xe=(a,e)=>by(a)&&by(e)&&a.readyState==="open"&&(0,gy.default)([...a.activeSourceBuffers],e);var $a=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new mr(0);this.currentLowLatencySegmentLength$=new mr(0);this.currentSegmentLength$=new mr(0);this.onLastSegment$=new mr(!1);this.fullyBuffered$=new mr(!1);this.playingRepresentation$=new mr(void 0);this.playingRepresentationInit$=new mr(void 0);this.error$=new mC;this.gaps=[];this.subscription=new fC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ge;this.switchAbortController=new ge;this.destroyAbortController=new ge;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ht(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);$e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new hS(this.sourceBuffer),this.subscription.add(Ql(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:yt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:yt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Ql(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:yt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!xe(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,kl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ut(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);$e(r,"No init buffer for starting representation"),$e(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=Ht(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ii(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new hs(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Ht(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ii(n)&&(this.isLive||(this.bufferLimit=1/0,yield new hs(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Ht(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var u,l;let t=(u=(0,Sn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Ee(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);$e(i);let s=this.segments.get(r);$e(s,"No segments for starting representation");let n=this.initData.get(r);if($e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ge,Ht(this.switchAbortController.signal,function(r,i=!1){return oe(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);$e(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(ve(o)||ve(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),$e(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();ii(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!ve(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return x(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ge,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!xe(this.mediaSource,this.sourceBuffer)||ii(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if($e(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);ii(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ut(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&kl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ut(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,vn.default)(o,i))l="high";else{let c=(0,ai.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&ut(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ai.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;ii(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,Sn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,Sn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ee(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>$(P({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ai.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;$e(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Ee(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=St(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&ia&&ia(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ia&&ia(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&xe(this.mediaSource,this.sourceBuffer)&&!(qt(this.sourceBuffer.buffered,p)&&qt(this.sourceBuffer.buffered,h)))&&g&&S});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return x(this,null,function*(){Ee(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return x(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ht(o,function(){return oe(this,null,function*(){let c=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=gn(),!c)return;let d=new DataView(c),p=La(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ra(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ee(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return x(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Ht(n,function(){return oe(this,null,function*(){let u=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ql(window,"online").pipe(hC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=gn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Ee(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ai.default)(e,0).byte.from,to:(0,ai.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>x(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=gn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:yt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!Ee(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=gn();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:yt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,vn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return x(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=La(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return x(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<i,b=p<=i;if(!m)continue;let g=La(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(ve(this.sourceBuffer)||!xe(this.mediaSource,this.sourceBuffer))){!this.isLive&&N.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:yt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ql(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=wl(()=>(0,vy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return x(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ht(this.destroyAbortController.signal,function(){return oe(this,null,function*(){let o=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,La(e.mime),i)).then(o=>x(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ee(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:yt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return x(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return x(this,null,function*(){if(!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ve(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(P({},u.time)),i=n(i);let l=ql(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,vn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return x(this,null,function*(){if(!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ve(e)?0:ut(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=wl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:yt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ve(this.sourceBuffer)||!xe(this.mediaSource,this.sourceBuffer)||ve(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:yt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ma=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Sy=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ca,assertNever as Ty,fromEvent as Iy,merge as bC,now as Da,Subscription as gC,Subject as Ey,ValueSubject as Wl,flattenObject as si,ErrorCategory as Va}from"@vkontakte/videoplayer-shared/es2015";var yy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Tn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Wl(void 0);this.lastConnectionReused$=new Wl(void 0);this.lastRequestFirstBytes$=new Wl(void 0);this.recoverableError$=new Ey;this.error$=new Ey;this.abortAllController=new ge;this.subscription=new gC;this.fetchManifest=Ca(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ma(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=yy(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(yn);return i?(t.log("success",si({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",si({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Ca(this.abortAllController.signal,function(l){return oe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,G;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let q=new URL(c,location.href);q.searchParams.append("bytes",`${r.from}-${r.to}`),c=q.toString();break}default:Ty(t)}this.requestQuic&&(c=Ma(c));let h=this.abortAllController.signal,m;if(n){let q=new ge;if(m=bC(Iy(this.abortAllController.signal,"abort"),Iy(n,"abort")).subscribe(()=>{try{q.abort()}catch(J){yn(J)}}),this.abortAllController.signal.aborted||n.aborted)try{q.abort()}catch(J){yn(J)}h=q.signal}let b=Da();p.log("startRequest",si({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:h}),v=Da();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let q=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:q}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){m==null||m.unsubscribe();let q=Da(),J={requestStartedAt:b,requestEndedAt:q,duration:q-b};return p.log("endRequest",si(J)),p.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),E=S.getReader();o&&((G=this.throughputEstimator)==null||G.trackStream(y,u));let I=0,L=new Uint8Array(0),M=!1,re=q=>{m==null||m.unsubscribe(),M=!0,yn(q)},C=Ca(h,function(k){return oe(this,arguments,function*({done:q,value:J}){if(I===0&&this.lastRequestFirstBytes$.next(Da()-b),h.aborted){m==null||m.unsubscribe();return}if(!q&&J){let T=new Uint8Array(L.length+J.length);T.set(L),T.set(J,L.length),L=T,I+=J.byteLength,i==null||i(new DataView(L.buffer),I),yield E==null?void 0:E.read().then(C,re)}})}.bind(this));yield E==null?void 0:E.read().then(C,re),m==null||m.unsubscribe();let j=Da(),Q={failed:M,requestStartedAt:b,requestEndedAt:j,duration:j-b};return M?(p.error("endRequest",si(Q)),p.end(),null):(p.log("endRequest",si(Q)),p.end(),L.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Ca(this.abortAllController.signal,function(e,t,r){return oe(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ca(this.abortAllController.signal,function(e,t){return oe(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>$(P({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=Sy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return x(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Ty(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return x(this,null,function*(){let r=yield lt(e,t);if(r.ok)return r;let i=yield r.text(),s=parseInt(i);switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Va.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Va.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Va.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Va.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Va.FATAL})}})}},yn=a=>{if(!Ra(a))throw a};var fr=(a,e,t)=>t*e+(1-t)*a,Yl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,xy=(a,e,t,r)=>{let i=0,s=t,n=Yl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as vC,ValueSubject as Py}from"@vkontakte/videoplayer-shared/es2015";var jt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Py(e.initial),this.debounced$=new Py(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=it(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(vC(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var In=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=fr(this.slow,e,this.params.emaAlphaSlow),this.fast=fr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var En=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Yl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=fr(this.emaSmoothed,e,this.params.emaAlpha);let r=xy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var xn=class extends jt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?fr(this.smoothed,t,this.params.emaAlpha):t}};var br=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new In({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new En({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new xn(P({initial:e,label:"liveEdgeDelay"},t))}};var zl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as SC,ValueSubject as yC}from"@vkontakte/videoplayer-shared/es2015";var _a=class a{constructor(e,t){this.currentRepresentation$=new yC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!SC(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next($(P({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ee(t.segmentReference))}};var wn=_(Bt(),1);import{assertNever as An}from"@vkontakte/videoplayer-shared/es2015";var wy=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let{containers:i,protocols:s,codecs:n,nativeHlsSupported:o}=N.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!r||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&i.mp4&&u;case"DASH_WEBM":return l&&i.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&i.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(i.mp4&&u||i.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&i.mp4&&u;case"DASH_LIVE_CMAF":return l&&i.mp4&&u&&i.cmaf;case"DASH_ONDEMAND":return l&&i.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&i.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(i.mp4||i.webm);default:return An(c)}})},Pn=a=>{let{webmDecodingInfo:e}=N.video,t="DASH_WEBM",r="DASH_WEBM_AV1";switch(a){case"vp9":return[t,r];case"av1":return[r,t];case"none":return[];case"smooth":return e?e[r].smooth?[r,t]:e[t].smooth?[t,r]:[r,t]:[t,r];case"power_efficient":return e?e[r].powerEfficient?[r,t]:e[t].powerEfficient?[t,r]:[r,t]:[t,r];default:An(a)}return[t,r]},Ay=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Pn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(N.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...Pn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Pn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Pn(a),...i,"HLS","HLS_ONDEMAND"];default:An(e)}return N.video.nativeHlsSupported?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},ky=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=N.device.isMac&&N.browser.isSafari;if(N.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:An(a)}else N.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Kl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ly=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,wn.default)(t.value.split("."),0)}for(let t of a){let r=(0,wn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,wn.default)(e.value.split("."),0)};var LC=["timeupdate","progress","play","seeked","stalled","waiting"],RC=["timeupdate","progress","loadeddata","playing","seeked"];var Ln=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Cy;this.representationSubscription=new Cy;this.state$=new O("none");this.currentVideoRepresentation$=new ne(void 0);this.currentVideoRepresentationInit$=new ne(void 0);this.currentAudioRepresentation$=new ne(void 0);this.currentVideoSegmentLength$=new ne(0);this.currentAudioSegmentLength$=new ne(0);this.error$=new kn;this.lastConnectionType$=new ne(void 0);this.lastConnectionReused$=new ne(void 0);this.lastRequestFirstBytes$=new ne(void 0);this.currentLiveTextRepresentation$=new ne(null);this.isLive$=new ne(!1);this.isActiveLive$=new ne(!1);this.isLowLatency$=new ne(!1);this.liveDuration$=new ne(0);this.liveAvailabilityStartTime$=new ne(void 0);this.bufferLength$=new ne(0);this.liveLatency$=new ne(void 0);this.liveLoadBufferLength$=new ne(0);this.livePositionFromPlayer$=new ne(0);this.currentStallDuration$=new ne(0);this.videoLastDataObtainedTimestamp$=new ne(0);this.fetcherRecoverableError$=new kn;this.fetcherError$=new kn;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new kn;this.gapWatchdogActive=!1;this.destroyController=new ge;this.initManifest=Xl(this.destroyController.signal,function(e,t,r){return oe(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=be(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Xl(this.destroyController.signal,function(){return oe(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=fy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=Je())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=Ly(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);N.display.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=$(P({},t),{streams:i});return this.tracer.log("updateManifestEnd",Ba(s)),s})}.bind(this));this.initRepresentations=Xl(this.destroyController.signal,function(e,t,r){return oe(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",Ba({initialVideo:e,initialAudio:t,sourceHls:r})),gr(this.manifest),gr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Sr(p,"error").pipe(Oa(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Pg():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&rn())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new $a("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],$y(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new $a("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}_a.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new _a(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Zl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Ks(this.manifestUrlString,2);this.manifestUrlString=be(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(yr(...RC.map(p=>Sr(this.element,p))).pipe(ni(p=>this.element?ut(this.element.buffered,this.element.currentTime*1e3):0),Jl(),AC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(yr(Sr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(vr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ni(({isActiveLive:h,isLowLatency:m})=>h&&m),Jl()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||zl(this.element,1)})),this.representationSubscription.add(vr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Oa(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(vr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$,currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Oa(({isActiveLive:h,isLowLatency:m,currentLowLatencySegmentLength:b})=>h&&m&&!!b)).subscribe(({currentLowLatencySegmentLength:h})=>{let m=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(vr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Oa(({isLive:h})=>h),ni(h=>P({},h)),Jl((h,m)=>m.bufferLength<h.bufferLength),ni(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let g=Ks(this.manifestUrlString,2);return(h/2+m+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(vr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-g;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>v&&(E=1+Math.sign(y)*S),zl(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let m=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var E,I;return(I=(E=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?I:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(vr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(kC(1e3)).subscribe(b=>x(this,[b],function*({liveLoadBufferLength:h,bufferLength:m}){if(gr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Ks(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,L=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),re=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLive$.next(re);let C="none";if(M?C="active_low_latency":this.isLowLatency$.getValue()&&re?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),C="active_low_latency"):v!==0&&L<y?C="live_forward_buffering":L<y+I&&(C="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),C==="live_forward_buffering"||C==="live_with_target_offset"){let j=p-(y+E),Q=this.normolizeLiveOffset(Math.trunc(v+j/g)),R=Math.abs(Q-v),G;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?G=v:Q>0&&R>this.tuning.dashCmafLive.offsetCalculationError?G=Q:G=0,this.manifestUrlString=be(this.manifestUrlString,G,2)}C!=="none"&&C!=="active_low_latency"&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=yr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ni(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=yr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ni(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(yr(this.forceEnded$,vr({allBuffersFull:l,someBufferEnded:c}).pipe(Oa(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(yr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,ec.default)((0,ec.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ee(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&$y(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Zl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Tn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=br.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,P({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return x(this,null,function*(){var r,i,s;gr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLive$.next(t===0),this.liveLastSeekOffset=t,this.manifestUrlString=be(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){gr(this.element),this.state$.setState("running"),this.subscription.add(yr(...LC.map(e=>Sr(this.element,e)),Sr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Sr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Sr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,S,y,E,I,L;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=wC(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(E=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?E:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset).catch(M=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:M})}),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let M=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(M),(L=this.audioBufferManager)==null||L.maintain(M),i.position=M}this.tracer.log("stallIntervalCallback",Ba(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Zl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return x(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)})}seek(e,t){return x(this,null,function*(){var i,s,n,o,u;gr(this.element),gr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),qt(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(My(this.element)||My(this.videoBufferManager))&&(this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Ba({requestedPosition:e,forcePrecise:t,position:r})))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=PC(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return x(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),r={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=i&&u.to+n>i&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,r=$(P({},r),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Ba(r)))}}};var Rn=class{constructor(e,t){this.fov=e,this.orientation=t}};var $n=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/it(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=P({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*it(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Dy=`attribute vec2 a_vertex;
71
71
  attribute vec2 a_texel;
72
72
 
73
73
  varying vec2 v_texel;
@@ -78,7 +78,7 @@ void main(void) {
78
78
  // save texel vector to pass to fragment shader
79
79
  v_texel = a_texel;
80
80
  }
81
- `;var Xy=`#ifdef GL_ES
81
+ `;var Vy=`#ifdef GL_ES
82
82
  precision highp float;
83
83
  precision highp int;
84
84
  #else
@@ -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 Fn=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 _n(this.params.fov,this.params.orientation),this.cameraRotationManager=new Nn(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(Ky,this.gl.VERTEX_SHADER),r=this.createShader(Xy,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 KD,now as Jy,Subscription as XD,filter as JD,combine as Zy,ValueSubject as uc,isNonNullable as ZD}from"@vkontakte/videoplayer-shared/es2015";var lc=class{constructor(){this.isSeeked$=new uc(!1);this.isBuffering$=new uc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new XD;this.severeStallOccurred$=new uc(!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(Zy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(JD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Zy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(KD(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=Jy(),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,ZD(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=Jy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},eT=lc;import{combine as eC,map as tC,observeElementSize as rC,Subscription as iC,ValueSubject as cc,noop as aC}from"@vkontakte/videoplayer-shared/es2015";var qn=class{constructor(){this.subscription=new iC;this.pipSize$=new cc(void 0);this.videoSize$=new cc(void 0);this.elementSize$=new cc(void 0);this.pictureInPictureWindowRemoveEventListener=aC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(rC(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(eC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(tC(({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 xr=class{constructor(e){this.subscription=new dC;this.videoState=new V("stopped");this.droppedFramesManager=new hn;this.stallsManager=new eT;this.elementSizeManager=new qn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ki;this.audioTrackSwitchHistory=new Ki;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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&w(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"&&w(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"&&w(this.params.desiredState.playbackState,"paused");return;default:return oC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Fn(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=xe(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(oe(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 Bn({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=Ae(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:tT.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(rT(l=>!!l.length),aT()).subscribe(l=>{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:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(dc(l=>l.to.state!=="none"),Qa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Qa()),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.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(rT(iT),aT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(dc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(we(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"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(Ga(r.pause$,r.ended$).subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(uC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Wl(h));let f=[];for(let b of h.representations){let g=Ay(b);f.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Yl(p));let h=[];for(let f of p.representations){let b=wy(R(E({},f),{streamId:p.id}));b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=ky(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add(Ga(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$,cC(this.video,"progress")).subscribe(()=>P(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,sT.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===p.id});iT(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,g)}}),i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Qa()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Yl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Wl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},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 o=t.playbackState.stateChangeStarted$.pipe(dc(({to:l})=>l==="ready"),Qa());this.subscription.add(Ga(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,pc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Ga(o,this.player.state$.stateChangeEnded$,pc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Ga(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pc(["init"])).pipe(lC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var D,Z,M,q,U,L,H,_,z,k,y,C,Q;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(D=e.videoTrack.getState())==null?void 0:D.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===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:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ut(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let 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=(L=[...this.audioStreamsMap.keys()].find(({id:N})=>N===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let N=ln(n,c,(H=this.audioStreamsMap.get(g))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(_=N==null?void 0:N.bitrate)!=null?_:-1/0)}if(o){let N=ln(o,c,(z=this.audioStreamsMap.get(g))!=null?z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=N==null?void 0:N.bitrate)!=null?k:-1/0)}}let S=Ut(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,I=g&&iv(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}),x=(C=this.videoTracksMap.get(T))==null?void 0:C.representation,$=I&&((Q=this.audioTracksMap.get(I))==null?void 0:Q.representation);if(x&&$)return[x,$];if(x&&!$&&this.audioTracksMap.size===0)return[x,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tT.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),this.params.output.currentVideoStream$.next(void 0),Pe(this.video),this.tracer.end()}};var Wa=class extends xr{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 nT,interval as pC,map as oT}from"@vkontakte/videoplayer-shared/es2015";var Ya=class extends xr{constructor(e){super(e),this.liveOffset=new bt,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(oT(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(nT({interval:pC(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(nT({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(oT(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Ly(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 lT=O(tn(),1);import{assertNever as za,assertNonNullable as uT,debounce as hC,ErrorCategory as Un,filter as fC,isNonNullable as mC,isNullable as bC,map as Hn,merge as gC,Observable as vC,observableFrom as SC,Subscription as yC,videoSizeToQuality as TC}from"@vkontakte/videoplayer-shared/es2015";var et={};var pi=(a,e)=>new vC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ka=class{constructor(e){this.subscription=new yC;this.videoState=new V("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:za(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:za(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:za(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:za(e)}break;default:za(t)}};this.textTracksManager=new qe(e.source.url),this.video=xe(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(oe(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),Pe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Un.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,lT.default)(import("hls.js").then(i=>{e||(et.Hls=i.default,et.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){uT(et.Hls,"hls.js not loaded"),this.hls=new et.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){uT(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Un.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ae(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(nt(this.video,e.isLooped,r)),this.subscription.add(we(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(Hn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(pi(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Un.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"),w(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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,et.Events.MANIFEST_PARSED).pipe(Hn(({levels:l})=>l.reduce((c,d)=>{var S,T;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(T=Nt((S=d.attrs.QUALITY)!=null?S:""))!=null?T:TC({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,et.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,et.Events.LEVEL_LOADING).pipe(Hn(({url:l})=>oe(l))),t.hostname$),s(pi(this.hls,et.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(Ot(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,et.Events.LEVEL_SWITCHED).pipe(Hn(({level:l})=>n(this.hls.levels[l])));o.pipe(fC(mC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ot(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(bC(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=gC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,SC(["init"])).pipe(hC(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 P(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Un.DOM,thrown:t})))||(this.videoState.setState("paused"),w(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"),w(this.params.desiredState.playbackState,"stopped",!0)}};var cT="X-Playback-Duration",hc=a=>P(void 0,null,function*(){var i;let e=yield lt(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(cT)?parseInt(e.headers.get(cT),10):void 0});import{assertNever as MC,combine as DC,debounce as CC,ErrorCategory as Gn,filter as VC,filterChanged as OC,isNonNullable as hT,isNullable as Wn,map as fT,merge as BC,observableFrom as _C,Subscription as NC,ValueSubject as bc,VideoQuality as FC}from"@vkontakte/videoplayer-shared/es2015";var mc=O(vu(),1);import{videoSizeToQuality as IC,getExponentialDelay as EC}from"@vkontakte/videoplayer-shared/es2015";var xC=a=>{let e=null;if(a.QUALITY&&(e=Nt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=IC({width:t,height:r})}return e!=null?e:null},PC=(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,mc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=xC(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(I=>parseInt(I,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,mc.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}},wC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),fc=0,dT=(i,...s)=>P(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield lt(a,r)).text();fc+=1;try{let{qualityManifests:u,textTracks:l}=PC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(fc<=t.manifestRetryMaxCount)return yield wC(EC(fc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),dT(a,e,t)}return{qualityManifests:[],textTracks:[]}}),jn=dT;import{isNonNullable as AC,Subscription as kC,throttle as LC,ValueSubject as pT,Subject as RC,ErrorCategory as $C}from"@vkontakte/videoplayer-shared/es2015";var Qn=class{constructor(e,t,r,i,s){this.subscription=new kC;this.abortControllers={destroy:new fe,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new pT(null);this.getCurrentTime$=new pT(null);this.error$=new RC;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(LC(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 P(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 P(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 P(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield lt(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(AC(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([R(E({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return P(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new fe;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 P(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:$C.WTF,thrown:t,message:e})}};var Xa=class{constructor(e){this.subscription=new NC;this.videoState=new V("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new bc([]);this.liveOffset=new bt;this.manifestStartTime$=new bc(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"),w(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"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(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"&&w(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"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return MC(t)}};var r;this.params=e,this.video=xe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:FC.INVARIANT,url:this.params.source.url};let t=(i,s)=>jn(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:Gn.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:Gn.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(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new bc((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:Gn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ae(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(we(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"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(OC(),fT(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&&hT(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(oe(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(DC({startTime:this.manifestStartTime$.pipe(VC(hT)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(fT(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=BC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,_C(["init"])).pipe(CC(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),Pe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Wn(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=he(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),hc(n).then(c=>{var d;if(!Wn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Wn(p)||!isFinite(p))&&lt(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();hc(g).then(v=>{Wn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Gn.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=he(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 qC,debounce as UC,ErrorCategory as gc,fromEvent as vc,isNonNullable as HC,isNullable as jC,map as mT,merge as Sc,observableFrom as bT,Subscription as QC,ValueSubject as GC,VideoQuality as WC,clientChecker as YC}from"@vkontakte/videoplayer-shared/es2015";var Ja=class{constructor(e){this.subscription=new QC;this.videoState=new V("stopped");this.manifests$=new GC([]);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"),w(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"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return qC(t)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=xe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:WC.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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),jn(he(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:gc.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||!i.from)&&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:gc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ae(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(mT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(we(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(Sc(i.pause$,i.ended$).subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready")},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&&HC(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(oe(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(mT(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)),!YC.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Sc(vc(o,"addtrack"),vc(o,"removetrack"),vc(o,"change"),bT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Sc(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,bT(["init"])).pipe(UC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Pe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(jC(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(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var yT=O(Hr(),1),yc=O(ei(),1),TT=O(Ft(),1);import{assertNever as zC,assertNonNullable as gT,debounce as KC,ErrorCategory as vT,isHigherOrEqual as XC,isLowerOrEqual as JC,isNonNullable as ZC,merge as ST,observableFrom as e0,Subscription as t0,map as r0}from"@vkontakte/videoplayer-shared/es2015";var Za=class{constructor(e){this.subscription=new t0;this.videoState=new V("stopped");this.trackUrls={};this.textTracksManager=new qe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(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);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return zC(e)}};this.params=e,this.video=xe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,yT.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,yc.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:vT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ae(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(r0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(we(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"),w(t.playbackState,"playing")},r)).add(ST(i.pause$,i.ended$).subscribe(()=>{this.videoState.setState("paused"),w(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&&ZC(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)}}},r)),this.textTracksManager.connect(this.video,t,e);let n=ST(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,e0(["init"])).pipe(KC(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),Pe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;gT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];gT(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(oe(t))}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Ut(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,yc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||zi({limits:e,lowestAvailableQuality:(c=(0,TT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?JC(i,e.max):!0,u=e.min?XC(i,e.min):!0;o&&u||r(e)}};import{assertNever as ET,debounce as n0,merge as xT,observableFrom as o0,Subscription as u0,map as PT,ValueSubject as l0,ErrorCategory as Ic,VideoQuality as c0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as i0}from"@vkontakte/videoplayer-shared/es2015";var IT=["stun:videostun.mycdn.me:80"],a0=1e3,s0=3,Tc=()=>null,Yn=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=Tc;this.externalStopCallback=Tc;this.externalErrorCallback=Tc;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 P(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 P(this,null,function*(){try{let e={iceServers:[{urls:IT}]};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 P(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return P(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:i0.WTF,message:e.message})}onPeerConnectionStream(e){return P(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 P(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),a0)}normalizeOptions(e={}){let t={stunServerList:IT,maxRetryNumber:s0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var es=class{constructor(e){this.videoState=new V("stopped");this.maxSeekBackTime$=new l0(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"),w(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"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return ET(e)}};this.subscription=new u0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=xe(e.container,e.tuning),this.liveStreamClient=new Yn(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),Pe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ic.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};xT(this.videoState.stateChangeStarted$.pipe(PT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(PT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ae(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(we(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 ET(n.to)}},r)).add(xT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,o0(["init"])).pipe(n0(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(oe(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:c0.INVARIANT}),this.video.srcObject=e,w(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:Ic.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ic.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ts=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 is,assertNonNullable as Wt,ErrorCategory as zn,filter as $T,isNonNullable as MT,isNullable as v0,map as S0,merge as y0,once as T0,Subject as le,Subscription as DT,ValueSubject as B,flattenObject as CT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as d0,map as wT,Subscription as p0,Subject as h0}from"@vkontakte/videoplayer-shared/es2015";var AT=a=>new d0(e=>{let t=new p0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(wT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(wT(({type:l})=>l!==void 0)),n=new h0,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 f0,Subscription as m0,combine as b0,filter as LT,once as RT}from"@vkontakte/videoplayer-shared/es2015";function kT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as g0}from"@vkontakte/videoplayer-shared/es2015";var rs=class rs{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new fe;this.subscriptions=new m0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(LT(s=>!!s.type),RT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){g0.isSafari&&e!=="MPEG"||this.subscriptions.add(b0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(LT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),RT()).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 P(this,null,function*(){let{volumeMultiplier:t}=this,r=kT();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:rs.errorId,category:f0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${rs.errorId} exception`,thrown:e})}};rs.errorId="VolumeMultiplierManager";var hi=rs;var I0={chunkDuration:5e3,maxParallelRequests:5},as=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new le;this.noAvailableProvidersError$=new le;this.volumeMultiplierError$=new le;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new le,fetcherError$:new le,fetcherRecoverableError$: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 B(void 0),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),severeStallOccurred$:new le,availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B(""),getCurrentTime$:new B(null)};this.subscription=new DT;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=rS([...aS(this.params.tuning),...iS(this.params.tuning)],this.params.tuning).filter(l=>MT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Ec.default)(i,l)),...t.filter(l=>(0,Ec.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",CT(s)),this.screenFormatsIterator=new ts(s);let n=[...kl(!0),...kl(!1)];this.chromecastFormatsIterator=new ts(n.filter(l=>MT(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(v0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:zn.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 is(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 Wa(R(E({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Ya(R(E({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Wt(o),si||!this.params.tuning.useHlsJs?new Ja(R(E({},n),{source:o})):new Ka(R(E({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Xa(R(E({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Za(R(E({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new yv(R(E({},n),{source:o,config:R(E({},I0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new es({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 is(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 Qi({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 is(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return is(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 is(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 R(E({},e),{url:r(e.url)})}return(0,OT.default)((0,VT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new DT,t=!1,r=0;return e.add(y0(this.providerOutput.error$.pipe($T(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),AT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(S0(i=>({id:`ProviderHangup:${i}`,category:zn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe($T(({to:s})=>s==="playing"),T0()).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===zn.NETWORK,u=i.category===zn.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=R(E({},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",CT(n))})),e}};import{fromEvent as Kn,once as E0,combine as x0,Subscription as BT,ValueSubject as xc,map as P0,filter as w0,isNonNullable as Xn,now as _e,safeStorage as Pc}from"@vkontakte/videoplayer-shared/es2015";var A0=5e3,_T="one_video_throughput",NT="one_video_rtt",It=window.navigator.connection,FT=()=>{let a=It==null?void 0:It.downlink;if(Xn(a)&&a!==10)return a*1e3},qT=()=>{let a=It==null?void 0:It.rtt;if(Xn(a)&&a!==3e3)return a},UT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wc=class a{constructor(e){this.subscription=new BT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(_T)||(e.useBrowserEstimation?FT():void 0)||A0,r=(s=(i=a.load(NT))!=null?i:e.useBrowserEstimation?qT():void 0)!=null?s:0;if(this.throughput$=new xc(t),this.rtt$=new xc(r),this.rttAdjustedThroughput$=new xc(UT(t,r,e.rttPenaltyRequestSize)),this.throughput=Sr.getSmoothedValue(t,-1,e),this.rtt=Sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=FT();u&&this.throughput.next(u);let l=qT();Xn(l)&&this.rtt.next(l)};It&&"onchange"in It&&this.subscription.add(Kn(It,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Pc.set(_T,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Pc.set(NT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(x0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(P0(({throughput:n,rtt:o})=>UT(n,o,e.rttPenaltyRequestSize)),w0(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=_e(),i=new BT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Kn(e,"progress").pipe(E0()).subscribe(s=>{t=s.loaded,r=_e()}));break;case 1:case 0:i.add(Kn(e,"loadstart").subscribe(()=>{t=0,r=_e()}));break}i.add(Kn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=_e(),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=_e(),n=0,o=_e(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>P(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,_e()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=_e();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=_e()}else n+=d.byteLength;o=_e()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&_e()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,_e()-o,this.concurrentDownloads.size),n=0,o=_e());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=Pc.get(e);if(Xn(t))return(r=parseInt(t,10))!=null?r:void 0}},HT=wc;import{fillWithDefault as k0,VideoQuality as Jn}from"@vkontakte/videoplayer-shared/es2015";var jT={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:Jn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Jn.Q_720P,trafficSavingLimit:Jn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Jn.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:!1,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,disableYandexPiP:!1},QT=a=>{var e;return R(E({},k0(a,jT)),{configName:[...(e=a.configName)!=null?e:[],...jT.configName]})};import{assertNonNullable as Zn,combine as Et,ErrorCategory as eo,filter as Ie,filterChanged as W,fromEvent as kc,isNonNullable as V0,isNullable as O0,Logger as B0,map as j,mapTo as zT,merge as Yt,now as to,once as dt,Subject as Y,Subscription as KT,tap as XT,ValueSubject as A,isHigher as _0,isInvariantQuality as JT,flattenObject as zt,throttle as Lc,getTraceSubscriptionMethod as ZT,Tracer as N0,InternalsExposure as F0}from"@vkontakte/videoplayer-shared/es2015";import{merge as L0,map as R0,filter as GT,isNonNullable as $0}from"@vkontakte/videoplayer-shared/es2015";var Ac=({seekState:a,position$:e})=>L0(a.stateChangeEnded$.pipe(R0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),GT($0)),e.pipe(GT(()=>a.getState().state==="none")));import{assertNonNullable as M0}from"@vkontakte/videoplayer-shared/es2015";var WT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return M0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as D0,once as C0}from"@vkontakte/videoplayer-shared/es2015";var YT=(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(D0(i=>i.length>0),C0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var ro=class{constructor(e={configName:[]},t=N0.createRootTracer(!1)){this.subscription=new KT;this.logger=new B0;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 V("stopped"),seekState:new V({state:"none"}),volume:new V({volume:1,muted:!1}),videoTrack:new V(void 0),videoStream:new V(void 0),audioStream:new V(void 0),autoVideoTrackSwitching:new V(!0),autoVideoTrackLimits:new V({}),isLooped:new V(!1),isLowLatency:new V(!1),playbackRate:new V(1),externalTextTracks:new V([]),internalTextTracks:new V([]),currentTextTrack:new V(void 0),textTrackCuesSettings:new V({}),cameraOrientation:new V({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({}),predefinedQualityLimitType$:new A("unknown"),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 Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,fetcherRecoverableError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,autoplaySoundProhibited$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y,fetcherError$:new Y,severeStallOccured$:new Y};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:jg,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=QT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new As({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new HT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new F0("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,eI.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:eo.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=pd(i,["container"]);return this.tracer.log("initVideo",zt(r)),this.domContainer=WT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new as({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&&!ta()?(this.tracer.log("request play from hidden tab"),kc(document,"visibilitychange").pipe(dt()).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}),Number.isFinite(s)&&(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,t){let r=this.desiredState.volume,i=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||i;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:s}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:s}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e,r=this.info.volume$.getValue();return this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:r,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:r,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Zn(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(Ie(r=>r.length>0),dt()).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}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.setAutoQualityLimits(i),this}setPlaybackRate(e){var r;Zn(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=>E({type:"external"},t))),this}selectTextTrack(e){var t;return YT(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",E({},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(O0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return V0(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(j(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(hl({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Ie(({from:e})=>e==="stopped"),dt()).subscribe(()=>{this.initedAt=to(),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(R(E({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:eo.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(dt()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).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(j(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(j(n=>n.destination),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Et({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(j(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>JT(u)?1:JT(l)?-1:_0(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(j(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(Et({hasLiveOffsetByPaused:Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(n=>n.to),W(),j(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(Et({atLiveEdge:Et({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ac({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(j(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),W(),XT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(j(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Et({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(j(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),W(),XT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(j(n=>n.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(j(n=>n.volume),W()).subscribe(this.info.volume$)).add(Ac({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Yt(e.providerOutput.endedEvent$.pipe(zT(!0)),e.providerOutput.seekedEvent$.pipe(zT(!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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(j(n=>({id:n?`No${n}`:"NoProviders",category:eo.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(dt(),j(n=>n!=null?n:to()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(dt(),j(()=>to()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(dt(),j(()=>to()-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(Ie(({to:n})=>n==="playing"),dt()).subscribe(()=>r.next(!1)));let i=0,s=Yt(e.providerOutput.isBuffering$,t,r).pipe(j(()=>{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(j(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 KT;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(Ie(r=>r.length>0),dt()).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=Ut(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(j(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(j(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;Zn(this.providerContainer),Zn(e),Hg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Ug(r)),this.providerContainer.current$.subscribe(({type:r})=>Yi("provider",r)),e.duration$.subscribe(r=>Yi("duration",r)),e.availableVideoTracks$.pipe(Ie(r=>!!r.length),dt()).subscribe(r=>Yi("tracks",r)),this.events.fatalError$.subscribe(new Se("fatalError")),this.events.managedError$.subscribe(new Se("managedError")),e.position$.subscribe(new Se("position")),e.currentVideoTrack$.pipe(j(r=>r==null?void 0:r.quality)).subscribe(new Se("quality")),this.info.currentBuffer$.subscribe(new Se("buffer")),e.isBuffering$.subscribe(new Se("isBuffering"))].forEach(r=>this.subscription.add(r)),Yi("codecs",tS())}initTracerSubscription(){let e=ZT(this.tracer.log.bind(this.tracer)),t=ZT(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(Et({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Ie(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),W((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Ie(r=>r>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Ie(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(Et({currentBuffer:this.info.currentBuffer$.pipe(Ie(r=>r.end>0),W((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(W())}).pipe(Lc(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(Et({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Ie(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Lc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),Ie(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),Ie(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(),Ie(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Et({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Ie(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Lc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),Ie(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=()=>P(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:eo.DOM,message:String(i)})})});this.subscription.add(Yt(kc(document,"visibilitychange"),kc(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 b8,Observable as g8,Subject as v8,ValueSubject as S8,VideoQuality as y8}from"@vkontakte/videoplayer-shared/es2015";var T8=`@vkontakte/videoplayer-core@${hd}`;export{ys as ChromecastState,co as HttpConnectionType,g8 as Observable,Ee as PlaybackState,ro as Player,Ts as PredefinedQualityLimits,T8 as SDK_VERSION,v8 as Subject,b8 as Subscription,po as Surface,hd as VERSION,S8 as ValueSubject,Mt as VideoFormat,y8 as VideoQuality};
124
+ `;var Mn=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 Rn(this.params.fov,this.params.orientation),this.cameraRotationManager=new $n(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(Dy,this.gl.VERTEX_SHADER),r=this.createShader(Vy,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 CC,now as _y,Subscription as DC,filter as VC,combine as Oy,ValueSubject as tc,isNonNullable as _C}from"@vkontakte/videoplayer-shared/es2015";var rc=class{constructor(){this.isSeeked$=new tc(!1);this.isBuffering$=new tc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new DC;this.severeStallOccurred$=new tc(!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(Oy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(VC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Oy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(CC(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=_y(),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,_C(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=_y(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},By=rc;import{combine as OC,map as BC,observeElementSize as NC,Subscription as FC,ValueSubject as ic,noop as qC}from"@vkontakte/videoplayer-shared/es2015";var Cn=class{constructor(){this.subscription=new FC;this.pipSize$=new ic(void 0);this.videoSize$=new ic(void 0);this.elementSize$=new ic(void 0);this.pictureInPictureWindowRemoveEventListener=qC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(NC(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(OC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(BC(({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 Tr=class{constructor(e){this.subscription=new YC;this.videoState=new O("stopped");this.droppedFramesManager=new hn;this.stallsManager=new By;this.elementSizeManager=new Cn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Gi;this.audioTrackSwitchHistory=new Gi;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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&w(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"&&w(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"&&w(this.params.desiredState.playbackState,"paused");return;default:return jC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Mn(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 Ue(e.source.url),this.params=e,this.video=we(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(ce(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 Ln({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=Le(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Ny.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(Fy(l=>!!l.length),Uy()).subscribe(l=>{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:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ac(l=>l.to.state!=="none"),Fa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Fa()),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.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Fy(qy),Uy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ac(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(QC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Nl(h));let m=[];for(let b of h.representations){let g=oy(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Fl(p));let h=[];for(let m of p.representations){let b=ny($(P({},m),{streamId:p.id}));b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=uy(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add(Dn(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$,WC(this.video,"progress")).subscribe(()=>x(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Hy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===p.id});qy(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,g)}}),i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Fa()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Fl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Fa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(Nl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},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 o=t.playbackState.stateChangeStarted$.pipe(ac(({to:l})=>l==="ready"),Fa());this.subscription.add(Dn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,sc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Dn(o,this.player.state$.stateChangeEnded$,sc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Dn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,sc(["init"])).pipe(GC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var M,re,C,j,Q,R,G,q,J,k,T,V,Y;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(M=e.videoTrack.getState())==null?void 0:M.id,n=[...this.videoTracksMap.keys()].find(({id:U})=>U===i),o=t.currentVideoTrack$.getValue(),u=((j=(C=e.videoStream.getState())!=null?C:n&&((re=this.videoTracksMap.get(n))==null?void 0:re.stream))!=null?j:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:U})=>U===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ut(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),b=(Q=e.audioStream.getState())!=null?Q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(R=[...this.audioStreamsMap.keys()].find(({id:U})=>U===(b==null?void 0:b.id)))!=null?R:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let U=ln(n,c,(G=this.audioStreamsMap.get(g))!=null?G:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(q=U==null?void 0:U.bitrate)!=null?q:-1/0)}if(o){let U=ln(o,c,(J=this.audioStreamsMap.get(g))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=U==null?void 0:U.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:m,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}),y=r?S!=null?S:n:n!=null?n:S,E=g&&rv(y,c,(T=this.audioStreamsMap.get(g))!=null?T:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(V=this.videoTracksMap.get(y))==null?void 0:V.representation,L=E&&((Y=this.audioTracksMap.get(E))==null?void 0:Y.representation);if(I&&L)return[I,L];if(I&&!L&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ny.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),this.params.output.currentVideoStream$.next(void 0),Ae(this.video),this.tracer.end()}};var qa=class extends Tr{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 jy,interval as zC,map as Qy}from"@vkontakte/videoplayer-shared/es2015";var Ua=class extends Tr{constructor(e){super(e),this.liveOffset=new bt,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(Qy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(jy({interval:zC(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(jy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Qy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=ly(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 Wy=_(zs(),1);import{assertNever as Ha,assertNonNullable as Gy,debounce as KC,ErrorCategory as Vn,filter as XC,isNonNullable as JC,isNullable as ZC,map as _n,merge as eD,Observable as tD,observableFrom as rD,Subscription as iD,videoSizeToQuality as aD}from"@vkontakte/videoplayer-shared/es2015";var et={};var oi=(a,e)=>new tD(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),ja=class{constructor(e){this.subscription=new iD;this.videoState=new O("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:Ha(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ha(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ha(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ha(e)}break;default:Ha(t)}};this.textTracksManager=new Ue(e.source.url),this.video=we(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(ce(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),Ae(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Vn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Wy.default)(import("hls.js").then(i=>{e||(et.Hls=i.default,et.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Gy(et.Hls,"hls.js not loaded"),this.hls=new et.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Gy(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Vn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Le(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(nt(this.video,e.isLooped,r)),this.subscription.add(ke(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,i.playbackRateState$,r)),s(je(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(_n(l=>l.to)),this.params.output.playbackState$),this.subscription.add(oi(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Vn.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"),w(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(oi(this.hls,et.Events.MANIFEST_PARSED).pipe(_n(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(y=Ot((S=d.attrs.QUALITY)!=null?S:""))!=null?y:aD({width:h,height:m});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:m},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(oi(this.hls,et.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||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(oi(this.hls,et.Events.LEVEL_LOADING).pipe(_n(({url:l})=>ce(l))),t.hostname$),s(oi(this.hls,et.Events.FRAG_CHANGED),l=>{var p,h,m,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((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Dt(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=oi(this.hls,et.Events.LEVEL_SWITCHED).pipe(_n(({level:l})=>n(this.hls.levels[l])));o.pipe(XC(JC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Dt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(ZC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.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=eD(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,rD(["init"])).pipe(KC(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 x(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vn.DOM,thrown:t})))||(this.videoState.setState("paused"),w(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"),w(this.params.desiredState.playbackState,"stopped",!0)}};var Yy="X-Playback-Duration",nc=a=>x(void 0,null,function*(){var i;let e=yield lt(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(Yy)?parseInt(e.headers.get(Yy),10):void 0});import{assertNever as fD,combine as bD,debounce as gD,ErrorCategory as Nn,filter as vD,filterChanged as SD,isNonNullable as Xy,isNullable as Fn,map as Jy,merge as yD,observableFrom as TD,Subscription as ID,ValueSubject as lc,VideoQuality as ED}from"@vkontakte/videoplayer-shared/es2015";var uc=_(du(),1);import{videoSizeToQuality as sD,getExponentialDelay as nD}from"@vkontakte/videoplayer-shared/es2015";var oD=a=>{let e=null;if(a.QUALITY&&(e=Ot(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=sD({width:t,height:r})}return e!=null?e:null},uD=(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,uc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=oD(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=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,y]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,uc.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,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},lD=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),oc=0,zy=(i,...s)=>x(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield lt(a,r)).text();oc+=1;try{let{qualityManifests:u,textTracks:l}=uD(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(oc<=t.manifestRetryMaxCount)return yield lD(nD(oc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),zy(a,e,t)}return{qualityManifests:[],textTracks:[]}}),On=zy;import{isNonNullable as cD,Subscription as dD,throttle as pD,ValueSubject as Ky,Subject as hD,ErrorCategory as mD}from"@vkontakte/videoplayer-shared/es2015";var Bn=class{constructor(e,t,r,i,s){this.subscription=new dD;this.abortControllers={destroy:new ge,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Ky(null);this.getCurrentTime$=new Ky(null);this.error$=new hD;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(pD(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 x(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 x(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 x(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield lt(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(cD(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([$(P({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return x(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ge;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 x(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:mD.WTF,thrown:t,message:e})}};var Qa=class{constructor(e){this.subscription=new ID;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new lc([]);this.liveOffset=new bt;this.manifestStartTime$=new lc(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"),w(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"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(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"&&w(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"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return fD(t)}};var r;this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ED.INVARIANT,url:this.params.source.url};let t=(i,s)=>On(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 Bn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ue(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:Nn.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:Nn.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(ce(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new lc((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:Nn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Le(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(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(je(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"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(SD(),Jy(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&&Xy(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(ce(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(bD({startTime:this.manifestStartTime$.pipe(vD(Xy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Jy(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=yD(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,TD(["init"])).pipe(gD(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),Ae(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Fn(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 m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=be(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),nc(n).then(c=>{var d;if(!Fn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Fn(p)||!isFinite(p))&&lt(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();nc(g).then(v=>{Fn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nn.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=be(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 xD,debounce as PD,ErrorCategory as cc,fromEvent as dc,isNonNullable as wD,isNullable as AD,map as Zy,merge as eT,observableFrom as tT,Subscription as kD,ValueSubject as LD,VideoQuality as RD}from"@vkontakte/videoplayer-shared/es2015";var Ga=class{constructor(e){this.subscription=new kD;this.videoState=new O("stopped");this.manifests$=new LD([]);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"),w(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"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return xD(t)}};this.textTracksManager=new Ue(e.source.url),this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:RD.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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),On(be(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:cc.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||!i.from)&&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:cc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Le(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(Zy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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&&wD(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(ce(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 m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.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(Zy(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)),!N.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(eT(dc(o,"addtrack"),dc(o,"removetrack"),dc(o,"change"),tT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=eT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,tT(["init"])).pipe(PD(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ae(this.video)}prepare(){var s,n;let e=this.selectManifest();if(AD(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(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var aT=_(Fr(),1),pc=_(Xr(),1),sT=_(Bt(),1);import{assertNever as $D,assertNonNullable as rT,debounce as MD,ErrorCategory as iT,isHigherOrEqual as CD,isLowerOrEqual as DD,isNonNullable as VD,merge as _D,observableFrom as OD,Subscription as BD,map as ND}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new BD;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Ue;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(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);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return $D(e)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),(0,aT.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,pc.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:iT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Le(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(ND(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(je(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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&&VD(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=_D(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,OD(["init"])).pipe(MD(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),Ae(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;rT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];rT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ma(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ce(t))}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:iT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Ft(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,pc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Qi({limits:e,lowestAvailableQuality:(c=(0,sT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?DD(i,e.max):!0,u=e.min?CD(i,e.min):!0;o&&u||r(e)}};import{assertNever as oT,debounce as HD,merge as uT,observableFrom as jD,Subscription as QD,map as lT,ValueSubject as GD,ErrorCategory as mc,VideoQuality as WD}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as FD}from"@vkontakte/videoplayer-shared/es2015";var nT=["stun:videostun.mycdn.me:80"],qD=1e3,UD=3,hc=()=>null,qn=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=hc;this.externalStopCallback=hc;this.externalErrorCallback=hc;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 x(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 x(this,null,function*(){try{let e={iceServers:[{urls:nT}]};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 x(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return x(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:FD.WTF,message:e.message})}onPeerConnectionStream(e){return x(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 x(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),qD)}normalizeOptions(e={}){let t={stunServerList:nT,maxRetryNumber:UD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ya=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new GD(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"),w(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"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return oT(e)}};this.subscription=new QD,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=we(e.container,e.tuning),this.liveStreamClient=new qn(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),Ae(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})};uT(this.videoState.stateChangeStarted$.pipe(lT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(lT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Le(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(je(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(ke(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 oT(n.to)}},r)).add(uT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,jD(["init"])).pipe(HD(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(ce(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:WD.INVARIANT}),this.video.srcObject=e,w(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(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(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 za=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 Xa,assertNonNullable as Qt,ErrorCategory as Un,filter as fT,isNonNullable as bT,isNullable as e0,map as t0,merge as r0,once as i0,Subject as pe,Subscription as gT,ValueSubject as B,flattenObject as vT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as YD,map as cT,Subscription as zD,Subject as KD}from"@vkontakte/videoplayer-shared/es2015";var dT=a=>new YD(e=>{let t=new zD,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(cT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(cT(({type:l})=>l!==void 0)),n=new KD,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 XD,Subscription as JD,combine as ZD,filter as hT,once as mT}from"@vkontakte/videoplayer-shared/es2015";function pT(){return new(window.AudioContext||window.webkitAudioContext)}var Ka=class Ka{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ge;this.subscriptions=new JD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(hT(s=>!!s.type),mT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){N.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(ZD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(hT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),mT()).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 x(this,null,function*(){let{volumeMultiplier:t}=this,r=pT();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:Ka.errorId,category:XD.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ka.errorId} exception`,thrown:e})}};Ka.errorId="VolumeMultiplierManager";var ui=Ka;var a0={chunkDuration:5e3,maxParallelRequests:5},Ja=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new pe;this.noAvailableProvidersError$=new pe;this.volumeMultiplierError$=new pe;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new pe,fetcherError$:new pe,fetcherRecoverableError$:new pe,warning$:new pe,willSeekEvent$:new pe,soundProhibitedEvent$:new pe,seekedEvent$:new pe,loopedEvent$:new pe,endedEvent$:new pe,firstBytesEvent$:new pe,loadedMetadataEvent$:new pe,firstFrameEvent$:new pe,canplay$:new pe,isLive$:new B(void 0),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),severeStallOccurred$:new pe,availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B(""),getCurrentTime$:new B(null)};this.subscription=new gT;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=wy([...ky(this.params.tuning),...Ay(this.params.tuning)],this.params.tuning).filter(l=>bT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,fc.default)(i,l)),...t.filter(l=>(0,fc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",vT(s)),this.screenFormatsIterator=new za(s);let n=[...Kl(!0),...Kl(!1)];this.chromecastFormatsIterator=new za(n.filter(l=>bT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ui.isSupported()&&(this.volumeMultiplierManager=new ui(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(e0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Un.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 Xa(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 Qt(o),new qa($(P({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ua($(P({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Qt(o),N.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Ga($(P({},n),{source:o})):new ja($(P({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Qa($(P({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Wa($(P({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Sv($(P({},n),{source:o,config:$(P({},a0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ya({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 Xa(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 Qt(o),new Fi({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 Xa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Xa(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 Xa(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 $(P({},e),{url:r(e.url)})}return(0,yT.default)((0,ST.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new gT,t=!1,r=0;return e.add(r0(this.providerOutput.error$.pipe(fT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),dT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(t0(i=>({id:`ProviderHangup:${i}`,category:Un.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(fT(({to:s})=>s==="playing"),i0()).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===Un.NETWORK,u=i.category===Un.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=$(P({},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",vT(n))})),e}};import{fromEvent as Hn,once as s0,combine as n0,Subscription as TT,ValueSubject as bc,map as o0,filter as u0,isNonNullable as jn,now as Be,safeStorage as gc}from"@vkontakte/videoplayer-shared/es2015";var l0=5e3,IT="one_video_throughput",ET="one_video_rtt",Tt=window.navigator.connection,xT=()=>{let a=Tt==null?void 0:Tt.downlink;if(jn(a)&&a!==10)return a*1e3},PT=()=>{let a=Tt==null?void 0:Tt.rtt;if(jn(a)&&a!==3e3)return a},wT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},vc=class a{constructor(e){this.subscription=new TT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(IT)||(e.useBrowserEstimation?xT():void 0)||l0,r=(s=(i=a.load(ET))!=null?i:e.useBrowserEstimation?PT():void 0)!=null?s:0;if(this.throughput$=new bc(t),this.rtt$=new bc(r),this.rttAdjustedThroughput$=new bc(wT(t,r,e.rttPenaltyRequestSize)),this.throughput=br.getSmoothedValue(t,-1,e),this.rtt=br.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=xT();u&&this.throughput.next(u);let l=PT();jn(l)&&this.rtt.next(l)};Tt&&"onchange"in Tt&&this.subscription.add(Hn(Tt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{gc.set(IT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{gc.set(ET,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(n0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(o0(({throughput:n,rtt:o})=>wT(n,o,e.rttPenaltyRequestSize)),u0(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=Be(),i=new TT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Hn(e,"progress").pipe(s0()).subscribe(s=>{t=s.loaded,r=Be()}));break;case 1:case 0:i.add(Hn(e,"loadstart").subscribe(()=>{t=0,r=Be()}));break}i.add(Hn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Be(),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=Be(),n=0,o=Be(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>x(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Be()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Be();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=Be()}else n+=d.byteLength;o=Be()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Be()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Be()-o,this.concurrentDownloads.size),n=0,o=Be());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=gc.get(e);if(jn(t))return(r=parseInt(t,10))!=null?r:void 0}},AT=vc;import{fillWithDefault as c0,VideoQuality as Qn}from"@vkontakte/videoplayer-shared/es2015";var kT={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:Qn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Qn.Q_720P,trafficSavingLimit:Qn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Qn.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:!1,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,disableYandexPiP:!1,asyncResolveClientChecker:!1},LT=a=>{var e;return $(P({},c0(a,kT)),{configName:[...(e=a.configName)!=null?e:[],...kT.configName]})};import{assertNonNullable as Gn,combine as It,ErrorCategory as Wn,filter as D,filterChanged as K,fromEvent as yc,isNonNullable as g0,isNullable as v0,Logger as S0,map as W,mapTo as CT,merge as Gt,now as Yn,once as F,Subject as X,Subscription as DT,tap as VT,ValueSubject as A,isHigher as y0,isInvariantQuality as _T,flattenObject as Wt,throttle as Tc,getTraceSubscriptionMethod as OT,Tracer as T0,InternalsExposure as I0}from"@vkontakte/videoplayer-shared/es2015";import{merge as d0,map as p0,filter as RT,isNonNullable as h0}from"@vkontakte/videoplayer-shared/es2015";var Sc=({seekState:a,position$:e})=>d0(a.stateChangeEnded$.pipe(p0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),RT(h0)),e.pipe(RT(()=>a.getState().state==="none")));import{assertNonNullable as m0}from"@vkontakte/videoplayer-shared/es2015";var $T=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return m0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as f0,once as b0}from"@vkontakte/videoplayer-shared/es2015";var MT=(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(f0(i=>i.length>0),b0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var zn=class{constructor(e={configName:[]},t=T0.createRootTracer(!1)){this.subscription=new DT;this.logger=new S0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInited=new A(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({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({}),predefinedQualityLimitType$:new A("unknown"),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,fetcherRecoverableError$: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,fetcherError$:new X,severeStallOccured$:new X};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Hg,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=LT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ts({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new AT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new I0("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,m)=>{let b=typeof m;return(0,BT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Wn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i;this.config=e,(i=this.internalsExposure)==null||i.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,c;let o=e,{container:s}=o,n=ad(o,["container"]);this.tracer.log("initVideo",Wt(n)),this.domContainer=$T(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ja({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],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(),this.playerInited.next(!0)},r=()=>{this.tuning.asyncResolveClientChecker?N.isInited$.pipe(D(s=>!!s),F()).subscribe(()=>{console.log("Core SDK async start"),t()}):t()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),yc(document,"visibilitychange").pipe(F()).subscribe(r)):r(),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(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.playerInited.pipe(D(r=>!!r),F()).subscribe(()=>{let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.playerInited.pipe(D(r=>!!r),F()).subscribe(()=>{let r=this.desiredState.volume,i=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||i;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:s}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:s})}),this}setMuted(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{let t=this.tuning.isAudioDisabled||e,r=this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:r,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:r,muted:t})}),this}setVideoStream(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{Gn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();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(D(r=>r.length>0),F()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}this.setAutoQualityLimits(i)}),this}setPlaybackRate(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{var r;Gn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)}),this}setExternalTextTracks(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>P({type:"external"},t)))}),this}selectTextTrack(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{var t;MT(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.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",P({},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.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.playerInited.pipe(D(r=>!!r),F()).subscribe(()=>{let r=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.playerInited.pipe(D(r=>!!r),F()).subscribe(()=>{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})}}),this}holdCamera(){return this.playerInited.pipe(D(e=>e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(v0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return g0(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(Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ol({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(D(({from:e})=>e==="stopped"),F()).subscribe(()=>{this.initedAt=Yn(),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",Wt(n)),n.state==="requested"?this.desiredState.seekState.setState($(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Wn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(F()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Wt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(W(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(W(n=>n.destination),K()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(It({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(W(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>_T(u)?1:_T(l)?-1:y0(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(K()).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(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(K()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(K()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(K()).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(W(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(It({hasLiveOffsetByPaused:Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(n=>n.to),K(),W(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(It({atLiveEdge:It({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(W(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),K(),VT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(W(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(It({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(W(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),K(),VT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(W(n=>n.muted),K()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(W(n=>n.volume),K()).subscribe(this.info.volume$)).add(Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Gt(e.providerOutput.endedEvent$.pipe(CT(!0)),e.providerOutput.seekedEvent$.pipe(CT(!1))).pipe(K()).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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(W(n=>({id:n?`No${n}`:"NoProviders",category:Wn.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(F(),W(n=>n!=null?n:Yn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(F(),W(()=>Yn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(F(),W(()=>Yn()-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(D(({to:n})=>n==="playing"),F()).subscribe(()=>r.next(!1)));let i=0,s=Gt(e.providerOutput.isBuffering$,t,r).pipe(W(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),K());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(Gt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Gt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(W(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 DT;this.subscription.add(t),this.subscription.add(e.current$.pipe(K((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(D(r=>r.length>0),F()).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(Gt(this.desiredState.videoTrack.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(W(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;Gn(this.providerContainer),Gn(e),Ug(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>qg(r)),this.providerContainer.current$.subscribe(({type:r})=>ji("provider",r)),e.duration$.subscribe(r=>ji("duration",r)),e.availableVideoTracks$.pipe(D(r=>!!r.length),F()).subscribe(r=>ji("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(W(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),ji("codecs",N.video.supportedCodecs)}initTracerSubscription(){let e=OT(this.tracer.log.bind(this.tracer)),t=OT(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(K()).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(It({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(D(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),K((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(D(r=>r>0),K()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(D(r=>r>0),K()).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(It({currentBuffer:this.info.currentBuffer$.pipe(D(r=>r.end>0),K((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(K())}).pipe(Tc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(K()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(K()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(K()).subscribe(e("canChangePlaybackSpeed"))).add(It({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(D(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Tc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(K(),D(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(K(),D(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(K()).subscribe(e("muted"))).add(this.info.volume$.pipe(K()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(K(),D(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(It({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(D(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Tc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(K(),D(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=()=>x(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:Wn.DOM,message:String(i)})})});this.subscription.add(Gt(yc(document,"visibilitychange"),yc(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",Wt({quality:t,availableTracks:Wt(e),track:Wt(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}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Xi()}};import{Subscription as F8,Observable as q8,Subject as U8,ValueSubject as H8,VideoQuality as j8}from"@vkontakte/videoplayer-shared/es2015";var Q8=`@vkontakte/videoplayer-core@${sd}`;export{ms as ChromecastState,io as HttpConnectionType,q8 as Observable,Pe as PlaybackState,zn as Player,fs as PredefinedQualityLimits,Q8 as SDK_VERSION,U8 as Subject,F8 as Subscription,ao as Surface,sd as VERSION,H8 as ValueSubject,pt as VideoFormat,j8 as VideoQuality,N as clientChecker,Hi as isMobile};