@vkontakte/videoplayer-core 2.0.130-dev.afe0f37e.0 → 2.0.130-dev.ca914dc0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2018.esm.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.130-dev.afe0f37e.0
3
- * Mon, 07 Apr 2025 10:04:46 GMT
2
+ * @vkontakte/videoplayer-core v2.0.130-dev.ca914dc0.0
3
+ * Tue, 08 Apr 2025 14:25:05 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-130/doc/
5
5
  */
6
- var jT=Object.create;var nd=Object.defineProperty;var QT=Object.getOwnPropertyDescriptor;var GT=Object.getOwnPropertyNames;var WT=Object.getPrototypeOf,YT=Object.prototype.hasOwnProperty;var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var zT=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of GT(e))!YT.call(a,r)&&r!==t&&nd(a,r,{get:()=>e[r],enumerable:!(i=QT(e,r))||i.enumerable});return a};var D=(a,e,t)=>(t=a!=null?jT(WT(a)):{},zT(e||!a||!a.__esModule?nd(t,"default",{value:a,enumerable:!0}):t,a));var re=f((Jn,ud)=>{"use strict";var pr=function(a){return a&&a.Math===Math&&a};ud.exports=pr(typeof globalThis=="object"&&globalThis)||pr(typeof window=="object"&&window)||pr(typeof self=="object"&&self)||pr(typeof global=="object"&&global)||pr(typeof Jn=="object"&&Jn)||function(){return this}()||Function("return this")()});var de=f((P0,ld)=>{"use strict";ld.exports=function(a){try{return!!a()}catch(e){return!0}}});var hr=f((w0,cd)=>{"use strict";var KT=de();cd.exports=!KT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Zn=f((A0,md)=>{"use strict";var XT=hr(),hd=Function.prototype,dd=hd.apply,pd=hd.call;md.exports=typeof Reflect=="object"&&Reflect.apply||(XT?pd.bind(dd):function(){return pd.apply(dd,arguments)})});var ne=f((k0,gd)=>{"use strict";var fd=hr(),bd=Function.prototype,eo=bd.call,JT=fd&&bd.bind.bind(eo,eo);gd.exports=fd?JT:function(a){return function(){return eo.apply(a,arguments)}}});var Xt=f((R0,Sd)=>{"use strict";var vd=ne(),ZT=vd({}.toString),eI=vd("".slice);Sd.exports=function(a){return eI(ZT(a),8,-1)}});var to=f((L0,yd)=>{"use strict";var tI=Xt(),iI=ne();yd.exports=function(a){if(tI(a)==="Function")return iI(a)}});var ee=f(($0,Td)=>{"use strict";var io=typeof document=="object"&&document.all;Td.exports=typeof io=="undefined"&&io!==void 0?function(a){return typeof a=="function"||a===io}:function(a){return typeof a=="function"}});var $e=f((M0,Id)=>{"use strict";var rI=de();Id.exports=!rI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Me=f((D0,Ed)=>{"use strict";var aI=hr(),cs=Function.prototype.call;Ed.exports=aI?cs.bind(cs):function(){return cs.apply(cs,arguments)}});var ro=f(wd=>{"use strict";var xd={}.propertyIsEnumerable,Pd=Object.getOwnPropertyDescriptor,sI=Pd&&!xd.call({1:2},1);wd.f=sI?function(e){var t=Pd(this,e);return!!t&&t.enumerable}:xd});var mr=f((V0,Ad)=>{"use strict";Ad.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Rd=f((O0,kd)=>{"use strict";var nI=ne(),oI=de(),uI=Xt(),ao=Object,lI=nI("".split);kd.exports=oI(function(){return!ao("z").propertyIsEnumerable(0)})?function(a){return uI(a)==="String"?lI(a,""):ao(a)}:ao});var xi=f((B0,Ld)=>{"use strict";Ld.exports=function(a){return a==null}});var At=f((_0,$d)=>{"use strict";var cI=xi(),dI=TypeError;$d.exports=function(a){if(cI(a))throw new dI("Can't call method on "+a);return a}});var Jt=f((N0,Md)=>{"use strict";var pI=Rd(),hI=At();Md.exports=function(a){return pI(hI(a))}});var De=f((F0,Dd)=>{"use strict";var mI=ee();Dd.exports=function(a){return typeof a=="object"?a!==null:mI(a)}});var Pi=f((q0,Cd)=>{"use strict";Cd.exports={}});var ct=f((U0,Od)=>{"use strict";var so=Pi(),no=re(),fI=ee(),Vd=function(a){return fI(a)?a:void 0};Od.exports=function(a,e){return arguments.length<2?Vd(so[a])||Vd(no[a]):so[a]&&so[a][e]||no[a]&&no[a][e]}});var fr=f((H0,Bd)=>{"use strict";var bI=ne();Bd.exports=bI({}.isPrototypeOf)});var Zt=f((j0,Fd)=>{"use strict";var gI=re(),_d=gI.navigator,Nd=_d&&_d.userAgent;Fd.exports=Nd?String(Nd):""});var uo=f((Q0,Gd)=>{"use strict";var Qd=re(),oo=Zt(),qd=Qd.process,Ud=Qd.Deno,Hd=qd&&qd.versions||Ud&&Ud.version,jd=Hd&&Hd.v8,je,ds;jd&&(je=jd.split("."),ds=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!ds&&oo&&(je=oo.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=oo.match(/Chrome\/(\d+)/),je&&(ds=+je[1])));Gd.exports=ds});var lo=f((G0,Yd)=>{"use strict";var Wd=uo(),vI=de(),SI=re(),yI=SI.String;Yd.exports=!!Object.getOwnPropertySymbols&&!vI(function(){var a=Symbol("symbol detection");return!yI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Wd&&Wd<41})});var co=f((W0,zd)=>{"use strict";var TI=lo();zd.exports=TI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var po=f((Y0,Kd)=>{"use strict";var II=ct(),EI=ee(),xI=fr(),PI=co(),wI=Object;Kd.exports=PI?function(a){return typeof a=="symbol"}:function(a){var e=II("Symbol");return EI(e)&&xI(e.prototype,wI(a))}});var br=f((z0,Xd)=>{"use strict";var AI=String;Xd.exports=function(a){try{return AI(a)}catch(e){return"Object"}}});var et=f((K0,Jd)=>{"use strict";var kI=ee(),RI=br(),LI=TypeError;Jd.exports=function(a){if(kI(a))return a;throw new LI(RI(a)+" is not a function")}});var gr=f((X0,Zd)=>{"use strict";var $I=et(),MI=xi();Zd.exports=function(a,e){var t=a[e];return MI(t)?void 0:$I(t)}});var tp=f((J0,ep)=>{"use strict";var ho=Me(),mo=ee(),fo=De(),DI=TypeError;ep.exports=function(a,e){var t,i;if(e==="string"&&mo(t=a.toString)&&!fo(i=ho(t,a))||mo(t=a.valueOf)&&!fo(i=ho(t,a))||e!=="string"&&mo(t=a.toString)&&!fo(i=ho(t,a)))return i;throw new DI("Can't convert object to primitive value")}});var Qe=f((Z0,ip)=>{"use strict";ip.exports=!0});var sp=f((eV,ap)=>{"use strict";var rp=re(),CI=Object.defineProperty;ap.exports=function(a,e){try{CI(rp,a,{value:e,configurable:!0,writable:!0})}catch(t){rp[a]=e}return e}});var vr=f((tV,up)=>{"use strict";var VI=Qe(),OI=re(),BI=sp(),np="__core-js_shared__",op=up.exports=OI[np]||BI(np,{});(op.versions||(op.versions=[])).push({version:"3.38.0",mode:VI?"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 bo=f((iV,cp)=>{"use strict";var lp=vr();cp.exports=function(a,e){return lp[a]||(lp[a]=e||{})}});var wi=f((rV,dp)=>{"use strict";var _I=At(),NI=Object;dp.exports=function(a){return NI(_I(a))}});var Ge=f((aV,pp)=>{"use strict";var FI=ne(),qI=wi(),UI=FI({}.hasOwnProperty);pp.exports=Object.hasOwn||function(e,t){return UI(qI(e),t)}});var go=f((sV,hp)=>{"use strict";var HI=ne(),jI=0,QI=Math.random(),GI=HI(1 .toString);hp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+GI(++jI+QI,36)}});var pe=f((nV,fp)=>{"use strict";var WI=re(),YI=bo(),mp=Ge(),zI=go(),KI=lo(),XI=co(),Ai=WI.Symbol,vo=YI("wks"),JI=XI?Ai.for||Ai:Ai&&Ai.withoutSetter||zI;fp.exports=function(a){return mp(vo,a)||(vo[a]=KI&&mp(Ai,a)?Ai[a]:JI("Symbol."+a)),vo[a]}});var Sp=f((oV,vp)=>{"use strict";var ZI=Me(),bp=De(),gp=po(),eE=gr(),tE=tp(),iE=pe(),rE=TypeError,aE=iE("toPrimitive");vp.exports=function(a,e){if(!bp(a)||gp(a))return a;var t=eE(a,aE),i;if(t){if(e===void 0&&(e="default"),i=ZI(t,a,e),!bp(i)||gp(i))return i;throw new rE("Can't convert object to primitive value")}return e===void 0&&(e="number"),tE(a,e)}});var So=f((uV,yp)=>{"use strict";var sE=Sp(),nE=po();yp.exports=function(a){var e=sE(a,"string");return nE(e)?e:e+""}});var ps=f((lV,Ip)=>{"use strict";var oE=re(),Tp=De(),yo=oE.document,uE=Tp(yo)&&Tp(yo.createElement);Ip.exports=function(a){return uE?yo.createElement(a):{}}});var To=f((cV,Ep)=>{"use strict";var lE=$e(),cE=de(),dE=ps();Ep.exports=!lE&&!cE(function(){return Object.defineProperty(dE("div"),"a",{get:function(){return 7}}).a!==7})});var wp=f(Pp=>{"use strict";var pE=$e(),hE=Me(),mE=ro(),fE=mr(),bE=Jt(),gE=So(),vE=Ge(),SE=To(),xp=Object.getOwnPropertyDescriptor;Pp.f=pE?xp:function(e,t){if(e=bE(e),t=gE(t),SE)try{return xp(e,t)}catch(i){}if(vE(e,t))return fE(!hE(mE.f,e,t),e[t])}});var Io=f((pV,Ap)=>{"use strict";var yE=de(),TE=ee(),IE=/#|\.prototype\./,Sr=function(a,e){var t=xE[EE(a)];return t===wE?!0:t===PE?!1:TE(e)?yE(e):!!e},EE=Sr.normalize=function(a){return String(a).replace(IE,".").toLowerCase()},xE=Sr.data={},PE=Sr.NATIVE="N",wE=Sr.POLYFILL="P";Ap.exports=Sr});var ki=f((hV,Rp)=>{"use strict";var kp=to(),AE=et(),kE=hr(),RE=kp(kp.bind);Rp.exports=function(a,e){return AE(a),e===void 0?a:kE?RE(a,e):function(){return a.apply(e,arguments)}}});var Eo=f((mV,Lp)=>{"use strict";var LE=$e(),$E=de();Lp.exports=LE&&$E(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var tt=f((fV,$p)=>{"use strict";var ME=De(),DE=String,CE=TypeError;$p.exports=function(a){if(ME(a))return a;throw new CE(DE(a)+" is not an object")}});var ei=f(Dp=>{"use strict";var VE=$e(),OE=To(),BE=Eo(),hs=tt(),Mp=So(),_E=TypeError,xo=Object.defineProperty,NE=Object.getOwnPropertyDescriptor,Po="enumerable",wo="configurable",Ao="writable";Dp.f=VE?BE?function(e,t,i){if(hs(e),t=Mp(t),hs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Ao in i&&!i[Ao]){var r=NE(e,t);r&&r[Ao]&&(e[t]=i.value,i={configurable:wo in i?i[wo]:r[wo],enumerable:Po in i?i[Po]:r[Po],writable:!1})}return xo(e,t,i)}:xo:function(e,t,i){if(hs(e),t=Mp(t),hs(i),OE)try{return xo(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new _E("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ri=f((gV,Cp)=>{"use strict";var FE=$e(),qE=ei(),UE=mr();Cp.exports=FE?function(a,e,t){return qE.f(a,e,UE(1,t))}:function(a,e,t){return a[e]=t,a}});var se=f((vV,Op)=>{"use strict";var yr=re(),HE=Zn(),jE=to(),QE=ee(),GE=wp().f,WE=Io(),Li=Pi(),YE=ki(),$i=Ri(),Vp=Ge();vr();var zE=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return HE(a,this,arguments)};return e.prototype=a.prototype,e};Op.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?yr:r?yr[t]:yr[t]&&yr[t].prototype,o=i?Li:Li[t]||$i(Li,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,v;for(h in e)l=WE(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Vp(n,h),m=o[h],c&&(a.dontCallGetSet?(v=GE(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?g=YE(p,yr):a.wrap&&c?g=zE(p):s&&QE(p)?g=jE(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&$i(g,"sham",!0),$i(o,h,g),s&&(d=t+"Prototype",Vp(Li,d)||$i(Li,d,{}),$i(Li[d],h,p),a.real&&u&&(l||!u[h])&&$i(u,h,p)))}});var _p=f((SV,Bp)=>{"use strict";var KE=Math.ceil,XE=Math.floor;Bp.exports=Math.trunc||function(e){var t=+e;return(t>0?XE:KE)(t)}});var Tr=f((yV,Np)=>{"use strict";var JE=_p();Np.exports=function(a){var e=+a;return e!==e||e===0?0:JE(e)}});var qp=f((TV,Fp)=>{"use strict";var ZE=Tr(),ex=Math.max,tx=Math.min;Fp.exports=function(a,e){var t=ZE(a);return t<0?ex(t+e,0):tx(t,e)}});var ko=f((IV,Up)=>{"use strict";var ix=Tr(),rx=Math.min;Up.exports=function(a){var e=ix(a);return e>0?rx(e,9007199254740991):0}});var Mi=f((EV,Hp)=>{"use strict";var ax=ko();Hp.exports=function(a){return ax(a.length)}});var Ro=f((xV,Qp)=>{"use strict";var sx=Jt(),nx=qp(),ox=Mi(),jp=function(a){return function(e,t,i){var r=sx(e),s=ox(r);if(s===0)return!a&&-1;var n=nx(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Qp.exports={includes:jp(!0),indexOf:jp(!1)}});var Ir=f((PV,Gp)=>{"use strict";Gp.exports=function(){}});var Wp=f(()=>{"use strict";var ux=se(),lx=Ro().includes,cx=de(),dx=Ir(),px=cx(function(){return!Array(1).includes()});ux({target:"Array",proto:!0,forced:px},{includes:function(e){return lx(this,e,arguments.length>1?arguments[1]:void 0)}});dx("includes")});var kt=f((kV,Yp)=>{"use strict";var hx=ct();Yp.exports=hx});var Kp=f((RV,zp)=>{"use strict";Wp();var mx=kt();zp.exports=mx("Array","includes")});var Jp=f((LV,Xp)=>{"use strict";var fx=Kp();Xp.exports=fx});var Be=f(($V,Zp)=>{"use strict";var bx=Jp();Zp.exports=bx});var bs=f((HV,oh)=>{"use strict";var xx=bo(),Px=go(),nh=xx("keys");oh.exports=function(a){return nh[a]||(nh[a]=Px(a))}});var lh=f((jV,uh)=>{"use strict";var wx=de();uh.exports=!wx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gs=f((QV,dh)=>{"use strict";var Ax=Ge(),kx=ee(),Rx=wi(),Lx=bs(),$x=lh(),ch=Lx("IE_PROTO"),Mo=Object,Mx=Mo.prototype;dh.exports=$x?Mo.getPrototypeOf:function(a){var e=Rx(a);if(Ax(e,ch))return e[ch];var t=e.constructor;return kx(t)&&e instanceof t?t.prototype:e instanceof Mo?Mx:null}});var vs=f((GV,ph)=>{"use strict";ph.exports={}});var fh=f((WV,mh)=>{"use strict";var Dx=ne(),Do=Ge(),Cx=Jt(),Vx=Ro().indexOf,Ox=vs(),hh=Dx([].push);mh.exports=function(a,e){var t=Cx(a),i=0,r=[],s;for(s in t)!Do(Ox,s)&&Do(t,s)&&hh(r,s);for(;e.length>i;)Do(t,s=e[i++])&&(~Vx(r,s)||hh(r,s));return r}});var Co=f((YV,bh)=>{"use strict";bh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vo=f((zV,gh)=>{"use strict";var Bx=fh(),_x=Co();gh.exports=Object.keys||function(e){return Bx(e,_x)}});var Oo=f((KV,Ih)=>{"use strict";var Sh=$e(),Nx=de(),yh=ne(),Fx=gs(),qx=Vo(),Ux=Jt(),Hx=ro().f,Th=yh(Hx),jx=yh([].push),Qx=Sh&&Nx(function(){var a=Object.create(null);return a[2]=2,!Th(a,2)}),vh=function(a){return function(e){for(var t=Ux(e),i=qx(t),r=Qx&&Fx(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Sh||(r?u in t:Th(t,u)))&&jx(o,a?[u,t[u]]:t[u]);return o}};Ih.exports={entries:vh(!0),values:vh(!1)}});var Eh=f(()=>{"use strict";var Gx=se(),Wx=Oo().entries;Gx({target:"Object",stat:!0},{entries:function(e){return Wx(e)}})});var Ph=f((ZV,xh)=>{"use strict";Eh();var Yx=Pi();xh.exports=Yx.Object.entries});var Ah=f((eO,wh)=>{"use strict";var zx=Ph();wh.exports=zx});var Di=f((tO,kh)=>{"use strict";var Kx=Ah();kh.exports=Kx});var ti=f((iO,Rh)=>{"use strict";Rh.exports={}});var Mh=f((rO,$h)=>{"use strict";var Xx=re(),Jx=ee(),Lh=Xx.WeakMap;$h.exports=Jx(Lh)&&/native code/.test(String(Lh))});var Fo=f((aO,Vh)=>{"use strict";var Zx=Mh(),Ch=re(),eP=De(),tP=Ri(),Bo=Ge(),_o=vr(),iP=bs(),rP=vs(),Dh="Object already initialized",No=Ch.TypeError,aP=Ch.WeakMap,Ss,Er,ys,sP=function(a){return ys(a)?Er(a):Ss(a,{})},nP=function(a){return function(e){var t;if(!eP(e)||(t=Er(e)).type!==a)throw new No("Incompatible receiver, "+a+" required");return t}};Zx||_o.state?(We=_o.state||(_o.state=new aP),We.get=We.get,We.has=We.has,We.set=We.set,Ss=function(a,e){if(We.has(a))throw new No(Dh);return e.facade=a,We.set(a,e),e},Er=function(a){return We.get(a)||{}},ys=function(a){return We.has(a)}):(ii=iP("state"),rP[ii]=!0,Ss=function(a,e){if(Bo(a,ii))throw new No(Dh);return e.facade=a,tP(a,ii,e),e},Er=function(a){return Bo(a,ii)?a[ii]:{}},ys=function(a){return Bo(a,ii)});var We,ii;Vh.exports={set:Ss,get:Er,has:ys,enforce:sP,getterFor:nP}});var Ho=f((sO,Bh)=>{"use strict";var qo=$e(),oP=Ge(),Oh=Function.prototype,uP=qo&&Object.getOwnPropertyDescriptor,Uo=oP(Oh,"name"),lP=Uo&&function(){}.name==="something",cP=Uo&&(!qo||qo&&uP(Oh,"name").configurable);Bh.exports={EXISTS:Uo,PROPER:lP,CONFIGURABLE:cP}});var Nh=f(_h=>{"use strict";var dP=$e(),pP=Eo(),hP=ei(),mP=tt(),fP=Jt(),bP=Vo();_h.f=dP&&!pP?Object.defineProperties:function(e,t){mP(e);for(var i=fP(t),r=bP(t),s=r.length,n=0,o;s>n;)hP.f(e,o=r[n++],i[o]);return e}});var jo=f((oO,Fh)=>{"use strict";var gP=ct();Fh.exports=gP("document","documentElement")});var Yo=f((uO,Wh)=>{"use strict";var vP=tt(),SP=Nh(),qh=Co(),yP=vs(),TP=jo(),IP=ps(),EP=bs(),Uh=">",Hh="<",Go="prototype",Wo="script",Qh=EP("IE_PROTO"),Qo=function(){},Gh=function(a){return Hh+Wo+Uh+a+Hh+"/"+Wo+Uh},jh=function(a){a.write(Gh("")),a.close();var e=a.parentWindow.Object;return a=null,e},xP=function(){var a=IP("iframe"),e="java"+Wo+":",t;return a.style.display="none",TP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Gh("document.F=Object")),t.close(),t.F},Ts,Is=function(){try{Ts=new ActiveXObject("htmlfile")}catch(e){}Is=typeof document!="undefined"?document.domain&&Ts?jh(Ts):xP():jh(Ts);for(var a=qh.length;a--;)delete Is[Go][qh[a]];return Is()};yP[Qh]=!0;Wh.exports=Object.create||function(e,t){var i;return e!==null?(Qo[Go]=vP(e),i=new Qo,Qo[Go]=null,i[Qh]=e):i=Is(),t===void 0?i:SP.f(i,t)}});var Ci=f((lO,Yh)=>{"use strict";var PP=Ri();Yh.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:PP(a,e,t),a}});var Jo=f((cO,Xh)=>{"use strict";var wP=de(),AP=ee(),kP=De(),RP=Yo(),zh=gs(),LP=Ci(),$P=pe(),MP=Qe(),Xo=$P("iterator"),Kh=!1,dt,zo,Ko;[].keys&&(Ko=[].keys(),"next"in Ko?(zo=zh(zh(Ko)),zo!==Object.prototype&&(dt=zo)):Kh=!0);var DP=!kP(dt)||wP(function(){var a={};return dt[Xo].call(a)!==a});DP?dt={}:MP&&(dt=RP(dt));AP(dt[Xo])||LP(dt,Xo,function(){return this});Xh.exports={IteratorPrototype:dt,BUGGY_SAFARI_ITERATORS:Kh}});var Es=f((dO,Zh)=>{"use strict";var CP=pe(),VP=CP("toStringTag"),Jh={};Jh[VP]="z";Zh.exports=String(Jh)==="[object z]"});var xr=f((pO,em)=>{"use strict";var OP=Es(),BP=ee(),xs=Xt(),_P=pe(),NP=_P("toStringTag"),FP=Object,qP=xs(function(){return arguments}())==="Arguments",UP=function(a,e){try{return a[e]}catch(t){}};em.exports=OP?xs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=UP(e=FP(a),NP))=="string"?t:qP?xs(e):(i=xs(e))==="Object"&&BP(e.callee)?"Arguments":i}});var im=f((hO,tm)=>{"use strict";var HP=Es(),jP=xr();tm.exports=HP?{}.toString:function(){return"[object "+jP(this)+"]"}});var Pr=f((mO,am)=>{"use strict";var QP=Es(),GP=ei().f,WP=Ri(),YP=Ge(),zP=im(),KP=pe(),rm=KP("toStringTag");am.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(YP(r,rm)||GP(r,rm,{configurable:!0,value:e}),i&&!QP&&WP(r,"toString",zP))}});var nm=f((fO,sm)=>{"use strict";var XP=Jo().IteratorPrototype,JP=Yo(),ZP=mr(),ew=Pr(),tw=ti(),iw=function(){return this};sm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=JP(XP,{next:ZP(+!i,t)}),ew(a,r,!1,!0),tw[r]=iw,a}});var um=f((bO,om)=>{"use strict";var rw=ne(),aw=et();om.exports=function(a,e,t){try{return rw(aw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var cm=f((gO,lm)=>{"use strict";var sw=De();lm.exports=function(a){return sw(a)||a===null}});var pm=f((vO,dm)=>{"use strict";var nw=cm(),ow=String,uw=TypeError;dm.exports=function(a){if(nw(a))return a;throw new uw("Can't set "+ow(a)+" as a prototype")}});var Zo=f((SO,hm)=>{"use strict";var lw=um(),cw=De(),dw=At(),pw=pm();hm.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(i){}return function(r,s){return dw(r),pw(s),cw(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var xm=f((yO,Em)=>{"use strict";var hw=se(),mw=Me(),Ps=Qe(),Tm=Ho(),fw=ee(),bw=nm(),mm=gs(),fm=Zo(),gw=Pr(),vw=Ri(),eu=Ci(),Sw=pe(),bm=ti(),Im=Jo(),yw=Tm.PROPER,Tw=Tm.CONFIGURABLE,gm=Im.IteratorPrototype,ws=Im.BUGGY_SAFARI_ITERATORS,wr=Sw("iterator"),vm="keys",Ar="values",Sm="entries",ym=function(){return this};Em.exports=function(a,e,t,i,r,s,n){bw(t,e,i);var o=function(v){if(v===r&&h)return h;if(!ws&&v&&v in c)return c[v];switch(v){case vm:return function(){return new t(this,v)};case Ar:return function(){return new t(this,v)};case Sm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[wr]||c["@@iterator"]||r&&c[r],h=!ws&&d||o(r),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=mm(p.call(new a)),m!==Object.prototype&&m.next&&(!Ps&&mm(m)!==gm&&(fm?fm(m,gm):fw(m[wr])||eu(m,wr,ym)),gw(m,u,!0,!0),Ps&&(bm[u]=ym))),yw&&r===Ar&&d&&d.name!==Ar&&(!Ps&&Tw?vw(c,"name",Ar):(l=!0,h=function(){return mw(d,this)})),r)if(b={values:o(Ar),keys:s?h:o(vm),entries:o(Sm)},n)for(g in b)(ws||l||!(g in c))&&eu(c,g,b[g]);else hw({target:e,proto:!0,forced:ws||l},b);return(!Ps||n)&&c[wr]!==h&&eu(c,wr,h,{name:r}),bm[e]=h,b}});var wm=f((TO,Pm)=>{"use strict";Pm.exports=function(a,e){return{value:a,done:e}}});var iu=f((IO,$m)=>{"use strict";var Iw=Jt(),tu=Ir(),Am=ti(),Rm=Fo(),Ew=ei().f,xw=xm(),As=wm(),Pw=Qe(),ww=$e(),Lm="Array Iterator",Aw=Rm.set,kw=Rm.getterFor(Lm);$m.exports=xw(Array,"Array",function(a,e){Aw(this,{type:Lm,target:Iw(a),index:0,kind:e})},function(){var a=kw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,As(void 0,!0);switch(a.kind){case"keys":return As(t,!1);case"values":return As(e[t],!1)}return As([t,e[t]],!1)},"values");var km=Am.Arguments=Am.Array;tu("keys");tu("values");tu("entries");if(!Pw&&ww&&km.name!=="values")try{Ew(km,"name",{value:"values"})}catch(a){}});var Dm=f((EO,Mm)=>{"use strict";var Rw=pe(),Lw=ti(),$w=Rw("iterator"),Mw=Array.prototype;Mm.exports=function(a){return a!==void 0&&(Lw.Array===a||Mw[$w]===a)}});var ru=f((xO,Vm)=>{"use strict";var Dw=xr(),Cm=gr(),Cw=xi(),Vw=ti(),Ow=pe(),Bw=Ow("iterator");Vm.exports=function(a){if(!Cw(a))return Cm(a,Bw)||Cm(a,"@@iterator")||Vw[Dw(a)]}});var Bm=f((PO,Om)=>{"use strict";var _w=Me(),Nw=et(),Fw=tt(),qw=br(),Uw=ru(),Hw=TypeError;Om.exports=function(a,e){var t=arguments.length<2?Uw(a):e;if(Nw(t))return Fw(_w(t,a));throw new Hw(qw(a)+" is not iterable")}});var Fm=f((wO,Nm)=>{"use strict";var jw=Me(),_m=tt(),Qw=gr();Nm.exports=function(a,e,t){var i,r;_m(a);try{if(i=Qw(a,"return"),!i){if(e==="throw")throw t;return t}i=jw(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return _m(i),t}});var Rs=f((AO,jm)=>{"use strict";var Gw=ki(),Ww=Me(),Yw=tt(),zw=br(),Kw=Dm(),Xw=Mi(),qm=fr(),Jw=Bm(),Zw=ru(),Um=Fm(),eA=TypeError,ks=function(a,e){this.stopped=a,this.result=e},Hm=ks.prototype;jm.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Gw(e,i),l,c,d,h,p,m,b,g=function(S){return l&&Um(l,"normal",S),new ks(!0,S)},v=function(S){return r?(Yw(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=Zw(a),!c)throw new eA(zw(a)+" is not iterable");if(Kw(c)){for(d=0,h=Xw(a);h>d;d++)if(p=v(a[d]),p&&qm(Hm,p))return p;return new ks(!1)}l=Jw(a,c)}for(m=s?a.next:l.next;!(b=Ww(m,l)).done;){try{p=v(b.value)}catch(S){Um(l,"throw",S)}if(typeof p=="object"&&p&&qm(Hm,p))return p}return new ks(!1)}});var Gm=f((kO,Qm)=>{"use strict";var tA=$e(),iA=ei(),rA=mr();Qm.exports=function(a,e,t){tA?iA.f(a,e,rA(0,t)):a[e]=t}});var Wm=f(()=>{"use strict";var aA=se(),sA=Rs(),nA=Gm();aA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return sA(e,function(i,r){nA(t,i,r)},{AS_ENTRIES:!0}),t}})});var zm=f(($O,Ym)=>{"use strict";iu();Wm();var oA=Pi();Ym.exports=oA.Object.fromEntries});var Xm=f((MO,Km)=>{"use strict";Km.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 Zm=f(()=>{"use strict";iu();var uA=Xm(),lA=re(),cA=Pr(),Jm=ti();for(Ls in uA)cA(lA[Ls],Ls),Jm[Ls]=Jm.Array;var Ls});var tf=f((VO,ef)=>{"use strict";var dA=zm();Zm();ef.exports=dA});var au=f((OO,rf)=>{"use strict";var pA=tf();rf.exports=pA});var af=f(()=>{"use strict"});var su=f((NO,sf)=>{"use strict";var kr=re(),hA=Zt(),mA=Xt(),$s=function(a){return hA.slice(0,a.length)===a};sf.exports=function(){return $s("Bun/")?"BUN":$s("Cloudflare-Workers")?"CLOUDFLARE":$s("Deno/")?"DENO":$s("Node.js/")?"NODE":kr.Bun&&typeof Bun.version=="string"?"BUN":kr.Deno&&typeof Deno.version=="object"?"DENO":mA(kr.process)==="process"?"NODE":kr.window&&kr.document?"BROWSER":"REST"}()});var Ms=f((FO,nf)=>{"use strict";var fA=su();nf.exports=fA==="NODE"});var uf=f((qO,of)=>{"use strict";var bA=ei();of.exports=function(a,e,t){return bA.f(a,e,t)}});var df=f((UO,cf)=>{"use strict";var gA=ct(),vA=uf(),SA=pe(),yA=$e(),lf=SA("species");cf.exports=function(a){var e=gA(a);yA&&e&&!e[lf]&&vA(e,lf,{configurable:!0,get:function(){return this}})}});var hf=f((HO,pf)=>{"use strict";var TA=fr(),IA=TypeError;pf.exports=function(a,e){if(TA(e,a))return a;throw new IA("Incorrect invocation")}});var ou=f((jO,mf)=>{"use strict";var EA=ne(),xA=ee(),nu=vr(),PA=EA(Function.toString);xA(nu.inspectSource)||(nu.inspectSource=function(a){return PA(a)});mf.exports=nu.inspectSource});var lu=f((QO,Sf)=>{"use strict";var wA=ne(),AA=de(),ff=ee(),kA=xr(),RA=ct(),LA=ou(),bf=function(){},gf=RA("Reflect","construct"),uu=/^\s*(?:class|function)\b/,$A=wA(uu.exec),MA=!uu.test(bf),Rr=function(e){if(!ff(e))return!1;try{return gf(bf,[],e),!0}catch(t){return!1}},vf=function(e){if(!ff(e))return!1;switch(kA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return MA||!!$A(uu,LA(e))}catch(t){return!0}};vf.sham=!0;Sf.exports=!gf||AA(function(){var a;return Rr(Rr.call)||!Rr(Object)||!Rr(function(){a=!0})||a})?vf:Rr});var Tf=f((GO,yf)=>{"use strict";var DA=lu(),CA=br(),VA=TypeError;yf.exports=function(a){if(DA(a))return a;throw new VA(CA(a)+" is not a constructor")}});var cu=f((WO,Ef)=>{"use strict";var If=tt(),OA=Tf(),BA=xi(),_A=pe(),NA=_A("species");Ef.exports=function(a,e){var t=If(a).constructor,i;return t===void 0||BA(i=If(t)[NA])?e:OA(i)}});var Pf=f((YO,xf)=>{"use strict";var FA=ne();xf.exports=FA([].slice)});var Af=f((zO,wf)=>{"use strict";var qA=TypeError;wf.exports=function(a,e){if(a<e)throw new qA("Not enough arguments");return a}});var du=f((KO,kf)=>{"use strict";var UA=Zt();kf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(UA)});var yu=f((XO,Bf)=>{"use strict";var Ce=re(),HA=Zn(),jA=ki(),Rf=ee(),QA=Ge(),Of=de(),Lf=jo(),GA=Pf(),$f=ps(),WA=Af(),YA=du(),zA=Ms(),gu=Ce.setImmediate,vu=Ce.clearImmediate,KA=Ce.process,pu=Ce.Dispatch,XA=Ce.Function,Mf=Ce.MessageChannel,JA=Ce.String,hu=0,Lr={},Df="onreadystatechange",$r,ri,mu,fu;Of(function(){$r=Ce.location});var Su=function(a){if(QA(Lr,a)){var e=Lr[a];delete Lr[a],e()}},bu=function(a){return function(){Su(a)}},Cf=function(a){Su(a.data)},Vf=function(a){Ce.postMessage(JA(a),$r.protocol+"//"+$r.host)};(!gu||!vu)&&(gu=function(e){WA(arguments.length,1);var t=Rf(e)?e:XA(e),i=GA(arguments,1);return Lr[++hu]=function(){HA(t,void 0,i)},ri(hu),hu},vu=function(e){delete Lr[e]},zA?ri=function(a){KA.nextTick(bu(a))}:pu&&pu.now?ri=function(a){pu.now(bu(a))}:Mf&&!YA?(mu=new Mf,fu=mu.port2,mu.port1.onmessage=Cf,ri=jA(fu.postMessage,fu)):Ce.addEventListener&&Rf(Ce.postMessage)&&!Ce.importScripts&&$r&&$r.protocol!=="file:"&&!Of(Vf)?(ri=Vf,Ce.addEventListener("message",Cf,!1)):Df in $f("script")?ri=function(a){Lf.appendChild($f("script"))[Df]=function(){Lf.removeChild(this),Su(a)}}:ri=function(a){setTimeout(bu(a),0)});Bf.exports={set:gu,clear:vu}});var Ff=f((JO,Nf)=>{"use strict";var _f=re(),ZA=$e(),ek=Object.getOwnPropertyDescriptor;Nf.exports=function(a){if(!ZA)return _f[a];var e=ek(_f,a);return e&&e.value}});var Tu=f((ZO,Uf)=>{"use strict";var qf=function(){this.head=null,this.tail=null};qf.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}}};Uf.exports=qf});var jf=f((eB,Hf)=>{"use strict";var tk=Zt();Hf.exports=/ipad|iphone|ipod/i.test(tk)&&typeof Pebble!="undefined"});var Gf=f((tB,Qf)=>{"use strict";var ik=Zt();Qf.exports=/web0s(?!.*chrome)/i.test(ik)});var Zf=f((iB,Jf)=>{"use strict";var Oi=re(),rk=Ff(),Wf=ki(),Iu=yu().set,ak=Tu(),sk=du(),nk=jf(),ok=Gf(),Eu=Ms(),Yf=Oi.MutationObserver||Oi.WebKitMutationObserver,zf=Oi.document,Kf=Oi.process,Ds=Oi.Promise,wu=rk("queueMicrotask"),Vi,xu,Pu,Cs,Xf;wu||(Mr=new ak,Dr=function(){var a,e;for(Eu&&(a=Kf.domain)&&a.exit();e=Mr.get();)try{e()}catch(t){throw Mr.head&&Vi(),t}a&&a.enter()},!sk&&!Eu&&!ok&&Yf&&zf?(xu=!0,Pu=zf.createTextNode(""),new Yf(Dr).observe(Pu,{characterData:!0}),Vi=function(){Pu.data=xu=!xu}):!nk&&Ds&&Ds.resolve?(Cs=Ds.resolve(void 0),Cs.constructor=Ds,Xf=Wf(Cs.then,Cs),Vi=function(){Xf(Dr)}):Eu?Vi=function(){Kf.nextTick(Dr)}:(Iu=Wf(Iu,Oi),Vi=function(){Iu(Dr)}),wu=function(a){Mr.head||Vi(),Mr.add(a)});var Mr,Dr;Jf.exports=wu});var tb=f((rB,eb)=>{"use strict";eb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Vs=f((aB,ib)=>{"use strict";ib.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ai=f((sB,rb)=>{"use strict";var uk=re();rb.exports=uk.Promise});var Bi=f((nB,ob)=>{"use strict";var lk=re(),Cr=ai(),ck=ee(),dk=Io(),pk=ou(),hk=pe(),ab=su(),mk=Qe(),Au=uo(),sb=Cr&&Cr.prototype,fk=hk("species"),ku=!1,nb=ck(lk.PromiseRejectionEvent),bk=dk("Promise",function(){var a=pk(Cr),e=a!==String(Cr);if(!e&&Au===66||mk&&!(sb.catch&&sb.finally))return!0;if(!Au||Au<51||!/native code/.test(a)){var t=new Cr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[fk]=i,ku=t.then(function(){})instanceof i,!ku)return!0}return!e&&(ab==="BROWSER"||ab==="DENO")&&!nb});ob.exports={CONSTRUCTOR:bk,REJECTION_EVENT:nb,SUBCLASSING:ku}});var _i=f((oB,lb)=>{"use strict";var ub=et(),gk=TypeError,vk=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new gk("Bad Promise constructor");e=i,t=r}),this.resolve=ub(e),this.reject=ub(t)};lb.exports.f=function(a){return new vk(a)}});var kb=f(()=>{"use strict";var Sk=se(),yk=Qe(),Ns=Ms(),Rt=re(),Ui=Me(),cb=Ci(),db=Zo(),Tk=Pr(),Ik=df(),Ek=et(),_s=ee(),xk=De(),Pk=hf(),wk=cu(),bb=yu().set,Du=Zf(),Ak=tb(),kk=Vs(),Rk=Tu(),gb=Fo(),Fs=ai(),Cu=Bi(),vb=_i(),qs="Promise",Sb=Cu.CONSTRUCTOR,Lk=Cu.REJECTION_EVENT,$k=Cu.SUBCLASSING,Ru=gb.getterFor(qs),Mk=gb.set,Ni=Fs&&Fs.prototype,si=Fs,Os=Ni,yb=Rt.TypeError,Lu=Rt.document,Vu=Rt.process,$u=vb.f,Dk=$u,Ck=!!(Lu&&Lu.createEvent&&Rt.dispatchEvent),Tb="unhandledrejection",Vk="rejectionhandled",pb=0,Ib=1,Ok=2,Ou=1,Eb=2,Bs,hb,Bk,mb,xb=function(a){var e;return xk(a)&&_s(e=a.then)?e:!1},Pb=function(a,e){var t=e.value,i=e.state===Ib,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===Eb&&Nk(e),e.rejection=Ou),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new yb("Promise-chain cycle")):(l=xb(u))?Ui(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},wb=function(a,e){a.notified||(a.notified=!0,Du(function(){for(var t=a.reactions,i;i=t.get();)Pb(i,a);a.notified=!1,e&&!a.rejection&&_k(a)}))},Ab=function(a,e,t){var i,r;Ck?(i=Lu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Rt.dispatchEvent(i)):i={promise:e,reason:t},!Lk&&(r=Rt["on"+a])?r(i):a===Tb&&Ak("Unhandled promise rejection",t)},_k=function(a){Ui(bb,Rt,function(){var e=a.facade,t=a.value,i=fb(a),r;if(i&&(r=kk(function(){Ns?Vu.emit("unhandledRejection",t,e):Ab(Tb,e,t)}),a.rejection=Ns||fb(a)?Eb:Ou,r.error))throw r.value})},fb=function(a){return a.rejection!==Ou&&!a.parent},Nk=function(a){Ui(bb,Rt,function(){var e=a.facade;Ns?Vu.emit("rejectionHandled",e):Ab(Vk,e,a.value)})},Fi=function(a,e,t){return function(i){a(e,i,t)}},qi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Ok,wb(a,!0))},Mu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new yb("Promise can't be resolved itself");var i=xb(e);i?Du(function(){var r={done:!1};try{Ui(i,e,Fi(Mu,r,a),Fi(qi,r,a))}catch(s){qi(r,s,a)}}):(a.value=e,a.state=Ib,wb(a,!1))}catch(r){qi({done:!1},r,a)}}};if(Sb&&(si=function(e){Pk(this,Os),Ek(e),Ui(Bs,this);var t=Ru(this);try{e(Fi(Mu,t),Fi(qi,t))}catch(i){qi(t,i)}},Os=si.prototype,Bs=function(e){Mk(this,{type:qs,done:!1,notified:!1,parent:!1,reactions:new Rk,rejection:!1,state:pb,value:void 0})},Bs.prototype=cb(Os,"then",function(e,t){var i=Ru(this),r=$u(wk(this,si));return i.parent=!0,r.ok=_s(e)?e:!0,r.fail=_s(t)&&t,r.domain=Ns?Vu.domain:void 0,i.state===pb?i.reactions.add(r):Du(function(){Pb(r,i)}),r.promise}),hb=function(){var a=new Bs,e=Ru(a);this.promise=a,this.resolve=Fi(Mu,e),this.reject=Fi(qi,e)},vb.f=$u=function(a){return a===si||a===Bk?new hb(a):Dk(a)},!yk&&_s(Fs)&&Ni!==Object.prototype)){mb=Ni.then,$k||cb(Ni,"then",function(e,t){var i=this;return new si(function(r,s){Ui(mb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Ni.constructor}catch(a){}db&&db(Ni,Os)}Sk({global:!0,constructor:!0,wrap:!0,forced:Sb},{Promise:si});Tk(si,qs,!1,!0);Ik(qs)});var Db=f((cB,Mb)=>{"use strict";var Fk=pe(),Lb=Fk("iterator"),$b=!1;try{Rb=0,Bu={next:function(){return{done:!!Rb++}},return:function(){$b=!0}},Bu[Lb]=function(){return this},Array.from(Bu,function(){throw 2})}catch(a){}var Rb,Bu;Mb.exports=function(a,e){try{if(!e&&!$b)return!1}catch(r){return!1}var t=!1;try{var i={};i[Lb]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var _u=f((dB,Cb)=>{"use strict";var qk=ai(),Uk=Db(),Hk=Bi().CONSTRUCTOR;Cb.exports=Hk||!Uk(function(a){qk.all(a).then(void 0,function(){})})});var Vb=f(()=>{"use strict";var jk=se(),Qk=Me(),Gk=et(),Wk=_i(),Yk=Vs(),zk=Rs(),Kk=_u();jk({target:"Promise",stat:!0,forced:Kk},{all:function(e){var t=this,i=Wk.f(t),r=i.resolve,s=i.reject,n=Yk(function(){var o=Gk(t.resolve),u=[],l=0,c=1;zk(e,function(d){var h=l++,p=!1;c++,Qk(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var Bb=f(()=>{"use strict";var Xk=se(),Jk=Qe(),Zk=Bi().CONSTRUCTOR,Fu=ai(),eR=ct(),tR=ee(),iR=Ci(),Ob=Fu&&Fu.prototype;Xk({target:"Promise",proto:!0,forced:Zk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Jk&&tR(Fu)&&(Nu=eR("Promise").prototype.catch,Ob.catch!==Nu&&iR(Ob,"catch",Nu,{unsafe:!0}));var Nu});var _b=f(()=>{"use strict";var rR=se(),aR=Me(),sR=et(),nR=_i(),oR=Vs(),uR=Rs(),lR=_u();rR({target:"Promise",stat:!0,forced:lR},{race:function(e){var t=this,i=nR.f(t),r=i.reject,s=oR(function(){var n=sR(t.resolve);uR(e,function(o){aR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Nb=f(()=>{"use strict";var cR=se(),dR=_i(),pR=Bi().CONSTRUCTOR;cR({target:"Promise",stat:!0,forced:pR},{reject:function(e){var t=dR.f(this),i=t.reject;return i(e),t.promise}})});var qu=f((yB,Fb)=>{"use strict";var hR=tt(),mR=De(),fR=_i();Fb.exports=function(a,e){if(hR(a),mR(e)&&e.constructor===a)return e;var t=fR.f(a),i=t.resolve;return i(e),t.promise}});var Hb=f(()=>{"use strict";var bR=se(),gR=ct(),qb=Qe(),vR=ai(),Ub=Bi().CONSTRUCTOR,SR=qu(),yR=gR("Promise"),TR=qb&&!Ub;bR({target:"Promise",stat:!0,forced:qb||Ub},{resolve:function(e){return SR(TR&&this===yR?vR:this,e)}})});var jb=f(()=>{"use strict";kb();Vb();Bb();_b();Nb();Hb()});var Yb=f(()=>{"use strict";var IR=se(),ER=Qe(),Us=ai(),xR=de(),Gb=ct(),Wb=ee(),PR=cu(),Qb=qu(),wR=Ci(),Hu=Us&&Us.prototype,AR=!!Us&&xR(function(){Hu.finally.call({then:function(){}},function(){})});IR({target:"Promise",proto:!0,real:!0,forced:AR},{finally:function(a){var e=PR(this,Gb("Promise")),t=Wb(a);return this.then(t?function(i){return Qb(e,a()).then(function(){return i})}:a,t?function(i){return Qb(e,a()).then(function(){throw i})}:a)}});!ER&&Wb(Us)&&(Uu=Gb("Promise").prototype.finally,Hu.finally!==Uu&&wR(Hu,"finally",Uu,{unsafe:!0}));var Uu});var Kb=f((AB,zb)=>{"use strict";af();jb();Yb();var kR=kt();zb.exports=kR("Promise","finally")});var Jb=f((kB,Xb)=>{"use strict";var RR=Kb();Xb.exports=RR});var Hs=f((RB,Zb)=>{"use strict";var LR=Jb();Zb.exports=LR});var pg=f(()=>{"use strict";var jR=se(),QR=Oo().values;jR({target:"Object",stat:!0},{values:function(e){return QR(e)}})});var mg=f((h_,hg)=>{"use strict";pg();var GR=Pi();hg.exports=GR.Object.values});var bg=f((m_,fg)=>{"use strict";var WR=mg();fg.exports=WR});var ji=f((f_,gg)=>{"use strict";var YR=bg();gg.exports=YR});var Cg=f(()=>{"use strict";var vL=se(),SL=wi(),yL=Mi(),TL=Tr(),IL=Ir();vL({target:"Array",proto:!0},{at:function(e){var t=SL(this),i=yL(t),r=TL(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});IL("at")});var Og=f((xN,Vg)=>{"use strict";Cg();var EL=kt();Vg.exports=EL("Array","at")});var _g=f((PN,Bg)=>{"use strict";var xL=Og();Bg.exports=xL});var Ct=f((wN,Ng)=>{"use strict";var PL=_g();Ng.exports=PL});var fl=f((dq,yv)=>{"use strict";var u$=Xt();yv.exports=Array.isArray||function(e){return u$(e)==="Array"}});var Iv=f((pq,Tv)=>{"use strict";var l$=TypeError,c$=9007199254740991;Tv.exports=function(a){if(a>c$)throw l$("Maximum allowed index exceeded");return a}});var Pv=f((hq,xv)=>{"use strict";var d$=fl(),p$=Mi(),h$=Iv(),m$=ki(),Ev=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?m$(n,o):!1,d,h;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&d$(d)?(h=p$(d),u=Ev(a,e,d,h,u,s-1)-1):(h$(u+1),a[u]=d),u++),l++;return u};xv.exports=Ev});var Rv=f((mq,kv)=>{"use strict";var wv=fl(),f$=lu(),b$=De(),g$=pe(),v$=g$("species"),Av=Array;kv.exports=function(a){var e;return wv(a)&&(e=a.constructor,f$(e)&&(e===Av||wv(e.prototype))?e=void 0:b$(e)&&(e=e[v$],e===null&&(e=void 0))),e===void 0?Av:e}});var $v=f((fq,Lv)=>{"use strict";var S$=Rv();Lv.exports=function(a,e){return new(S$(a))(e===0?0:e)}});var Mv=f(()=>{"use strict";var y$=se(),T$=Pv(),I$=et(),E$=wi(),x$=Mi(),P$=$v();y$({target:"Array",proto:!0},{flatMap:function(e){var t=E$(this),i=x$(t),r;return I$(e),r=P$(t,0),r.length=T$(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Dv=f(()=>{"use strict";var w$=Ir();w$("flatMap")});var Vv=f((yq,Cv)=>{"use strict";Mv();Dv();var A$=kt();Cv.exports=A$("Array","flatMap")});var Bv=f((Tq,Ov)=>{"use strict";var k$=Vv();Ov.exports=k$});var bl=f((Iq,_v)=>{"use strict";var R$=Bv();_v.exports=R$});var Xr=f((Eq,Nv)=>{"use strict";var L$=xr(),$$=String;Nv.exports=function(a){if(L$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return $$(a)}});var gl=f((xq,Fv)=>{"use strict";Fv.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 Hv=f((Pq,Uv)=>{"use strict";var M$=ne(),D$=At(),C$=Xr(),Sl=gl(),qv=M$("".replace),V$=RegExp("^["+Sl+"]+"),O$=RegExp("(^|[^"+Sl+"])["+Sl+"]+$"),vl=function(a){return function(e){var t=C$(D$(e));return a&1&&(t=qv(t,V$,"")),a&2&&(t=qv(t,O$,"$1")),t}};Uv.exports={start:vl(1),end:vl(2),trim:vl(3)}});var Wv=f((wq,Gv)=>{"use strict";var B$=Ho().PROPER,_$=de(),jv=gl(),Qv="\u200B\x85\u180E";Gv.exports=function(a){return _$(function(){return!!jv[a]()||Qv[a]()!==Qv||B$&&jv[a].name!==a})}});var yl=f((Aq,Yv)=>{"use strict";var N$=Hv().start,F$=Wv();Yv.exports=F$("trimStart")?function(){return N$(this)}:"".trimStart});var Kv=f(()=>{"use strict";var q$=se(),zv=yl();q$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==zv},{trimLeft:zv})});var Jv=f(()=>{"use strict";Kv();var U$=se(),Xv=yl();U$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Xv},{trimStart:Xv})});var eS=f((Mq,Zv)=>{"use strict";Jv();var H$=kt();Zv.exports=H$("String","trimLeft")});var iS=f((Dq,tS)=>{"use strict";var j$=eS();tS.exports=j$});var aS=f((Cq,rS)=>{"use strict";var Q$=iS();rS.exports=Q$});var yS=f(()=>{"use strict"});var TS=f(()=>{"use strict"});var ES=f((mH,IS)=>{"use strict";var mM=De(),fM=Xt(),bM=pe(),gM=bM("match");IS.exports=function(a){var e;return mM(a)&&((e=a[gM])!==void 0?!!e:fM(a)==="RegExp")}});var PS=f((fH,xS)=>{"use strict";var vM=tt();xS.exports=function(){var a=vM(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 kS=f((bH,AS)=>{"use strict";var SM=Me(),yM=Ge(),TM=fr(),IM=PS(),wS=RegExp.prototype;AS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in wS)&&!yM(a,"flags")&&TM(wS,a)?SM(IM,a):e}});var LS=f((gH,RS)=>{"use strict";var kl=ne(),EM=wi(),xM=Math.floor,wl=kl("".charAt),PM=kl("".replace),Al=kl("".slice),wM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,AM=/\$([$&'`]|\d{1,2})/g;RS.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=AM;return r!==void 0&&(r=EM(r),u=wM),PM(s,u,function(l,c){var d;switch(wl(c,0)){case"$":return"$";case"&":return a;case"`":return Al(e,0,t);case"'":return Al(e,n);case"<":d=r[Al(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=xM(h/10);return p===0?l:p<=o?i[p-1]===void 0?wl(c,1):i[p-1]+wl(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var DS=f(()=>{"use strict";var kM=se(),RM=Me(),Ll=ne(),$S=At(),LM=ee(),$M=xi(),MM=ES(),Ki=Xr(),DM=gr(),CM=kS(),VM=LS(),OM=pe(),BM=Qe(),_M=OM("replace"),NM=TypeError,Rl=Ll("".indexOf),FM=Ll("".replace),MS=Ll("".slice),qM=Math.max;kM({target:"String",proto:!0},{replaceAll:function(e,t){var i=$S(this),r,s,n,o,u,l,c,d,h,p,m=0,b="";if(!$M(e)){if(r=MM(e),r&&(s=Ki($S(CM(e))),!~Rl(s,"g")))throw new NM("`.replaceAll` does not allow non-global regexes");if(n=DM(e,_M),n)return RM(n,e,i,t);if(BM&&r)return FM(Ki(i),e,t)}for(o=Ki(i),u=Ki(e),l=LM(t),l||(t=Ki(t)),c=u.length,d=qM(1,c),h=Rl(o,u);h!==-1;)p=l?Ki(t(u,h,o)):VM(u,o,h,[],void 0,t),b+=MS(o,m,h)+p,m=h+c,h=h+d>o.length?-1:Rl(o,u,h+d);return m<o.length&&(b+=MS(o,m)),b}})});var VS=f((yH,CS)=>{"use strict";yS();TS();DS();var UM=kt();CS.exports=UM("String","replaceAll")});var BS=f((TH,OS)=>{"use strict";var HM=VS();OS.exports=HM});var NS=f((IH,_S)=>{"use strict";var jM=BS();_S.exports=jM});var qS=f((EH,FS)=>{"use strict";var QM=Tr(),GM=Xr(),WM=At(),YM=RangeError;FS.exports=function(e){var t=GM(WM(this)),i="",r=QM(e);if(r<0||r===1/0)throw new YM("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var GS=f((xH,QS)=>{"use strict";var jS=ne(),zM=ko(),US=Xr(),KM=qS(),XM=At(),JM=jS(KM),ZM=jS("".slice),eD=Math.ceil,HS=function(a){return function(e,t,i){var r=US(XM(e)),s=zM(t),n=r.length,o=i===void 0?" ":US(i),u,l;return s<=n||o===""?r:(u=s-n,l=JM(o,eD(u/o.length)),l.length>u&&(l=ZM(l,0,u)),a?r+l:l+r)}};QS.exports={start:HS(!1),end:HS(!0)}});var YS=f((PH,WS)=>{"use strict";var tD=Zt();WS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(tD)});var zS=f(()=>{"use strict";var iD=se(),rD=GS().start,aD=YS();iD({target:"String",proto:!0,forced:aD},{padStart:function(e){return rD(this,e,arguments.length>1?arguments[1]:void 0)}})});var XS=f((kH,KS)=>{"use strict";zS();var sD=kt();KS.exports=sD("String","padStart")});var ZS=f((RH,JS)=>{"use strict";var nD=XS();JS.exports=nD});var ty=f((LH,ey)=>{"use strict";var oD=ZS();ey.exports=oD});var od="2.0.130-dev.afe0f37e.0";var Le=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Le||{}),lt=(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))(lt||{});var us=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(us||{}),Kn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Kn||{});var Xn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Xn||{}),ls=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ls||{});var OT=D(Be(),1);import{assertNever as sh,assertNonNullable as gx,isNonNullable as ms,ValueSubject as Lo,Subject as vx,Subscription as Sx,merge as yx,observableFrom as Tx,fromEvent as th,map as ih,tap as rh,filterChanged as Ix,isNullable as $o,ErrorCategory as ah}from"@vkontakte/videoplayer-shared/es2018";var eh=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var fs=class{constructor(e){this.connection$=new Lo(void 0);this.castState$=new Lo("NOT_AVAILABLE");this.errorEvent$=new vx;this.realCastState$=new Lo("NOT_AVAILABLE");this.subscription=new Sx;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 i=ms((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||eh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ah.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 i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ms(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();$o(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();$o(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),i=cast.framework.CastContext.getInstance();this.subscription.add(th(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.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 sh(r.sessionState)}})).add(yx(th(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(rh(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),ih(r=>r.castState)),Tx([i.getCastState()])).pipe(Ix(),ih(Ex),rh(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=ms(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();gx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;($o(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(r==="CONNECTED"?ms(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:ah.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Ex=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 sh(a)}};var mc=D(Be(),1),vT=D(Di(),1),ST=D(au(),1);var lg=D(Hs(),1);import{assertNever as eg}from"@vkontakte/videoplayer-shared/es2018";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 i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:eg(t)}return a},js=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:eg(e)}};var w=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as $R,Subject as Qs,merge as tg}from"@vkontakte/videoplayer-shared/es2018";var C=class{constructor(e){this.transitionStarted$=new Qs;this.transitionEnded$=new Qs;this.transitionUpdated$=new Qs;this.forceChanged$=new Qs;this.stateChangeStarted$=tg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=tg(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||$R(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as MR}from"@vkontakte/videoplayer-shared/es2018";var ig=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 MR(a)}};import{assertNever as Hi,assertNonNullable as ni,debounce as rg,ErrorCategory as ag,fromEvent as oi,isNonNullable as sg,map as ng,merge as og,observableFrom as DR,Subject as CR,Subscription as ju,timeout as VR,getHighestQuality as OR}from"@vkontakte/videoplayer-shared/es2018";var BR=5,_R=5,NR=500,ug=7e3,Vr=class{constructor(e){this.subscription=new ju;this.loadMediaTimeoutSubscription=new ju;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Hi(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:Hi(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:Hi(e)}break}default:Hi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ig(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 ju;this.subscription.add(e),this.subscription.add(og(this.videoState.stateChangeStarted$.pipe(ng(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(ng(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new CR;e.add(r.pipe(rg(NR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(oi(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)>BR)&&r.next(o),s=o})),e.add(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.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<_R&&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:Hi(n)}}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=og(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,DR(["init"])).pipe(rg(0));t(i,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 i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?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),i=this.createLoadRequest(t);this.loadMedia(i)}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 r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];ni(c);let d=OR(Object.keys(c));ni(d);let h=c[d];ni(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];ni(c),i=c.url,r="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];ni(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];ni(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];ni(c),i=he(c.url),r="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:ag.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Hi(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return sg(o)&&(n.metadata.title=o),sg(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(VR(ug).subscribe(()=>s(`timeout(${ug})`)))});(0,lg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ag.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var hl=D(Be(),1);import{clearVideoElement as dg}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as FR}from"@vkontakte/videoplayer-shared/es2018";var cg=a=>{try{a.pause(),a.playbackRate=0,FR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as qR,Subscription as UR}from"@vkontakte/videoplayer-shared/es2018";var Qu=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)}},Gu=window.WeakMap?new WeakMap:new Qu,Wu=window.WeakMap?new WeakMap:new Map,HR=(a,e=20)=>{let t=0;return qR(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?dg(i):(i=document.createElement("video"),a.appendChild(i)),Gu.set(i,r);let s=new UR;return s.add(HR(i,e)),Wu.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},xe=a=>{let e=Wu.get(a);e==null||e.unsubscribe(),Wu.delete(a);let t=Gu.get(a);Gu.delete(a),t?dg(a):cg(a)};var zu=D(ji(),1);import{assertNonNullable as Or,isNonNullable as rt,isNullable as XR,fromEvent as Qi,merge as vg,observableFrom as Sg,filterChanged as yg,map as Br,Subject as Tg,Subscription as JR,ValueSubject as ZR,ErrorCategory as eL}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Yu,isNullable as zR,Subscription as KR}from"@vkontakte/videoplayer-shared/es2018";var Gs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=zR(r),l=new KR;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},it=(a,e,t)=>Gs(e,()=>a.loop,i=>{Yu(i)&&(a.loop=i)},{onError:t}),Pe=(a,e,t,i)=>Gs(e,()=>({muted:a.muted,volume:a.volume}),r=>{Yu(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),_e=(a,e,t,i)=>Gs(e,()=>a.playbackRate,r=>{Yu(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Lt=Gs;var tL=a=>["__",a.language,a.label].join("|"),iL=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Ku=class a{constructor(e){this.available$=new Tg;this.current$=new ZR(void 0);this.error$=new Tg;this.subscription=new JR;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:eL.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Lt(t.internalTextTracks,()=>(0,zu.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Br(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Lt(t.externalTextTracks,()=>(0,zu.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Br(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Lt(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:r})),this.subscription.add(Lt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Or(this.video);let{textTracks:e}=this.video;this.subscription.add(Qi(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(vg(Qi(e,"addtrack"),Qi(e,"removetrack"),Sg(["init"])).pipe(Br(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),yg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(vg(Qi(e,"change"),Sg(["init"])).pipe(Br(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Br(i=>i&&this.htmlTextTrackToITextTrack(i).id),yg()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Qi(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Qi(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;rt(t.align)&&(r.align=t.align),rt(t.position)&&(r.position=t.position),rt(t.size)&&(r.size=t.size),rt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Or(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:i}=e,r=e.id?e.id:tL(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Or(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(XR(e)||!iL(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){Or(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){Or(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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)}},Ne=Ku;var ui=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 Ig=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},Xu=a=>{let e=Ig(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Eg=a=>{let e=Ig(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as we,map as $t,merge as Zu,filterChanged as dL,isNonNullable as Mg,Subject as pL,filter as Nr,mapTo as el,combine as hL,once as mL,throttle as fL,ErrorCategory as bL,ValueSubject as Dg,Subscription as gL}from"@vkontakte/videoplayer-shared/es2018";var rL=3,xg=(a,e,t=rL)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Ws=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,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/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||i||n||u||l||r||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 i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var Pg=D(Be(),1);var _r=()=>{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 Ys=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,Pg.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=_r()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e){let t=await 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,i=/iphone/i.test(e)?"iPhone":void 0,r=/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||i||r||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 i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var zs=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(i){console.error(i)}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(i){console.error(i)}}};var Ye=()=>window.ManagedMediaSource||window.MediaSource,Ks=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},wg=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ag=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var aL=document.createElement("video"),sL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',nL='video/mp4; codecs="hev1.1.6.L93.B0"',kg='video/webm; codecs="vp09.00.10.08"',Rg='video/webm; codecs="av01.0.00M.08"',oL='audio/mp4; codecs="mp4a.40.2"',uL='audio/webm; codecs="opus"',Lg,lL=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Rg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:kg}})]);Lg={DASH_WEBM_AV1:e,DASH_WEBM:t}};lL().catch(a=>{console.log(aL),console.error(a)});var Xs=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 Lg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,h,p,m,b,g,v,S,y,E;this._video=document.createElement("video");try{this._protocols={mms:Ks(),mse:wg(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"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 T=!!((c=(l=Ye())==null?void 0:l.isTypeSupported)!=null&&c.call(l,sL)),k=!!((h=(d=Ye())==null?void 0:d.isTypeSupported)!=null&&h.call(d,nL)),B=!!((m=(p=Ye())==null?void 0:p.isTypeSupported)!=null&&m.call(p,oL));this._codecs={h264:T,h265:k,vp9:!!((g=(b=Ye())==null?void 0:b.isTypeSupported)!=null&&g.call(b,kg)),av1:!!((S=(v=Ye())==null?void 0:v.isTypeSupported)!=null&&S.call(v,Rg)),aac:B,opus:!!((E=(y=Ye())==null?void 0:y.isTypeSupported)!=null&&E.call(y,uL)),mpeg:(T||k)&&B},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}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 $g="audio/mpeg",Js=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,$g))},this._codecs={mp3:!!((r=(i=Ye())==null?void 0:i.isTypeSupported)!=null&&r.call(i,$g))}}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 cL}from"@vkontakte/videoplayer-shared/es2018";var Ju=class{constructor(){this.isInited$=new cL(!1);this._displayChecker=new zs,this._deviceChecker=new Ys(this._displayChecker),this._browserChecker=new Ws,this._videoChecker=new Xs(this._deviceChecker,this._browserChecker),this._audioChecker=new Js,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}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},N=new Ju;var Ae=a=>{let e=A=>we(a,A).pipe(el(void 0)),t=new gL,i=()=>t.unsubscribe(),s=Zu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>we(a,A))).pipe($t(A=>A.type==="ended"?a.readyState<2:a.readyState<3),dL()),n=Zu(we(a,"progress"),we(a,"timeupdate")).pipe($t(()=>xg(a.buffered,a.currentTime))),o=N.browser.isSafari?hL({play:e("play").pipe(mL()),playing:e("playing")}).pipe(el(void 0)):e("playing"),u=we(a,"volumechange").pipe($t(()=>({muted:a.muted,volume:a.volume}))),l=we(a,"ratechange").pipe($t(()=>a.playbackRate)),c=we(a,"error").pipe(Nr(()=>!!(a.error||a.played.length)),$t(()=>{var q;let A=a.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:bL.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:(q=a.error)!=null?q:void 0}})),d=we(a,"timeupdate").pipe($t(()=>a.currentTime)),h=new pL,p=.3,m;t.add(d.subscribe(A=>{a.loop&&Mg(m)&&Mg(A)&&m>=a.duration-p&&A<=p&&h.next(m),m=A}));let b=e("pause").pipe(Nr(()=>!a.error&&m!==a.duration)),g=we(a,"enterpictureinpicture"),v=we(a,"leavepictureinpicture"),S=new Dg(Eg(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new Dg(Xu(a)),E=we(a,"fullscreenchange");t.add(E.pipe($t(()=>Xu(a))).subscribe(y));let T=.1,k=1e3,B=we(a,"timeupdate").pipe(Nr(A=>a.duration-a.currentTime<T)),O=Zu(B.pipe(Nr(A=>!a.loop)),we(a,"ended")).pipe(fL(k),el(void 0)),_=B.pipe(Nr(A=>a.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:O,looped$:h,loopExpected$:_,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:we(a,"durationchange").pipe($t(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:S,inFullscreen$:y,enterPip$:g,leavePip$:v,destroy:i}};import{VideoQuality as Mt}from"@vkontakte/videoplayer-shared/es2018";var Dt=a=>{switch(a){case"mobile":return Mt.Q_144P;case"lowest":return Mt.Q_240P;case"low":return Mt.Q_360P;case"sd":case"medium":return Mt.Q_480P;case"hd":case"high":return Mt.Q_720P;case"fullhd":case"full":return Mt.Q_1080P;case"quadhd":case"quad":return Mt.Q_1440P;case"ultrahd":case"ultra":return Mt.Q_2160P}};var Vt=D(Ct(),1),zg=D(Be(),1),tn=D(Di(),1);import{isNonNullable as Se,isNullable as Qg,now as Kg,isHigher as Gg,isHigherOrEqual as al,isInvariantQuality as Wg,isLowerOrEqual as sl,videoSizeToQuality as kL,assertNotEmptyArray as Xg,assertNonNullable as RL}from"@vkontakte/videoplayer-shared/es2018";var tl=!1,ht={},Fg=a=>{tl=a},qg=()=>{ht={}},Ug=a=>{a(ht)},Fr=(a,e)=>{var t;tl&&(ht.meta=(t=ht.meta)!=null?t:{},ht.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var i,r;if(!tl)return;ht.series=(i=ht.series)!=null?i:{};let t=(r=ht.series[this.name])!=null?r:[];t.push([Date.now(),e]),ht.series[this.name]=t}};import{isHigher as wL,isHigherOrEqual as MN,isLower as Hg,isLowerOrEqual as DN,isNonNullable as Zs,isNullable as AL,videoHeightToQuality as en}from"@vkontakte/videoplayer-shared/es2018";function il({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function rl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&il({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function qr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return AL(a)||Zs(a.min)&&Zs(a.max)&&Hg(a.max,a.min)||Zs(a.min)&&e&&wL(a.min,e)||Zs(a.max)&&t&&Hg(a.max,t)}function jg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return qr({limits:{max:a!=null&&a.max?en(a.max):void 0,min:a!=null&&a.min?en(a.min):void 0},highestAvailableQuality:e?en(e):void 0,lowestAvailableQuality:t?en(t):void 0})}var LL=new ve("best_bitrate"),Jg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var nl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ur=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Kg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Zg='Assertion "ABR Tracks is empty array" failed',rn=(a,e,t,i)=>{var u;let r=[...e].sort(nl(1)),s=[...t].sort(nl(1)),n=s.filter(l=>Se(l.bitrate)&&Se(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Vt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Vt.default)(s,-1);return o&&(0,zg.default)(n,o)?o:n.length?(0,Vt.default)(n,-1):(0,Vt.default)(s,0)},Yg=a=>"quality"in a,ev=(a,e,t,i)=>{var n;let r=Se((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&Se(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Kg()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Yg(o)?"video":"audio",l=Yg(o)?o.quality:o.bitrate;return e({message:`
6
+ var QT=Object.create;var od=Object.defineProperty;var GT=Object.getOwnPropertyDescriptor;var WT=Object.getOwnPropertyNames;var YT=Object.getPrototypeOf,zT=Object.prototype.hasOwnProperty;var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var KT=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of WT(e))!zT.call(a,r)&&r!==t&&od(a,r,{get:()=>e[r],enumerable:!(i=GT(e,r))||i.enumerable});return a};var D=(a,e,t)=>(t=a!=null?QT(YT(a)):{},KT(e||!a||!a.__esModule?od(t,"default",{value:a,enumerable:!0}):t,a));var re=f((Jn,ld)=>{"use strict";var pr=function(a){return a&&a.Math===Math&&a};ld.exports=pr(typeof globalThis=="object"&&globalThis)||pr(typeof window=="object"&&window)||pr(typeof self=="object"&&self)||pr(typeof global=="object"&&global)||pr(typeof Jn=="object"&&Jn)||function(){return this}()||Function("return this")()});var de=f((P0,cd)=>{"use strict";cd.exports=function(a){try{return!!a()}catch(e){return!0}}});var hr=f((w0,dd)=>{"use strict";var XT=de();dd.exports=!XT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Zn=f((A0,fd)=>{"use strict";var JT=hr(),md=Function.prototype,pd=md.apply,hd=md.call;fd.exports=typeof Reflect=="object"&&Reflect.apply||(JT?hd.bind(pd):function(){return hd.apply(pd,arguments)})});var ne=f((k0,vd)=>{"use strict";var bd=hr(),gd=Function.prototype,eo=gd.call,ZT=bd&&gd.bind.bind(eo,eo);vd.exports=bd?ZT:function(a){return function(){return eo.apply(a,arguments)}}});var Xt=f((R0,yd)=>{"use strict";var Sd=ne(),eI=Sd({}.toString),tI=Sd("".slice);yd.exports=function(a){return tI(eI(a),8,-1)}});var to=f((L0,Td)=>{"use strict";var iI=Xt(),rI=ne();Td.exports=function(a){if(iI(a)==="Function")return rI(a)}});var ee=f(($0,Id)=>{"use strict";var io=typeof document=="object"&&document.all;Id.exports=typeof io=="undefined"&&io!==void 0?function(a){return typeof a=="function"||a===io}:function(a){return typeof a=="function"}});var $e=f((M0,Ed)=>{"use strict";var aI=de();Ed.exports=!aI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Me=f((D0,xd)=>{"use strict";var sI=hr(),cs=Function.prototype.call;xd.exports=sI?cs.bind(cs):function(){return cs.apply(cs,arguments)}});var ro=f(Ad=>{"use strict";var Pd={}.propertyIsEnumerable,wd=Object.getOwnPropertyDescriptor,nI=wd&&!Pd.call({1:2},1);Ad.f=nI?function(e){var t=wd(this,e);return!!t&&t.enumerable}:Pd});var mr=f((V0,kd)=>{"use strict";kd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ld=f((O0,Rd)=>{"use strict";var oI=ne(),uI=de(),lI=Xt(),ao=Object,cI=oI("".split);Rd.exports=uI(function(){return!ao("z").propertyIsEnumerable(0)})?function(a){return lI(a)==="String"?cI(a,""):ao(a)}:ao});var xi=f((B0,$d)=>{"use strict";$d.exports=function(a){return a==null}});var At=f((_0,Md)=>{"use strict";var dI=xi(),pI=TypeError;Md.exports=function(a){if(dI(a))throw new pI("Can't call method on "+a);return a}});var Jt=f((N0,Dd)=>{"use strict";var hI=Ld(),mI=At();Dd.exports=function(a){return hI(mI(a))}});var De=f((F0,Cd)=>{"use strict";var fI=ee();Cd.exports=function(a){return typeof a=="object"?a!==null:fI(a)}});var Pi=f((q0,Vd)=>{"use strict";Vd.exports={}});var ct=f((U0,Bd)=>{"use strict";var so=Pi(),no=re(),bI=ee(),Od=function(a){return bI(a)?a:void 0};Bd.exports=function(a,e){return arguments.length<2?Od(so[a])||Od(no[a]):so[a]&&so[a][e]||no[a]&&no[a][e]}});var fr=f((H0,_d)=>{"use strict";var gI=ne();_d.exports=gI({}.isPrototypeOf)});var Zt=f((j0,qd)=>{"use strict";var vI=re(),Nd=vI.navigator,Fd=Nd&&Nd.userAgent;qd.exports=Fd?String(Fd):""});var uo=f((Q0,Wd)=>{"use strict";var Gd=re(),oo=Zt(),Ud=Gd.process,Hd=Gd.Deno,jd=Ud&&Ud.versions||Hd&&Hd.version,Qd=jd&&jd.v8,je,ds;Qd&&(je=Qd.split("."),ds=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!ds&&oo&&(je=oo.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=oo.match(/Chrome\/(\d+)/),je&&(ds=+je[1])));Wd.exports=ds});var lo=f((G0,zd)=>{"use strict";var Yd=uo(),SI=de(),yI=re(),TI=yI.String;zd.exports=!!Object.getOwnPropertySymbols&&!SI(function(){var a=Symbol("symbol detection");return!TI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Yd&&Yd<41})});var co=f((W0,Kd)=>{"use strict";var II=lo();Kd.exports=II&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var po=f((Y0,Xd)=>{"use strict";var EI=ct(),xI=ee(),PI=fr(),wI=co(),AI=Object;Xd.exports=wI?function(a){return typeof a=="symbol"}:function(a){var e=EI("Symbol");return xI(e)&&PI(e.prototype,AI(a))}});var br=f((z0,Jd)=>{"use strict";var kI=String;Jd.exports=function(a){try{return kI(a)}catch(e){return"Object"}}});var et=f((K0,Zd)=>{"use strict";var RI=ee(),LI=br(),$I=TypeError;Zd.exports=function(a){if(RI(a))return a;throw new $I(LI(a)+" is not a function")}});var gr=f((X0,ep)=>{"use strict";var MI=et(),DI=xi();ep.exports=function(a,e){var t=a[e];return DI(t)?void 0:MI(t)}});var ip=f((J0,tp)=>{"use strict";var ho=Me(),mo=ee(),fo=De(),CI=TypeError;tp.exports=function(a,e){var t,i;if(e==="string"&&mo(t=a.toString)&&!fo(i=ho(t,a))||mo(t=a.valueOf)&&!fo(i=ho(t,a))||e!=="string"&&mo(t=a.toString)&&!fo(i=ho(t,a)))return i;throw new CI("Can't convert object to primitive value")}});var Qe=f((Z0,rp)=>{"use strict";rp.exports=!0});var np=f((eV,sp)=>{"use strict";var ap=re(),VI=Object.defineProperty;sp.exports=function(a,e){try{VI(ap,a,{value:e,configurable:!0,writable:!0})}catch(t){ap[a]=e}return e}});var vr=f((tV,lp)=>{"use strict";var OI=Qe(),BI=re(),_I=np(),op="__core-js_shared__",up=lp.exports=BI[op]||_I(op,{});(up.versions||(up.versions=[])).push({version:"3.38.0",mode:OI?"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 bo=f((iV,dp)=>{"use strict";var cp=vr();dp.exports=function(a,e){return cp[a]||(cp[a]=e||{})}});var wi=f((rV,pp)=>{"use strict";var NI=At(),FI=Object;pp.exports=function(a){return FI(NI(a))}});var Ge=f((aV,hp)=>{"use strict";var qI=ne(),UI=wi(),HI=qI({}.hasOwnProperty);hp.exports=Object.hasOwn||function(e,t){return HI(UI(e),t)}});var go=f((sV,mp)=>{"use strict";var jI=ne(),QI=0,GI=Math.random(),WI=jI(1 .toString);mp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+WI(++QI+GI,36)}});var pe=f((nV,bp)=>{"use strict";var YI=re(),zI=bo(),fp=Ge(),KI=go(),XI=lo(),JI=co(),Ai=YI.Symbol,vo=zI("wks"),ZI=JI?Ai.for||Ai:Ai&&Ai.withoutSetter||KI;bp.exports=function(a){return fp(vo,a)||(vo[a]=XI&&fp(Ai,a)?Ai[a]:ZI("Symbol."+a)),vo[a]}});var yp=f((oV,Sp)=>{"use strict";var eE=Me(),gp=De(),vp=po(),tE=gr(),iE=ip(),rE=pe(),aE=TypeError,sE=rE("toPrimitive");Sp.exports=function(a,e){if(!gp(a)||vp(a))return a;var t=tE(a,sE),i;if(t){if(e===void 0&&(e="default"),i=eE(t,a,e),!gp(i)||vp(i))return i;throw new aE("Can't convert object to primitive value")}return e===void 0&&(e="number"),iE(a,e)}});var So=f((uV,Tp)=>{"use strict";var nE=yp(),oE=po();Tp.exports=function(a){var e=nE(a,"string");return oE(e)?e:e+""}});var ps=f((lV,Ep)=>{"use strict";var uE=re(),Ip=De(),yo=uE.document,lE=Ip(yo)&&Ip(yo.createElement);Ep.exports=function(a){return lE?yo.createElement(a):{}}});var To=f((cV,xp)=>{"use strict";var cE=$e(),dE=de(),pE=ps();xp.exports=!cE&&!dE(function(){return Object.defineProperty(pE("div"),"a",{get:function(){return 7}}).a!==7})});var Ap=f(wp=>{"use strict";var hE=$e(),mE=Me(),fE=ro(),bE=mr(),gE=Jt(),vE=So(),SE=Ge(),yE=To(),Pp=Object.getOwnPropertyDescriptor;wp.f=hE?Pp:function(e,t){if(e=gE(e),t=vE(t),yE)try{return Pp(e,t)}catch(i){}if(SE(e,t))return bE(!mE(fE.f,e,t),e[t])}});var Io=f((pV,kp)=>{"use strict";var TE=de(),IE=ee(),EE=/#|\.prototype\./,Sr=function(a,e){var t=PE[xE(a)];return t===AE?!0:t===wE?!1:IE(e)?TE(e):!!e},xE=Sr.normalize=function(a){return String(a).replace(EE,".").toLowerCase()},PE=Sr.data={},wE=Sr.NATIVE="N",AE=Sr.POLYFILL="P";kp.exports=Sr});var ki=f((hV,Lp)=>{"use strict";var Rp=to(),kE=et(),RE=hr(),LE=Rp(Rp.bind);Lp.exports=function(a,e){return kE(a),e===void 0?a:RE?LE(a,e):function(){return a.apply(e,arguments)}}});var Eo=f((mV,$p)=>{"use strict";var $E=$e(),ME=de();$p.exports=$E&&ME(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var tt=f((fV,Mp)=>{"use strict";var DE=De(),CE=String,VE=TypeError;Mp.exports=function(a){if(DE(a))return a;throw new VE(CE(a)+" is not an object")}});var ei=f(Cp=>{"use strict";var OE=$e(),BE=To(),_E=Eo(),hs=tt(),Dp=So(),NE=TypeError,xo=Object.defineProperty,FE=Object.getOwnPropertyDescriptor,Po="enumerable",wo="configurable",Ao="writable";Cp.f=OE?_E?function(e,t,i){if(hs(e),t=Dp(t),hs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Ao in i&&!i[Ao]){var r=FE(e,t);r&&r[Ao]&&(e[t]=i.value,i={configurable:wo in i?i[wo]:r[wo],enumerable:Po in i?i[Po]:r[Po],writable:!1})}return xo(e,t,i)}:xo:function(e,t,i){if(hs(e),t=Dp(t),hs(i),BE)try{return xo(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new NE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ri=f((gV,Vp)=>{"use strict";var qE=$e(),UE=ei(),HE=mr();Vp.exports=qE?function(a,e,t){return UE.f(a,e,HE(1,t))}:function(a,e,t){return a[e]=t,a}});var se=f((vV,Bp)=>{"use strict";var yr=re(),jE=Zn(),QE=to(),GE=ee(),WE=Ap().f,YE=Io(),Li=Pi(),zE=ki(),$i=Ri(),Op=Ge();vr();var KE=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return jE(a,this,arguments)};return e.prototype=a.prototype,e};Bp.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?yr:r?yr[t]:yr[t]&&yr[t].prototype,o=i?Li:Li[t]||$i(Li,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,v;for(h in e)l=YE(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Op(n,h),m=o[h],c&&(a.dontCallGetSet?(v=WE(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?g=zE(p,yr):a.wrap&&c?g=KE(p):s&&GE(p)?g=QE(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&$i(g,"sham",!0),$i(o,h,g),s&&(d=t+"Prototype",Op(Li,d)||$i(Li,d,{}),$i(Li[d],h,p),a.real&&u&&(l||!u[h])&&$i(u,h,p)))}});var Np=f((SV,_p)=>{"use strict";var XE=Math.ceil,JE=Math.floor;_p.exports=Math.trunc||function(e){var t=+e;return(t>0?JE:XE)(t)}});var Tr=f((yV,Fp)=>{"use strict";var ZE=Np();Fp.exports=function(a){var e=+a;return e!==e||e===0?0:ZE(e)}});var Up=f((TV,qp)=>{"use strict";var ex=Tr(),tx=Math.max,ix=Math.min;qp.exports=function(a,e){var t=ex(a);return t<0?tx(t+e,0):ix(t,e)}});var ko=f((IV,Hp)=>{"use strict";var rx=Tr(),ax=Math.min;Hp.exports=function(a){var e=rx(a);return e>0?ax(e,9007199254740991):0}});var Mi=f((EV,jp)=>{"use strict";var sx=ko();jp.exports=function(a){return sx(a.length)}});var Ro=f((xV,Gp)=>{"use strict";var nx=Jt(),ox=Up(),ux=Mi(),Qp=function(a){return function(e,t,i){var r=nx(e),s=ux(r);if(s===0)return!a&&-1;var n=ox(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Gp.exports={includes:Qp(!0),indexOf:Qp(!1)}});var Ir=f((PV,Wp)=>{"use strict";Wp.exports=function(){}});var Yp=f(()=>{"use strict";var lx=se(),cx=Ro().includes,dx=de(),px=Ir(),hx=dx(function(){return!Array(1).includes()});lx({target:"Array",proto:!0,forced:hx},{includes:function(e){return cx(this,e,arguments.length>1?arguments[1]:void 0)}});px("includes")});var kt=f((kV,zp)=>{"use strict";var mx=ct();zp.exports=mx});var Xp=f((RV,Kp)=>{"use strict";Yp();var fx=kt();Kp.exports=fx("Array","includes")});var Zp=f((LV,Jp)=>{"use strict";var bx=Xp();Jp.exports=bx});var Be=f(($V,eh)=>{"use strict";var gx=Zp();eh.exports=gx});var bs=f((HV,uh)=>{"use strict";var Px=bo(),wx=go(),oh=Px("keys");uh.exports=function(a){return oh[a]||(oh[a]=wx(a))}});var ch=f((jV,lh)=>{"use strict";var Ax=de();lh.exports=!Ax(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gs=f((QV,ph)=>{"use strict";var kx=Ge(),Rx=ee(),Lx=wi(),$x=bs(),Mx=ch(),dh=$x("IE_PROTO"),Mo=Object,Dx=Mo.prototype;ph.exports=Mx?Mo.getPrototypeOf:function(a){var e=Lx(a);if(kx(e,dh))return e[dh];var t=e.constructor;return Rx(t)&&e instanceof t?t.prototype:e instanceof Mo?Dx:null}});var vs=f((GV,hh)=>{"use strict";hh.exports={}});var bh=f((WV,fh)=>{"use strict";var Cx=ne(),Do=Ge(),Vx=Jt(),Ox=Ro().indexOf,Bx=vs(),mh=Cx([].push);fh.exports=function(a,e){var t=Vx(a),i=0,r=[],s;for(s in t)!Do(Bx,s)&&Do(t,s)&&mh(r,s);for(;e.length>i;)Do(t,s=e[i++])&&(~Ox(r,s)||mh(r,s));return r}});var Co=f((YV,gh)=>{"use strict";gh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vo=f((zV,vh)=>{"use strict";var _x=bh(),Nx=Co();vh.exports=Object.keys||function(e){return _x(e,Nx)}});var Oo=f((KV,Eh)=>{"use strict";var yh=$e(),Fx=de(),Th=ne(),qx=gs(),Ux=Vo(),Hx=Jt(),jx=ro().f,Ih=Th(jx),Qx=Th([].push),Gx=yh&&Fx(function(){var a=Object.create(null);return a[2]=2,!Ih(a,2)}),Sh=function(a){return function(e){for(var t=Hx(e),i=Ux(t),r=Gx&&qx(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!yh||(r?u in t:Ih(t,u)))&&Qx(o,a?[u,t[u]]:t[u]);return o}};Eh.exports={entries:Sh(!0),values:Sh(!1)}});var xh=f(()=>{"use strict";var Wx=se(),Yx=Oo().entries;Wx({target:"Object",stat:!0},{entries:function(e){return Yx(e)}})});var wh=f((ZV,Ph)=>{"use strict";xh();var zx=Pi();Ph.exports=zx.Object.entries});var kh=f((eO,Ah)=>{"use strict";var Kx=wh();Ah.exports=Kx});var Di=f((tO,Rh)=>{"use strict";var Xx=kh();Rh.exports=Xx});var ti=f((iO,Lh)=>{"use strict";Lh.exports={}});var Dh=f((rO,Mh)=>{"use strict";var Jx=re(),Zx=ee(),$h=Jx.WeakMap;Mh.exports=Zx($h)&&/native code/.test(String($h))});var Fo=f((aO,Oh)=>{"use strict";var eP=Dh(),Vh=re(),tP=De(),iP=Ri(),Bo=Ge(),_o=vr(),rP=bs(),aP=vs(),Ch="Object already initialized",No=Vh.TypeError,sP=Vh.WeakMap,Ss,Er,ys,nP=function(a){return ys(a)?Er(a):Ss(a,{})},oP=function(a){return function(e){var t;if(!tP(e)||(t=Er(e)).type!==a)throw new No("Incompatible receiver, "+a+" required");return t}};eP||_o.state?(We=_o.state||(_o.state=new sP),We.get=We.get,We.has=We.has,We.set=We.set,Ss=function(a,e){if(We.has(a))throw new No(Ch);return e.facade=a,We.set(a,e),e},Er=function(a){return We.get(a)||{}},ys=function(a){return We.has(a)}):(ii=rP("state"),aP[ii]=!0,Ss=function(a,e){if(Bo(a,ii))throw new No(Ch);return e.facade=a,iP(a,ii,e),e},Er=function(a){return Bo(a,ii)?a[ii]:{}},ys=function(a){return Bo(a,ii)});var We,ii;Oh.exports={set:Ss,get:Er,has:ys,enforce:nP,getterFor:oP}});var Ho=f((sO,_h)=>{"use strict";var qo=$e(),uP=Ge(),Bh=Function.prototype,lP=qo&&Object.getOwnPropertyDescriptor,Uo=uP(Bh,"name"),cP=Uo&&function(){}.name==="something",dP=Uo&&(!qo||qo&&lP(Bh,"name").configurable);_h.exports={EXISTS:Uo,PROPER:cP,CONFIGURABLE:dP}});var Fh=f(Nh=>{"use strict";var pP=$e(),hP=Eo(),mP=ei(),fP=tt(),bP=Jt(),gP=Vo();Nh.f=pP&&!hP?Object.defineProperties:function(e,t){fP(e);for(var i=bP(t),r=gP(t),s=r.length,n=0,o;s>n;)mP.f(e,o=r[n++],i[o]);return e}});var jo=f((oO,qh)=>{"use strict";var vP=ct();qh.exports=vP("document","documentElement")});var Yo=f((uO,Yh)=>{"use strict";var SP=tt(),yP=Fh(),Uh=Co(),TP=vs(),IP=jo(),EP=ps(),xP=bs(),Hh=">",jh="<",Go="prototype",Wo="script",Gh=xP("IE_PROTO"),Qo=function(){},Wh=function(a){return jh+Wo+Hh+a+jh+"/"+Wo+Hh},Qh=function(a){a.write(Wh("")),a.close();var e=a.parentWindow.Object;return a=null,e},PP=function(){var a=EP("iframe"),e="java"+Wo+":",t;return a.style.display="none",IP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Wh("document.F=Object")),t.close(),t.F},Ts,Is=function(){try{Ts=new ActiveXObject("htmlfile")}catch(e){}Is=typeof document!="undefined"?document.domain&&Ts?Qh(Ts):PP():Qh(Ts);for(var a=Uh.length;a--;)delete Is[Go][Uh[a]];return Is()};TP[Gh]=!0;Yh.exports=Object.create||function(e,t){var i;return e!==null?(Qo[Go]=SP(e),i=new Qo,Qo[Go]=null,i[Gh]=e):i=Is(),t===void 0?i:yP.f(i,t)}});var Ci=f((lO,zh)=>{"use strict";var wP=Ri();zh.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:wP(a,e,t),a}});var Jo=f((cO,Jh)=>{"use strict";var AP=de(),kP=ee(),RP=De(),LP=Yo(),Kh=gs(),$P=Ci(),MP=pe(),DP=Qe(),Xo=MP("iterator"),Xh=!1,dt,zo,Ko;[].keys&&(Ko=[].keys(),"next"in Ko?(zo=Kh(Kh(Ko)),zo!==Object.prototype&&(dt=zo)):Xh=!0);var CP=!RP(dt)||AP(function(){var a={};return dt[Xo].call(a)!==a});CP?dt={}:DP&&(dt=LP(dt));kP(dt[Xo])||$P(dt,Xo,function(){return this});Jh.exports={IteratorPrototype:dt,BUGGY_SAFARI_ITERATORS:Xh}});var Es=f((dO,em)=>{"use strict";var VP=pe(),OP=VP("toStringTag"),Zh={};Zh[OP]="z";em.exports=String(Zh)==="[object z]"});var xr=f((pO,tm)=>{"use strict";var BP=Es(),_P=ee(),xs=Xt(),NP=pe(),FP=NP("toStringTag"),qP=Object,UP=xs(function(){return arguments}())==="Arguments",HP=function(a,e){try{return a[e]}catch(t){}};tm.exports=BP?xs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=HP(e=qP(a),FP))=="string"?t:UP?xs(e):(i=xs(e))==="Object"&&_P(e.callee)?"Arguments":i}});var rm=f((hO,im)=>{"use strict";var jP=Es(),QP=xr();im.exports=jP?{}.toString:function(){return"[object "+QP(this)+"]"}});var Pr=f((mO,sm)=>{"use strict";var GP=Es(),WP=ei().f,YP=Ri(),zP=Ge(),KP=rm(),XP=pe(),am=XP("toStringTag");sm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(zP(r,am)||WP(r,am,{configurable:!0,value:e}),i&&!GP&&YP(r,"toString",KP))}});var om=f((fO,nm)=>{"use strict";var JP=Jo().IteratorPrototype,ZP=Yo(),ew=mr(),tw=Pr(),iw=ti(),rw=function(){return this};nm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=ZP(JP,{next:ew(+!i,t)}),tw(a,r,!1,!0),iw[r]=rw,a}});var lm=f((bO,um)=>{"use strict";var aw=ne(),sw=et();um.exports=function(a,e,t){try{return aw(sw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var dm=f((gO,cm)=>{"use strict";var nw=De();cm.exports=function(a){return nw(a)||a===null}});var hm=f((vO,pm)=>{"use strict";var ow=dm(),uw=String,lw=TypeError;pm.exports=function(a){if(ow(a))return a;throw new lw("Can't set "+uw(a)+" as a prototype")}});var Zo=f((SO,mm)=>{"use strict";var cw=lm(),dw=De(),pw=At(),hw=hm();mm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=cw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return pw(r),hw(s),dw(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Pm=f((yO,xm)=>{"use strict";var mw=se(),fw=Me(),Ps=Qe(),Im=Ho(),bw=ee(),gw=om(),fm=gs(),bm=Zo(),vw=Pr(),Sw=Ri(),eu=Ci(),yw=pe(),gm=ti(),Em=Jo(),Tw=Im.PROPER,Iw=Im.CONFIGURABLE,vm=Em.IteratorPrototype,ws=Em.BUGGY_SAFARI_ITERATORS,wr=yw("iterator"),Sm="keys",Ar="values",ym="entries",Tm=function(){return this};xm.exports=function(a,e,t,i,r,s,n){gw(t,e,i);var o=function(v){if(v===r&&h)return h;if(!ws&&v&&v in c)return c[v];switch(v){case Sm:return function(){return new t(this,v)};case Ar:return function(){return new t(this,v)};case ym:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[wr]||c["@@iterator"]||r&&c[r],h=!ws&&d||o(r),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=fm(p.call(new a)),m!==Object.prototype&&m.next&&(!Ps&&fm(m)!==vm&&(bm?bm(m,vm):bw(m[wr])||eu(m,wr,Tm)),vw(m,u,!0,!0),Ps&&(gm[u]=Tm))),Tw&&r===Ar&&d&&d.name!==Ar&&(!Ps&&Iw?Sw(c,"name",Ar):(l=!0,h=function(){return fw(d,this)})),r)if(b={values:o(Ar),keys:s?h:o(Sm),entries:o(ym)},n)for(g in b)(ws||l||!(g in c))&&eu(c,g,b[g]);else mw({target:e,proto:!0,forced:ws||l},b);return(!Ps||n)&&c[wr]!==h&&eu(c,wr,h,{name:r}),gm[e]=h,b}});var Am=f((TO,wm)=>{"use strict";wm.exports=function(a,e){return{value:a,done:e}}});var iu=f((IO,Mm)=>{"use strict";var Ew=Jt(),tu=Ir(),km=ti(),Lm=Fo(),xw=ei().f,Pw=Pm(),As=Am(),ww=Qe(),Aw=$e(),$m="Array Iterator",kw=Lm.set,Rw=Lm.getterFor($m);Mm.exports=Pw(Array,"Array",function(a,e){kw(this,{type:$m,target:Ew(a),index:0,kind:e})},function(){var a=Rw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,As(void 0,!0);switch(a.kind){case"keys":return As(t,!1);case"values":return As(e[t],!1)}return As([t,e[t]],!1)},"values");var Rm=km.Arguments=km.Array;tu("keys");tu("values");tu("entries");if(!ww&&Aw&&Rm.name!=="values")try{xw(Rm,"name",{value:"values"})}catch(a){}});var Cm=f((EO,Dm)=>{"use strict";var Lw=pe(),$w=ti(),Mw=Lw("iterator"),Dw=Array.prototype;Dm.exports=function(a){return a!==void 0&&($w.Array===a||Dw[Mw]===a)}});var ru=f((xO,Om)=>{"use strict";var Cw=xr(),Vm=gr(),Vw=xi(),Ow=ti(),Bw=pe(),_w=Bw("iterator");Om.exports=function(a){if(!Vw(a))return Vm(a,_w)||Vm(a,"@@iterator")||Ow[Cw(a)]}});var _m=f((PO,Bm)=>{"use strict";var Nw=Me(),Fw=et(),qw=tt(),Uw=br(),Hw=ru(),jw=TypeError;Bm.exports=function(a,e){var t=arguments.length<2?Hw(a):e;if(Fw(t))return qw(Nw(t,a));throw new jw(Uw(a)+" is not iterable")}});var qm=f((wO,Fm)=>{"use strict";var Qw=Me(),Nm=tt(),Gw=gr();Fm.exports=function(a,e,t){var i,r;Nm(a);try{if(i=Gw(a,"return"),!i){if(e==="throw")throw t;return t}i=Qw(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Nm(i),t}});var Rs=f((AO,Qm)=>{"use strict";var Ww=ki(),Yw=Me(),zw=tt(),Kw=br(),Xw=Cm(),Jw=Mi(),Um=fr(),Zw=_m(),eA=ru(),Hm=qm(),tA=TypeError,ks=function(a,e){this.stopped=a,this.result=e},jm=ks.prototype;Qm.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Ww(e,i),l,c,d,h,p,m,b,g=function(S){return l&&Hm(l,"normal",S),new ks(!0,S)},v=function(S){return r?(zw(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=eA(a),!c)throw new tA(Kw(a)+" is not iterable");if(Xw(c)){for(d=0,h=Jw(a);h>d;d++)if(p=v(a[d]),p&&Um(jm,p))return p;return new ks(!1)}l=Zw(a,c)}for(m=s?a.next:l.next;!(b=Yw(m,l)).done;){try{p=v(b.value)}catch(S){Hm(l,"throw",S)}if(typeof p=="object"&&p&&Um(jm,p))return p}return new ks(!1)}});var Wm=f((kO,Gm)=>{"use strict";var iA=$e(),rA=ei(),aA=mr();Gm.exports=function(a,e,t){iA?rA.f(a,e,aA(0,t)):a[e]=t}});var Ym=f(()=>{"use strict";var sA=se(),nA=Rs(),oA=Wm();sA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return nA(e,function(i,r){oA(t,i,r)},{AS_ENTRIES:!0}),t}})});var Km=f(($O,zm)=>{"use strict";iu();Ym();var uA=Pi();zm.exports=uA.Object.fromEntries});var Jm=f((MO,Xm)=>{"use strict";Xm.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 ef=f(()=>{"use strict";iu();var lA=Jm(),cA=re(),dA=Pr(),Zm=ti();for(Ls in lA)dA(cA[Ls],Ls),Zm[Ls]=Zm.Array;var Ls});var rf=f((VO,tf)=>{"use strict";var pA=Km();ef();tf.exports=pA});var au=f((OO,af)=>{"use strict";var hA=rf();af.exports=hA});var sf=f(()=>{"use strict"});var su=f((NO,nf)=>{"use strict";var kr=re(),mA=Zt(),fA=Xt(),$s=function(a){return mA.slice(0,a.length)===a};nf.exports=function(){return $s("Bun/")?"BUN":$s("Cloudflare-Workers")?"CLOUDFLARE":$s("Deno/")?"DENO":$s("Node.js/")?"NODE":kr.Bun&&typeof Bun.version=="string"?"BUN":kr.Deno&&typeof Deno.version=="object"?"DENO":fA(kr.process)==="process"?"NODE":kr.window&&kr.document?"BROWSER":"REST"}()});var Ms=f((FO,of)=>{"use strict";var bA=su();of.exports=bA==="NODE"});var lf=f((qO,uf)=>{"use strict";var gA=ei();uf.exports=function(a,e,t){return gA.f(a,e,t)}});var pf=f((UO,df)=>{"use strict";var vA=ct(),SA=lf(),yA=pe(),TA=$e(),cf=yA("species");df.exports=function(a){var e=vA(a);TA&&e&&!e[cf]&&SA(e,cf,{configurable:!0,get:function(){return this}})}});var mf=f((HO,hf)=>{"use strict";var IA=fr(),EA=TypeError;hf.exports=function(a,e){if(IA(e,a))return a;throw new EA("Incorrect invocation")}});var ou=f((jO,ff)=>{"use strict";var xA=ne(),PA=ee(),nu=vr(),wA=xA(Function.toString);PA(nu.inspectSource)||(nu.inspectSource=function(a){return wA(a)});ff.exports=nu.inspectSource});var lu=f((QO,yf)=>{"use strict";var AA=ne(),kA=de(),bf=ee(),RA=xr(),LA=ct(),$A=ou(),gf=function(){},vf=LA("Reflect","construct"),uu=/^\s*(?:class|function)\b/,MA=AA(uu.exec),DA=!uu.test(gf),Rr=function(e){if(!bf(e))return!1;try{return vf(gf,[],e),!0}catch(t){return!1}},Sf=function(e){if(!bf(e))return!1;switch(RA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return DA||!!MA(uu,$A(e))}catch(t){return!0}};Sf.sham=!0;yf.exports=!vf||kA(function(){var a;return Rr(Rr.call)||!Rr(Object)||!Rr(function(){a=!0})||a})?Sf:Rr});var If=f((GO,Tf)=>{"use strict";var CA=lu(),VA=br(),OA=TypeError;Tf.exports=function(a){if(CA(a))return a;throw new OA(VA(a)+" is not a constructor")}});var cu=f((WO,xf)=>{"use strict";var Ef=tt(),BA=If(),_A=xi(),NA=pe(),FA=NA("species");xf.exports=function(a,e){var t=Ef(a).constructor,i;return t===void 0||_A(i=Ef(t)[FA])?e:BA(i)}});var wf=f((YO,Pf)=>{"use strict";var qA=ne();Pf.exports=qA([].slice)});var kf=f((zO,Af)=>{"use strict";var UA=TypeError;Af.exports=function(a,e){if(a<e)throw new UA("Not enough arguments");return a}});var du=f((KO,Rf)=>{"use strict";var HA=Zt();Rf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(HA)});var yu=f((XO,_f)=>{"use strict";var Ce=re(),jA=Zn(),QA=ki(),Lf=ee(),GA=Ge(),Bf=de(),$f=jo(),WA=wf(),Mf=ps(),YA=kf(),zA=du(),KA=Ms(),gu=Ce.setImmediate,vu=Ce.clearImmediate,XA=Ce.process,pu=Ce.Dispatch,JA=Ce.Function,Df=Ce.MessageChannel,ZA=Ce.String,hu=0,Lr={},Cf="onreadystatechange",$r,ri,mu,fu;Bf(function(){$r=Ce.location});var Su=function(a){if(GA(Lr,a)){var e=Lr[a];delete Lr[a],e()}},bu=function(a){return function(){Su(a)}},Vf=function(a){Su(a.data)},Of=function(a){Ce.postMessage(ZA(a),$r.protocol+"//"+$r.host)};(!gu||!vu)&&(gu=function(e){YA(arguments.length,1);var t=Lf(e)?e:JA(e),i=WA(arguments,1);return Lr[++hu]=function(){jA(t,void 0,i)},ri(hu),hu},vu=function(e){delete Lr[e]},KA?ri=function(a){XA.nextTick(bu(a))}:pu&&pu.now?ri=function(a){pu.now(bu(a))}:Df&&!zA?(mu=new Df,fu=mu.port2,mu.port1.onmessage=Vf,ri=QA(fu.postMessage,fu)):Ce.addEventListener&&Lf(Ce.postMessage)&&!Ce.importScripts&&$r&&$r.protocol!=="file:"&&!Bf(Of)?(ri=Of,Ce.addEventListener("message",Vf,!1)):Cf in Mf("script")?ri=function(a){$f.appendChild(Mf("script"))[Cf]=function(){$f.removeChild(this),Su(a)}}:ri=function(a){setTimeout(bu(a),0)});_f.exports={set:gu,clear:vu}});var qf=f((JO,Ff)=>{"use strict";var Nf=re(),ek=$e(),tk=Object.getOwnPropertyDescriptor;Ff.exports=function(a){if(!ek)return Nf[a];var e=tk(Nf,a);return e&&e.value}});var Tu=f((ZO,Hf)=>{"use strict";var Uf=function(){this.head=null,this.tail=null};Uf.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}}};Hf.exports=Uf});var Qf=f((eB,jf)=>{"use strict";var ik=Zt();jf.exports=/ipad|iphone|ipod/i.test(ik)&&typeof Pebble!="undefined"});var Wf=f((tB,Gf)=>{"use strict";var rk=Zt();Gf.exports=/web0s(?!.*chrome)/i.test(rk)});var eb=f((iB,Zf)=>{"use strict";var Oi=re(),ak=qf(),Yf=ki(),Iu=yu().set,sk=Tu(),nk=du(),ok=Qf(),uk=Wf(),Eu=Ms(),zf=Oi.MutationObserver||Oi.WebKitMutationObserver,Kf=Oi.document,Xf=Oi.process,Ds=Oi.Promise,wu=ak("queueMicrotask"),Vi,xu,Pu,Cs,Jf;wu||(Mr=new sk,Dr=function(){var a,e;for(Eu&&(a=Xf.domain)&&a.exit();e=Mr.get();)try{e()}catch(t){throw Mr.head&&Vi(),t}a&&a.enter()},!nk&&!Eu&&!uk&&zf&&Kf?(xu=!0,Pu=Kf.createTextNode(""),new zf(Dr).observe(Pu,{characterData:!0}),Vi=function(){Pu.data=xu=!xu}):!ok&&Ds&&Ds.resolve?(Cs=Ds.resolve(void 0),Cs.constructor=Ds,Jf=Yf(Cs.then,Cs),Vi=function(){Jf(Dr)}):Eu?Vi=function(){Xf.nextTick(Dr)}:(Iu=Yf(Iu,Oi),Vi=function(){Iu(Dr)}),wu=function(a){Mr.head||Vi(),Mr.add(a)});var Mr,Dr;Zf.exports=wu});var ib=f((rB,tb)=>{"use strict";tb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Vs=f((aB,rb)=>{"use strict";rb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ai=f((sB,ab)=>{"use strict";var lk=re();ab.exports=lk.Promise});var Bi=f((nB,ub)=>{"use strict";var ck=re(),Cr=ai(),dk=ee(),pk=Io(),hk=ou(),mk=pe(),sb=su(),fk=Qe(),Au=uo(),nb=Cr&&Cr.prototype,bk=mk("species"),ku=!1,ob=dk(ck.PromiseRejectionEvent),gk=pk("Promise",function(){var a=hk(Cr),e=a!==String(Cr);if(!e&&Au===66||fk&&!(nb.catch&&nb.finally))return!0;if(!Au||Au<51||!/native code/.test(a)){var t=new Cr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[bk]=i,ku=t.then(function(){})instanceof i,!ku)return!0}return!e&&(sb==="BROWSER"||sb==="DENO")&&!ob});ub.exports={CONSTRUCTOR:gk,REJECTION_EVENT:ob,SUBCLASSING:ku}});var _i=f((oB,cb)=>{"use strict";var lb=et(),vk=TypeError,Sk=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new vk("Bad Promise constructor");e=i,t=r}),this.resolve=lb(e),this.reject=lb(t)};cb.exports.f=function(a){return new Sk(a)}});var Rb=f(()=>{"use strict";var yk=se(),Tk=Qe(),Ns=Ms(),Rt=re(),Ui=Me(),db=Ci(),pb=Zo(),Ik=Pr(),Ek=pf(),xk=et(),_s=ee(),Pk=De(),wk=mf(),Ak=cu(),gb=yu().set,Du=eb(),kk=ib(),Rk=Vs(),Lk=Tu(),vb=Fo(),Fs=ai(),Cu=Bi(),Sb=_i(),qs="Promise",yb=Cu.CONSTRUCTOR,$k=Cu.REJECTION_EVENT,Mk=Cu.SUBCLASSING,Ru=vb.getterFor(qs),Dk=vb.set,Ni=Fs&&Fs.prototype,si=Fs,Os=Ni,Tb=Rt.TypeError,Lu=Rt.document,Vu=Rt.process,$u=Sb.f,Ck=$u,Vk=!!(Lu&&Lu.createEvent&&Rt.dispatchEvent),Ib="unhandledrejection",Ok="rejectionhandled",hb=0,Eb=1,Bk=2,Ou=1,xb=2,Bs,mb,_k,fb,Pb=function(a){var e;return Pk(a)&&_s(e=a.then)?e:!1},wb=function(a,e){var t=e.value,i=e.state===Eb,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===xb&&Fk(e),e.rejection=Ou),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Tb("Promise-chain cycle")):(l=Pb(u))?Ui(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Ab=function(a,e){a.notified||(a.notified=!0,Du(function(){for(var t=a.reactions,i;i=t.get();)wb(i,a);a.notified=!1,e&&!a.rejection&&Nk(a)}))},kb=function(a,e,t){var i,r;Vk?(i=Lu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Rt.dispatchEvent(i)):i={promise:e,reason:t},!$k&&(r=Rt["on"+a])?r(i):a===Ib&&kk("Unhandled promise rejection",t)},Nk=function(a){Ui(gb,Rt,function(){var e=a.facade,t=a.value,i=bb(a),r;if(i&&(r=Rk(function(){Ns?Vu.emit("unhandledRejection",t,e):kb(Ib,e,t)}),a.rejection=Ns||bb(a)?xb:Ou,r.error))throw r.value})},bb=function(a){return a.rejection!==Ou&&!a.parent},Fk=function(a){Ui(gb,Rt,function(){var e=a.facade;Ns?Vu.emit("rejectionHandled",e):kb(Ok,e,a.value)})},Fi=function(a,e,t){return function(i){a(e,i,t)}},qi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Bk,Ab(a,!0))},Mu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Tb("Promise can't be resolved itself");var i=Pb(e);i?Du(function(){var r={done:!1};try{Ui(i,e,Fi(Mu,r,a),Fi(qi,r,a))}catch(s){qi(r,s,a)}}):(a.value=e,a.state=Eb,Ab(a,!1))}catch(r){qi({done:!1},r,a)}}};if(yb&&(si=function(e){wk(this,Os),xk(e),Ui(Bs,this);var t=Ru(this);try{e(Fi(Mu,t),Fi(qi,t))}catch(i){qi(t,i)}},Os=si.prototype,Bs=function(e){Dk(this,{type:qs,done:!1,notified:!1,parent:!1,reactions:new Lk,rejection:!1,state:hb,value:void 0})},Bs.prototype=db(Os,"then",function(e,t){var i=Ru(this),r=$u(Ak(this,si));return i.parent=!0,r.ok=_s(e)?e:!0,r.fail=_s(t)&&t,r.domain=Ns?Vu.domain:void 0,i.state===hb?i.reactions.add(r):Du(function(){wb(r,i)}),r.promise}),mb=function(){var a=new Bs,e=Ru(a);this.promise=a,this.resolve=Fi(Mu,e),this.reject=Fi(qi,e)},Sb.f=$u=function(a){return a===si||a===_k?new mb(a):Ck(a)},!Tk&&_s(Fs)&&Ni!==Object.prototype)){fb=Ni.then,Mk||db(Ni,"then",function(e,t){var i=this;return new si(function(r,s){Ui(fb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Ni.constructor}catch(a){}pb&&pb(Ni,Os)}yk({global:!0,constructor:!0,wrap:!0,forced:yb},{Promise:si});Ik(si,qs,!1,!0);Ek(qs)});var Cb=f((cB,Db)=>{"use strict";var qk=pe(),$b=qk("iterator"),Mb=!1;try{Lb=0,Bu={next:function(){return{done:!!Lb++}},return:function(){Mb=!0}},Bu[$b]=function(){return this},Array.from(Bu,function(){throw 2})}catch(a){}var Lb,Bu;Db.exports=function(a,e){try{if(!e&&!Mb)return!1}catch(r){return!1}var t=!1;try{var i={};i[$b]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var _u=f((dB,Vb)=>{"use strict";var Uk=ai(),Hk=Cb(),jk=Bi().CONSTRUCTOR;Vb.exports=jk||!Hk(function(a){Uk.all(a).then(void 0,function(){})})});var Ob=f(()=>{"use strict";var Qk=se(),Gk=Me(),Wk=et(),Yk=_i(),zk=Vs(),Kk=Rs(),Xk=_u();Qk({target:"Promise",stat:!0,forced:Xk},{all:function(e){var t=this,i=Yk.f(t),r=i.resolve,s=i.reject,n=zk(function(){var o=Wk(t.resolve),u=[],l=0,c=1;Kk(e,function(d){var h=l++,p=!1;c++,Gk(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var _b=f(()=>{"use strict";var Jk=se(),Zk=Qe(),eR=Bi().CONSTRUCTOR,Fu=ai(),tR=ct(),iR=ee(),rR=Ci(),Bb=Fu&&Fu.prototype;Jk({target:"Promise",proto:!0,forced:eR,real:!0},{catch:function(a){return this.then(void 0,a)}});!Zk&&iR(Fu)&&(Nu=tR("Promise").prototype.catch,Bb.catch!==Nu&&rR(Bb,"catch",Nu,{unsafe:!0}));var Nu});var Nb=f(()=>{"use strict";var aR=se(),sR=Me(),nR=et(),oR=_i(),uR=Vs(),lR=Rs(),cR=_u();aR({target:"Promise",stat:!0,forced:cR},{race:function(e){var t=this,i=oR.f(t),r=i.reject,s=uR(function(){var n=nR(t.resolve);lR(e,function(o){sR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Fb=f(()=>{"use strict";var dR=se(),pR=_i(),hR=Bi().CONSTRUCTOR;dR({target:"Promise",stat:!0,forced:hR},{reject:function(e){var t=pR.f(this),i=t.reject;return i(e),t.promise}})});var qu=f((yB,qb)=>{"use strict";var mR=tt(),fR=De(),bR=_i();qb.exports=function(a,e){if(mR(a),fR(e)&&e.constructor===a)return e;var t=bR.f(a),i=t.resolve;return i(e),t.promise}});var jb=f(()=>{"use strict";var gR=se(),vR=ct(),Ub=Qe(),SR=ai(),Hb=Bi().CONSTRUCTOR,yR=qu(),TR=vR("Promise"),IR=Ub&&!Hb;gR({target:"Promise",stat:!0,forced:Ub||Hb},{resolve:function(e){return yR(IR&&this===TR?SR:this,e)}})});var Qb=f(()=>{"use strict";Rb();Ob();_b();Nb();Fb();jb()});var zb=f(()=>{"use strict";var ER=se(),xR=Qe(),Us=ai(),PR=de(),Wb=ct(),Yb=ee(),wR=cu(),Gb=qu(),AR=Ci(),Hu=Us&&Us.prototype,kR=!!Us&&PR(function(){Hu.finally.call({then:function(){}},function(){})});ER({target:"Promise",proto:!0,real:!0,forced:kR},{finally:function(a){var e=wR(this,Wb("Promise")),t=Yb(a);return this.then(t?function(i){return Gb(e,a()).then(function(){return i})}:a,t?function(i){return Gb(e,a()).then(function(){throw i})}:a)}});!xR&&Yb(Us)&&(Uu=Wb("Promise").prototype.finally,Hu.finally!==Uu&&AR(Hu,"finally",Uu,{unsafe:!0}));var Uu});var Xb=f((AB,Kb)=>{"use strict";sf();Qb();zb();var RR=kt();Kb.exports=RR("Promise","finally")});var Zb=f((kB,Jb)=>{"use strict";var LR=Xb();Jb.exports=LR});var Hs=f((RB,eg)=>{"use strict";var $R=Zb();eg.exports=$R});var hg=f(()=>{"use strict";var QR=se(),GR=Oo().values;QR({target:"Object",stat:!0},{values:function(e){return GR(e)}})});var fg=f((h_,mg)=>{"use strict";hg();var WR=Pi();mg.exports=WR.Object.values});var gg=f((m_,bg)=>{"use strict";var YR=fg();bg.exports=YR});var ji=f((f_,vg)=>{"use strict";var zR=gg();vg.exports=zR});var Vg=f(()=>{"use strict";var SL=se(),yL=wi(),TL=Mi(),IL=Tr(),EL=Ir();SL({target:"Array",proto:!0},{at:function(e){var t=yL(this),i=TL(t),r=IL(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});EL("at")});var Bg=f((xN,Og)=>{"use strict";Vg();var xL=kt();Og.exports=xL("Array","at")});var Ng=f((PN,_g)=>{"use strict";var PL=Bg();_g.exports=PL});var Ct=f((wN,Fg)=>{"use strict";var wL=Ng();Fg.exports=wL});var fl=f((dq,Tv)=>{"use strict";var l$=Xt();Tv.exports=Array.isArray||function(e){return l$(e)==="Array"}});var Ev=f((pq,Iv)=>{"use strict";var c$=TypeError,d$=9007199254740991;Iv.exports=function(a){if(a>d$)throw c$("Maximum allowed index exceeded");return a}});var wv=f((hq,Pv)=>{"use strict";var p$=fl(),h$=Mi(),m$=Ev(),f$=ki(),xv=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?f$(n,o):!1,d,h;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&p$(d)?(h=h$(d),u=xv(a,e,d,h,u,s-1)-1):(m$(u+1),a[u]=d),u++),l++;return u};Pv.exports=xv});var Lv=f((mq,Rv)=>{"use strict";var Av=fl(),b$=lu(),g$=De(),v$=pe(),S$=v$("species"),kv=Array;Rv.exports=function(a){var e;return Av(a)&&(e=a.constructor,b$(e)&&(e===kv||Av(e.prototype))?e=void 0:g$(e)&&(e=e[S$],e===null&&(e=void 0))),e===void 0?kv:e}});var Mv=f((fq,$v)=>{"use strict";var y$=Lv();$v.exports=function(a,e){return new(y$(a))(e===0?0:e)}});var Dv=f(()=>{"use strict";var T$=se(),I$=wv(),E$=et(),x$=wi(),P$=Mi(),w$=Mv();T$({target:"Array",proto:!0},{flatMap:function(e){var t=x$(this),i=P$(t),r;return E$(e),r=w$(t,0),r.length=I$(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Cv=f(()=>{"use strict";var A$=Ir();A$("flatMap")});var Ov=f((yq,Vv)=>{"use strict";Dv();Cv();var k$=kt();Vv.exports=k$("Array","flatMap")});var _v=f((Tq,Bv)=>{"use strict";var R$=Ov();Bv.exports=R$});var bl=f((Iq,Nv)=>{"use strict";var L$=_v();Nv.exports=L$});var Xr=f((Eq,Fv)=>{"use strict";var $$=xr(),M$=String;Fv.exports=function(a){if($$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return M$(a)}});var gl=f((xq,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((Pq,Hv)=>{"use strict";var D$=ne(),C$=At(),V$=Xr(),Sl=gl(),Uv=D$("".replace),O$=RegExp("^["+Sl+"]+"),B$=RegExp("(^|[^"+Sl+"])["+Sl+"]+$"),vl=function(a){return function(e){var t=V$(C$(e));return a&1&&(t=Uv(t,O$,"")),a&2&&(t=Uv(t,B$,"$1")),t}};Hv.exports={start:vl(1),end:vl(2),trim:vl(3)}});var Yv=f((wq,Wv)=>{"use strict";var _$=Ho().PROPER,N$=de(),Qv=gl(),Gv="\u200B\x85\u180E";Wv.exports=function(a){return N$(function(){return!!Qv[a]()||Gv[a]()!==Gv||_$&&Qv[a].name!==a})}});var yl=f((Aq,zv)=>{"use strict";var F$=jv().start,q$=Yv();zv.exports=q$("trimStart")?function(){return F$(this)}:"".trimStart});var Xv=f(()=>{"use strict";var U$=se(),Kv=yl();U$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Kv},{trimLeft:Kv})});var Zv=f(()=>{"use strict";Xv();var H$=se(),Jv=yl();H$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Jv},{trimStart:Jv})});var tS=f((Mq,eS)=>{"use strict";Zv();var j$=kt();eS.exports=j$("String","trimLeft")});var rS=f((Dq,iS)=>{"use strict";var Q$=tS();iS.exports=Q$});var sS=f((Cq,aS)=>{"use strict";var G$=rS();aS.exports=G$});var TS=f(()=>{"use strict"});var IS=f(()=>{"use strict"});var xS=f((mH,ES)=>{"use strict";var fM=De(),bM=Xt(),gM=pe(),vM=gM("match");ES.exports=function(a){var e;return fM(a)&&((e=a[vM])!==void 0?!!e:bM(a)==="RegExp")}});var wS=f((fH,PS)=>{"use strict";var SM=tt();PS.exports=function(){var a=SM(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 RS=f((bH,kS)=>{"use strict";var yM=Me(),TM=Ge(),IM=fr(),EM=wS(),AS=RegExp.prototype;kS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in AS)&&!TM(a,"flags")&&IM(AS,a)?yM(EM,a):e}});var $S=f((gH,LS)=>{"use strict";var kl=ne(),xM=wi(),PM=Math.floor,wl=kl("".charAt),wM=kl("".replace),Al=kl("".slice),AM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,kM=/\$([$&'`]|\d{1,2})/g;LS.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=kM;return r!==void 0&&(r=xM(r),u=AM),wM(s,u,function(l,c){var d;switch(wl(c,0)){case"$":return"$";case"&":return a;case"`":return Al(e,0,t);case"'":return Al(e,n);case"<":d=r[Al(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=PM(h/10);return p===0?l:p<=o?i[p-1]===void 0?wl(c,1):i[p-1]+wl(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var CS=f(()=>{"use strict";var RM=se(),LM=Me(),Ll=ne(),MS=At(),$M=ee(),MM=xi(),DM=xS(),Ki=Xr(),CM=gr(),VM=RS(),OM=$S(),BM=pe(),_M=Qe(),NM=BM("replace"),FM=TypeError,Rl=Ll("".indexOf),qM=Ll("".replace),DS=Ll("".slice),UM=Math.max;RM({target:"String",proto:!0},{replaceAll:function(e,t){var i=MS(this),r,s,n,o,u,l,c,d,h,p,m=0,b="";if(!MM(e)){if(r=DM(e),r&&(s=Ki(MS(VM(e))),!~Rl(s,"g")))throw new FM("`.replaceAll` does not allow non-global regexes");if(n=CM(e,NM),n)return LM(n,e,i,t);if(_M&&r)return qM(Ki(i),e,t)}for(o=Ki(i),u=Ki(e),l=$M(t),l||(t=Ki(t)),c=u.length,d=UM(1,c),h=Rl(o,u);h!==-1;)p=l?Ki(t(u,h,o)):OM(u,o,h,[],void 0,t),b+=DS(o,m,h)+p,m=h+c,h=h+d>o.length?-1:Rl(o,u,h+d);return m<o.length&&(b+=DS(o,m)),b}})});var OS=f((yH,VS)=>{"use strict";TS();IS();CS();var HM=kt();VS.exports=HM("String","replaceAll")});var _S=f((TH,BS)=>{"use strict";var jM=OS();BS.exports=jM});var FS=f((IH,NS)=>{"use strict";var QM=_S();NS.exports=QM});var US=f((EH,qS)=>{"use strict";var GM=Tr(),WM=Xr(),YM=At(),zM=RangeError;qS.exports=function(e){var t=WM(YM(this)),i="",r=GM(e);if(r<0||r===1/0)throw new zM("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var WS=f((xH,GS)=>{"use strict";var QS=ne(),KM=ko(),HS=Xr(),XM=US(),JM=At(),ZM=QS(XM),eD=QS("".slice),tD=Math.ceil,jS=function(a){return function(e,t,i){var r=HS(JM(e)),s=KM(t),n=r.length,o=i===void 0?" ":HS(i),u,l;return s<=n||o===""?r:(u=s-n,l=ZM(o,tD(u/o.length)),l.length>u&&(l=eD(l,0,u)),a?r+l:l+r)}};GS.exports={start:jS(!1),end:jS(!0)}});var zS=f((PH,YS)=>{"use strict";var iD=Zt();YS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(iD)});var KS=f(()=>{"use strict";var rD=se(),aD=WS().start,sD=zS();rD({target:"String",proto:!0,forced:sD},{padStart:function(e){return aD(this,e,arguments.length>1?arguments[1]:void 0)}})});var JS=f((kH,XS)=>{"use strict";KS();var nD=kt();XS.exports=nD("String","padStart")});var ey=f((RH,ZS)=>{"use strict";var oD=JS();ZS.exports=oD});var iy=f((LH,ty)=>{"use strict";var uD=ey();ty.exports=uD});var ud="2.0.130-dev.ca914dc0.0";var Le=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Le||{}),lt=(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))(lt||{});var us=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(us||{}),Kn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Kn||{});var Xn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Xn||{}),ls=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ls||{});var BT=D(Be(),1);import{assertNever as nh,assertNonNullable as vx,isNonNullable as ms,ValueSubject as Lo,Subject as Sx,Subscription as yx,merge as Tx,observableFrom as Ix,fromEvent as ih,map as rh,tap as ah,filterChanged as Ex,isNullable as $o,ErrorCategory as sh}from"@vkontakte/videoplayer-shared/es2018";var th=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var fs=class{constructor(e){this.connection$=new Lo(void 0);this.castState$=new Lo("NOT_AVAILABLE");this.errorEvent$=new Sx;this.realCastState$=new Lo("NOT_AVAILABLE");this.subscription=new yx;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 i=ms((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||th("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:sh.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 i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ms(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();$o(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();$o(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),i=cast.framework.CastContext.getInstance();this.subscription.add(ih(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.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 nh(r.sessionState)}})).add(Tx(ih(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ah(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),rh(r=>r.castState)),Ix([i.getCastState()])).pipe(Ex(),rh(xx),ah(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=ms(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();vx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;($o(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(r==="CONNECTED"?ms(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:sh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},xx=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 nh(a)}};var fc=D(Be(),1),vT=D(Di(),1),ST=D(au(),1);var cg=D(Hs(),1);import{assertNever as tg}from"@vkontakte/videoplayer-shared/es2018";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 i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:tg(t)}return a},js=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:tg(e)}};var w=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as MR,Subject as Qs,merge as ig}from"@vkontakte/videoplayer-shared/es2018";var C=class{constructor(e){this.transitionStarted$=new Qs;this.transitionEnded$=new Qs;this.transitionUpdated$=new Qs;this.forceChanged$=new Qs;this.stateChangeStarted$=ig(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=ig(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||MR(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as DR}from"@vkontakte/videoplayer-shared/es2018";var rg=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 DR(a)}};import{assertNever as Hi,assertNonNullable as ni,debounce as ag,ErrorCategory as sg,fromEvent as oi,isNonNullable as ng,map as og,merge as ug,observableFrom as CR,Subject as VR,Subscription as ju,timeout as OR,getHighestQuality as BR}from"@vkontakte/videoplayer-shared/es2018";var _R=5,NR=5,FR=500,lg=7e3,Vr=class{constructor(e){this.subscription=new ju;this.loadMediaTimeoutSubscription=new ju;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Hi(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:Hi(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:Hi(e)}break}default:Hi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(rg(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 ju;this.subscription.add(e),this.subscription.add(ug(this.videoState.stateChangeStarted$.pipe(og(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(og(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new VR;e.add(r.pipe(ag(FR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(oi(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)>_R)&&r.next(o),s=o})),e.add(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.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<NR&&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:Hi(n)}}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=ug(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,CR(["init"])).pipe(ag(0));t(i,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 i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?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),i=this.createLoadRequest(t);this.loadMedia(i)}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 r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];ni(c);let d=BR(Object.keys(c));ni(d);let h=c[d];ni(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];ni(c),i=c.url,r="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];ni(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];ni(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];ni(c),i=he(c.url),r="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:sg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Hi(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return ng(o)&&(n.metadata.title=o),ng(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(OR(lg).subscribe(()=>s(`timeout(${lg})`)))});(0,cg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:sg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var hl=D(Be(),1);import{clearVideoElement as pg}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as qR}from"@vkontakte/videoplayer-shared/es2018";var dg=a=>{try{a.pause(),a.playbackRate=0,qR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as UR,Subscription as HR}from"@vkontakte/videoplayer-shared/es2018";var Qu=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)}},Gu=window.WeakMap?new WeakMap:new Qu,Wu=window.WeakMap?new WeakMap:new Map,jR=(a,e=20)=>{let t=0;return UR(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?pg(i):(i=document.createElement("video"),a.appendChild(i)),Gu.set(i,r);let s=new HR;return s.add(jR(i,e)),Wu.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},xe=a=>{let e=Wu.get(a);e==null||e.unsubscribe(),Wu.delete(a);let t=Gu.get(a);Gu.delete(a),t?pg(a):dg(a)};var zu=D(ji(),1);import{assertNonNullable as Or,isNonNullable as rt,isNullable as JR,fromEvent as Qi,merge as Sg,observableFrom as yg,filterChanged as Tg,map as Br,Subject as Ig,Subscription as ZR,ValueSubject as eL,ErrorCategory as tL}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Yu,isNullable as KR,Subscription as XR}from"@vkontakte/videoplayer-shared/es2018";var Gs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=KR(r),l=new XR;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},it=(a,e,t)=>Gs(e,()=>a.loop,i=>{Yu(i)&&(a.loop=i)},{onError:t}),Pe=(a,e,t,i)=>Gs(e,()=>({muted:a.muted,volume:a.volume}),r=>{Yu(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),_e=(a,e,t,i)=>Gs(e,()=>a.playbackRate,r=>{Yu(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Lt=Gs;var iL=a=>["__",a.language,a.label].join("|"),rL=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Ku=class a{constructor(e){this.available$=new Ig;this.current$=new eL(void 0);this.error$=new Ig;this.subscription=new ZR;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:tL.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Lt(t.internalTextTracks,()=>(0,zu.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Br(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Lt(t.externalTextTracks,()=>(0,zu.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Br(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Lt(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:r})),this.subscription.add(Lt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Or(this.video);let{textTracks:e}=this.video;this.subscription.add(Qi(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Sg(Qi(e,"addtrack"),Qi(e,"removetrack"),yg(["init"])).pipe(Br(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Tg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(Sg(Qi(e,"change"),yg(["init"])).pipe(Br(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Br(i=>i&&this.htmlTextTrackToITextTrack(i).id),Tg()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Qi(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Qi(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;rt(t.align)&&(r.align=t.align),rt(t.position)&&(r.position=t.position),rt(t.size)&&(r.size=t.size),rt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Or(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:i}=e,r=e.id?e.id:iL(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Or(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(JR(e)||!rL(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){Or(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){Or(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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)}},Ne=Ku;var ui=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 Eg=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},Xu=a=>{let e=Eg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},xg=a=>{let e=Eg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as we,map as $t,merge as Zu,filterChanged as pL,isNonNullable as Dg,Subject as hL,filter as Nr,mapTo as el,combine as mL,once as fL,throttle as bL,ErrorCategory as gL,ValueSubject as Cg,Subscription as vL}from"@vkontakte/videoplayer-shared/es2018";var aL=3,Pg=(a,e,t=aL)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Ws=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,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/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||i||n||u||l||r||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 i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var wg=D(Be(),1);var _r=()=>{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 Ys=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,wg.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=_r()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e){let t=await 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,i=/iphone/i.test(e)?"iPhone":void 0,r=/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||i||r||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 i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var zs=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(i){console.error(i)}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(i){console.error(i)}}};var Ye=()=>window.ManagedMediaSource||window.MediaSource,Ks=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ag=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},kg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var sL=document.createElement("video"),nL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',oL='video/mp4; codecs="hev1.1.6.L93.B0"',Rg='video/webm; codecs="vp09.00.10.08"',Lg='video/webm; codecs="av01.0.00M.08"',uL='audio/mp4; codecs="mp4a.40.2"',lL='audio/webm; codecs="opus"',$g,cL=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Lg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Rg}})]);$g={DASH_WEBM_AV1:e,DASH_WEBM:t}};cL().catch(a=>{console.log(sL),console.error(a)});var Xs=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 $g}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,h,p,m,b,g,v,S,y,E;this._video=document.createElement("video");try{this._protocols={mms:Ks(),mse:Ag(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"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 T=!!((c=(l=Ye())==null?void 0:l.isTypeSupported)!=null&&c.call(l,nL)),k=!!((h=(d=Ye())==null?void 0:d.isTypeSupported)!=null&&h.call(d,oL)),B=!!((m=(p=Ye())==null?void 0:p.isTypeSupported)!=null&&m.call(p,uL));this._codecs={h264:T,h265:k,vp9:!!((g=(b=Ye())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Rg)),av1:!!((S=(v=Ye())==null?void 0:v.isTypeSupported)!=null&&S.call(v,Lg)),aac:B,opus:!!((E=(y=Ye())==null?void 0:y.isTypeSupported)!=null&&E.call(y,lL)),mpeg:(T||k)&&B},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}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 Mg="audio/mpeg",Js=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Mg))},this._codecs={mp3:!!((r=(i=Ye())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Mg))}}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 dL}from"@vkontakte/videoplayer-shared/es2018";var Ju=class{constructor(){this.isInited$=new dL(!1);this._displayChecker=new zs,this._deviceChecker=new Ys(this._displayChecker),this._browserChecker=new Ws,this._videoChecker=new Xs(this._deviceChecker,this._browserChecker),this._audioChecker=new Js,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}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},N=new Ju;var Ae=a=>{let e=A=>we(a,A).pipe(el(void 0)),t=new vL,i=()=>t.unsubscribe(),s=Zu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>we(a,A))).pipe($t(A=>A.type==="ended"?a.readyState<2:a.readyState<3),pL()),n=Zu(we(a,"progress"),we(a,"timeupdate")).pipe($t(()=>Pg(a.buffered,a.currentTime))),o=N.browser.isSafari?mL({play:e("play").pipe(fL()),playing:e("playing")}).pipe(el(void 0)):e("playing"),u=we(a,"volumechange").pipe($t(()=>({muted:a.muted,volume:a.volume}))),l=we(a,"ratechange").pipe($t(()=>a.playbackRate)),c=we(a,"error").pipe(Nr(()=>!!(a.error||a.played.length)),$t(()=>{var q;let A=a.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:gL.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:(q=a.error)!=null?q:void 0}})),d=we(a,"timeupdate").pipe($t(()=>a.currentTime)),h=new hL,p=.3,m;t.add(d.subscribe(A=>{a.loop&&Dg(m)&&Dg(A)&&m>=a.duration-p&&A<=p&&h.next(m),m=A}));let b=e("pause").pipe(Nr(()=>!a.error&&m!==a.duration)),g=we(a,"enterpictureinpicture"),v=we(a,"leavepictureinpicture"),S=new Cg(xg(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new Cg(Xu(a)),E=we(a,"fullscreenchange");t.add(E.pipe($t(()=>Xu(a))).subscribe(y));let T=.1,k=1e3,B=we(a,"timeupdate").pipe(Nr(A=>a.duration-a.currentTime<T)),O=Zu(B.pipe(Nr(A=>!a.loop)),we(a,"ended")).pipe(bL(k),el(void 0)),_=B.pipe(Nr(A=>a.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:O,looped$:h,loopExpected$:_,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:we(a,"durationchange").pipe($t(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:S,inFullscreen$:y,enterPip$:g,leavePip$:v,destroy:i}};import{VideoQuality as Mt}from"@vkontakte/videoplayer-shared/es2018";var Dt=a=>{switch(a){case"mobile":return Mt.Q_144P;case"lowest":return Mt.Q_240P;case"low":return Mt.Q_360P;case"sd":case"medium":return Mt.Q_480P;case"hd":case"high":return Mt.Q_720P;case"fullhd":case"full":return Mt.Q_1080P;case"quadhd":case"quad":return Mt.Q_1440P;case"ultrahd":case"ultra":return Mt.Q_2160P}};var Vt=D(Ct(),1),Kg=D(Be(),1),tn=D(Di(),1);import{isNonNullable as Se,isNullable as Gg,now as Xg,isHigher as Wg,isHigherOrEqual as al,isInvariantQuality as Yg,isLowerOrEqual as sl,videoSizeToQuality as RL,assertNotEmptyArray as Jg,assertNonNullable as LL}from"@vkontakte/videoplayer-shared/es2018";var tl=!1,ht={},qg=a=>{tl=a},Ug=()=>{ht={}},Hg=a=>{a(ht)},Fr=(a,e)=>{var t;tl&&(ht.meta=(t=ht.meta)!=null?t:{},ht.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var i,r;if(!tl)return;ht.series=(i=ht.series)!=null?i:{};let t=(r=ht.series[this.name])!=null?r:[];t.push([Date.now(),e]),ht.series[this.name]=t}};import{isHigher as AL,isHigherOrEqual as MN,isLower as jg,isLowerOrEqual as DN,isNonNullable as Zs,isNullable as kL,videoHeightToQuality as en}from"@vkontakte/videoplayer-shared/es2018";function il({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function rl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&il({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function qr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return kL(a)||Zs(a.min)&&Zs(a.max)&&jg(a.max,a.min)||Zs(a.min)&&e&&AL(a.min,e)||Zs(a.max)&&t&&jg(a.max,t)}function Qg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return qr({limits:{max:a!=null&&a.max?en(a.max):void 0,min:a!=null&&a.min?en(a.min):void 0},highestAvailableQuality:e?en(e):void 0,lowestAvailableQuality:t?en(t):void 0})}var $L=new ve("best_bitrate"),Zg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var nl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ur=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',rn=(a,e,t,i)=>{var u;let r=[...e].sort(nl(1)),s=[...t].sort(nl(1)),n=s.filter(l=>Se(l.bitrate)&&Se(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Vt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Vt.default)(s,-1);return o&&(0,Kg.default)(n,o)?o:n.length?(0,Vt.default)(n,-1):(0,Vt.default)(s,0)},zg=a=>"quality"in a,tv=(a,e,t,i)=>{var n;let r=Se((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&Se(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Xg()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.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 i==null||i.recordSwitch(t),t},$L=(a,e)=>Math.log(e)/Math.log(a),ML=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&N.display.pixelRatio){let s=N.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=$L(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return rl({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}},Ot=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:b})=>{var te,H,I,$,Y;Xg(a,Zg);let{containerSizeFactor:g,containerSizeLimit:v}=ML({container:e,tuning:i,limits:r,panelSize:b}),S=i.considerPlaybackRate&&Se(o)?o:1,y=a.filter(x=>!Wg(x.quality)).sort((x,R)=>Gg(x.quality,R.quality)?-1:1),E=(te=(0,Vt.default)(y,-1))==null?void 0:te.quality,T=(H=(0,Vt.default)(y,0))==null?void 0:H.quality,k=qr({limits:r,lowestAvailableQuality:E,highestAvailableQuality:T}),B=S*Jg(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),O={},A=y.filter(x=>{let R=!0;if(v)if(x.size)R=x.size.width<=v.width&&x.size.height<=v.height;else{let ot=v&&kL(v);R=ot?sl(x.quality,ot):!0}if(!R)return O[x.quality]="FitsContainer",!1;let ce=p||t,bi=Se(ce)&&isFinite(ce)&&Se(x.bitrate)?ce-s>=x.bitrate*B:!0,nt=rl({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&(r==null?void 0:r.min)===x.quality;if(!bi&&!nt)return O[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Se(i.minBufferToSwitchUp)&&u&&!Wg(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Gg(x.quality,u.quality))return O[x.quality]="Buffer",!1;if(!!d&&al(x.quality,d)&&!nt)return O[x.quality]="DroppedFramesLimit",!1;if(!!h&&al(x.quality,h)&&!nt)return O[x.quality]="StallsLimit",!1;let Ie=k||(Qg(r==null?void 0:r.max)||sl(x.quality,r.max))&&(Qg(r==null?void 0:r.min)||al(x.quality,r.min)),Xe=Se(c)&&!c?sl(x.quality,i.backgroundVideoQualityLimit):!0;return!Ie||!Xe?(O[x.quality]="FitsQualityLimits",!1):!0})[0];A&&A.bitrate&&LL.next(A.bitrate);let q=(I=A!=null?A:(0,Vt.default)(y,-1))!=null?I:a[0],L=l==null?void 0:l.last,U=ev(i,m,q,l);return Se(l)&&U.quality!==(L==null?void 0:L.quality)&&m({message:`
9
+ `}),o}return i==null||i.recordSwitch(t),t},ML=(a,e)=>Math.log(e)/Math.log(a),DL=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&N.display.pixelRatio){let s=N.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=ML(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return rl({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}},Ot=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:b})=>{var te,H,I,$,Y;Jg(a,ev);let{containerSizeFactor:g,containerSizeLimit:v}=DL({container:e,tuning:i,limits:r,panelSize:b}),S=i.considerPlaybackRate&&Se(o)?o:1,y=a.filter(x=>!Yg(x.quality)).sort((x,R)=>Wg(x.quality,R.quality)?-1:1),E=(te=(0,Vt.default)(y,-1))==null?void 0:te.quality,T=(H=(0,Vt.default)(y,0))==null?void 0:H.quality,k=qr({limits:r,lowestAvailableQuality:E,highestAvailableQuality:T}),B=S*Zg(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),O={},A=y.filter(x=>{let R=!0;if(v)if(x.size)R=x.size.width<=v.width&&x.size.height<=v.height;else{let ot=v&&RL(v);R=ot?sl(x.quality,ot):!0}if(!R)return O[x.quality]="FitsContainer",!1;let ce=p||t,bi=Se(ce)&&isFinite(ce)&&Se(x.bitrate)?ce-s>=x.bitrate*B:!0,nt=rl({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&(r==null?void 0:r.min)===x.quality;if(!bi&&!nt)return O[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Se(i.minBufferToSwitchUp)&&u&&!Yg(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Wg(x.quality,u.quality))return O[x.quality]="Buffer",!1;if(!!d&&al(x.quality,d)&&!nt)return O[x.quality]="DroppedFramesLimit",!1;if(!!h&&al(x.quality,h)&&!nt)return O[x.quality]="StallsLimit",!1;let Ie=k||(Gg(r==null?void 0:r.max)||sl(x.quality,r.max))&&(Gg(r==null?void 0:r.min)||al(x.quality,r.min)),Xe=Se(c)&&!c?sl(x.quality,i.backgroundVideoQualityLimit):!0;return!Ie||!Xe?(O[x.quality]="FitsQualityLimits",!1):!0})[0];A&&A.bitrate&&$L.next(A.bitrate);let q=(I=A!=null?A:(0,Vt.default)(y,-1))!=null?I:a[0],L=l==null?void 0:l.last,U=tv(i,m,q,l);return Se(l)&&U.quality!==(L==null?void 0:L.quality)&&m({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
12
  ${a.map(x=>{var R,ce;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(R=x.size)==null?void 0:R.width}:${(ce=x.size)==null?void 0:ce.height} }`}).join(`
@@ -39,7 +39,7 @@ var jT=Object.create;var nd=Object.defineProperty;var QT=Object.getOwnPropertyDe
39
39
 
40
40
  [best video track] ${A==null?void 0:A.quality}
41
41
  [selected video track] ${U==null?void 0:U.quality}
42
- `}),U},tv=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Xg(t,Zg);let c=r.considerPlaybackRate&&Se(s)?s:1,d=[...t].sort(nl(-1)),h=a.bitrate;RL(h);let p=c*Jg(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=rn(a,e,t,r.minVideoAudioRatio),g=l||i;Se(g)&&isFinite(g)&&(m=d.find(y=>Se(y.bitrate)&&Se(b==null?void 0:b.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,S=m&&ev(r,u,m,o);return Se(o)&&(S==null?void 0:S.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
42
+ `}),U},iv=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Jg(t,ev);let c=r.considerPlaybackRate&&Se(s)?s:1,d=[...t].sort(nl(-1)),h=a.bitrate;LL(h);let p=c*Zg(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=rn(a,e,t,r.minVideoAudioRatio),g=l||i;Se(g)&&isFinite(g)&&(m=d.find(y=>Se(y.bitrate)&&Se(b==null?void 0:b.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,S=m&&tv(r,u,m,o);return Se(o)&&(S==null?void 0:S.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
43
43
  [AUDIO TRACKS ABR]
44
44
  [available audio tracks]
45
45
  ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
@@ -60,14 +60,14 @@ var jT=Object.create;var nd=Object.defineProperty;var QT=Object.getOwnPropertyDe
60
60
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
61
61
 
62
62
  [selected audio track] ${S==null?void 0:S.id}
63
- `}),S};var oe=a=>new URL(a).hostname;import{assertNever as pv,assertNonNullable as hv,combine as ZL,debounce as e$,ErrorCategory as mv,filter as fv,filterChanged as t$,isNonNullable as dl,map as un,merge as bv,observableFrom as i$,once as r$,Subscription as a$,ValueSubject as pl,videoQualityToHeight as gv,videoSizeToQuality as s$}from"@vkontakte/videoplayer-shared/es2018";var uv=D(Ct(),1);var rv=D(Be(),1),iv=a=>{if(a instanceof DOMException&&(0,rv.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=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!iv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return iv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as sn,isNullable as VL,assertNonNullable as Qr}from"@vkontakte/videoplayer-shared/es2018";var sv=D(ji(),1);import{isNonNullable as av,assertNonNullable as an,now as DL}from"@vkontakte/videoplayer-shared/es2018";function ue(){return DL()}function ol(a){return ue()-a}function ul(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(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 nv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Gi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;an(c);let L=ol(c),U;if(L<b){U=b-L,setTimeout(g,U);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,k()},v=L=>(s=L,q),S=L=>(d=L,q),y=()=>(p="json",q),E=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},T=L=>(h=L,q),k=()=>{c=ue(),n=new r,n.open("get",a);let L=0,U,te=0,H=()=>(an(c),Math.max(c,Math.max(U||0,te||0)));if(s&&n.addEventListener("progress",I=>{let $=ue();s.updateChunk&&I.loaded>L&&(s.updateChunk(H(),I.loaded-L),L=I.loaded,U=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;an(n);let I=n.status;if(I>=200&&I<300){let{response:$,responseType:Y}=n,x=$==null?void 0:$.byteLength;if(typeof x=="number"&&s){let R=x-L;R&&s.updateChunk&&s.updateChunk(H(),R)}Y==="json"&&(!$||!(0,sv.default)($).length)?E():(d&&d(),e($))}else E()}),n.addEventListener("error",()=>{E()}),h){let I=()=>{an(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(te=ue(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=p,n.send(),q},q={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:L=>(l=L,q),withRetryInterval:(L,U)=>(av(L)&&(b=L),av(U)&&(m=U),q),withTimeout:L=>(o=L,q),withFinally:S,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var Hr=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,i){return{start:e,end:t,bytes:i}}_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 i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/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(r)}/${Math.round(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),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 ov=D(ji(),1);var jr=class{constructor(e,t,i,r,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=i,this.MAX_PARALLEL_REQUESTS=r,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 i=ue(),r=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()-i,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=Gi(t,s,()=>r("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 i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,ov.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,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}`),i(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=i,s._retryCB=r,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 OL}from"@vkontakte/videoplayer-shared/es2018";var nn=1e4,ll=3;var BL=6e4,_L=10,NL=1,FL=500,Gr=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 OL,this.chunkRateEstimator=new Hr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ul(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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=ul(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,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,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||{};!jg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,uv.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)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||sn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{nv(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 jr(ll,nn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=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},h=(E,T,k)=>{u&&u.abort(),u=Gi(this.urlResolver.resolve(E,!1),T,k,()=>this._retryCallback()).withTimeout(nn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ll).withFinally(()=>{u=null}).send()},p=(E,T,k)=>{Qr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let T=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),i.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 k=ue()-1e4,B=0;for(let _=0;_<this.bufferStates.length;_++){let A=this.bufferStates[_];E=Math.min(E,A.buf),A.ts<k&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${E} drop=${B} jitter=${this.sourceJitter}`);let O=E-NL;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},v=E=>{let T,k=()=>T&&T.start?T.start.length:0,B=I=>T.start[I]/1e3,O=I=>T.dur[I]/1e3,_=I=>T.fragIndex+I,A=(I,$)=>({chunkIdx:_(I),startTS:B(I),dur:O(I),discontinuity:$}),q=()=>{let I=0;if(T&&T.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=$;this.sourceJitter>1&&(x+=this.sourceJitter-1);let R=T.dur.length-1;for(;R>=0&&(x-=T.dur[R],!(x<=0));--R);I=Math.min(R,T.dur.length-1-Y),I=Math.max(I,0)}return A(I,!0)},L=I=>{let $=k();if(!($<=0)){if(sn(I)){for(let Y=0;Y<$;Y++)if(B(Y)>I)return A(Y)}return q()}},U=I=>{let $=k(),Y=I?I.chunkIdx+1:0,x=Y-T.fragIndex;if(!($<=0)){if(!I||x<0||x-$>_L)return t(`Resync: offset=${x} bChunks=${$} chunk=`+JSON.stringify(I)),q();if(!(x>=$))return A(Y-T.fragIndex,!1)}},te=(I,$,Y)=>{l&&l.abort(),l=Gi(this.urlResolver.resolve(I,!0,this.lowLatency),$,Y,()=>this._retryCallback()).withTimeout(nn).withRetryCount(ll).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(I,$)=>{te(E,Y=>{if(!d())return;T=Y;let x=!!T.lowLatency;x!==this.lowLatency&&b(x);let R=0;for(let ce=0;ce<T.dur.length;++ce)R+=T.dur[ce];R>0&&(Qr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(R/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,I(L($))},()=>this._handleNetworkError())},nextChunk:U}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Qr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:T,logger:k}=this.params,B=v(e.jidxUrl),O,_,A,q,L=0,U,te,H,I=()=>{U&&(clearTimeout(U),U=void 0);let G=Math.max(FL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=L+G,Te=ue(),Ie=Math.min(1e4,be-Te);L=Te;let Xe=()=>{l||d()&&B.seek(()=>{d()&&(L=ue(),$(),I())})};Ie>0?U=window.setTimeout(()=>{this.paused?I():Xe()},Ie):Xe()},$=()=>{let G;for(;G=B.nextChunk(q);)q=G,bi(G);let be=B.nextChunk(A);if(be){if(A&&be.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?I():(S(),this._initPlayerWith(e));return}ce(be)}else I()},Y=(G,be)=>{if(!d()||!this.sourceBuffer)return;let Te,Ie,Xe,ot=yt=>{window.setTimeout(()=>{d()&&Y(G,be)},yt)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),ot(100);else{let yt=ue(),jt=T.currentTime;!this.paused&&T.buffered.length>1&&te===jt&&yt-H>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),te!==jt&&(te=jt,H=yt);let gi=this._getBufferSizeSec();if(gi>30)k(`Buffered ${gi} seconds; delaying appendBuffer`),ot(2e3);else try{this.sourceBuffer.appendBuffer(G),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:gi}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(sr){if(sr.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),Xe=this.sourceBuffer.buffered.length,Xe!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=jt,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),ot(1e3);else throw sr}}},x=()=>{_&&O&&(k([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(A)]),Y(_,function(){_=null,$()}))},R=G=>e.fragUrlTemplate.replace("%%id%%",G.chunkIdx),ce=G=>{d()&&p(R(G),(be,Te)=>{if(d()){if(Te/=1e3,_=be,A=G,n=G.startTS,Te){let Ie=Math.min(10,G.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}x()}},()=>this._handleNetworkError())},bi=G=>{d()&&(Qr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(R(G),!1)))},nt=G=>{d()&&(e.cachedHeader=G,Y(G,()=>{O=!0,x()}))};s=!0,B.seek(G=>{if(d()){if(L=ue(),!G){I();return}q=G,!VL(E)||G.startTS>E?ce(G):(A=G,$())}},E),e.cachedHeader?nt(e.cachedHeader):h(e.headerUrl,nt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),sn(r)&&(r+=.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,Qr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return sn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=ue();if(this.chunkRateEstimator.addInterval(h,m,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ol(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ue();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Gi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(nn).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:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.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):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},BL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var dv=D(Di(),1);import{debounce as qL,filter as lv,fromEvent as UL,interval as HL,isHigher as jL,isInvariantQuality as QL,isLower as GL,merge as WL,Subject as cv,Subscription as YL}from"@vkontakte/videoplayer-shared/es2018";var cl=class{constructor(){this.onDroopedVideoFramesLimit$=new cv;this.subscription=new YL;this.playing=!1;this.tracks=[];this.forceChecker$=new cv;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&&!QL(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&jL(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(UL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=HL(this.droppedFramesChecker.checkTime).pipe(lv(()=>this.playing),lv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(qL(this.droppedFramesChecker.checkTime)),i=WL(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),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 i,r;let t=(r=(i=(0,dv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>GL(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[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}},on=cl;import{map as zL,Observable as KL}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as XL}from"@vkontakte/videoplayer-shared/es2018";var Wr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var JL=(a,e)=>new KL(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Wr()))},{...i,...e});r.observe(a);let s=XL(document,"visibilitychange").pipe(zL(n=>!document.hidden||Wr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Fe=JL;var n$=["paused","playing","ready"],o$=["paused","playing","ready"],Yr=class{constructor(e){this.subscription=new a$;this.videoState=new C("stopped");this.representations$=new pl([]);this.droppedFramesManager=new on;this.maxSeekBackTime$=new pl(1/0);this.zeroTime$=new pl(void 0);this.liveOffset=new ui;this._dashCb=e=>{var t,i,r,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:mv.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=(i=Dt(u.name))!=null?i:s$(u.video),d=u.bitrate/1e3,h={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.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),dl(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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="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,hl.default)(o$,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,hl.default)(n$,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(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="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 pv(e)}};this.textTracksManager=new Ne(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:mv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(bv(this.videoState.stateChangeStarted$.pipe(un(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(un(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ee(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 i=Ae(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(un(r=>r.map(({track:s})=>s)),fv(r=>!!r.length),r$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(t$(),un(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(ZL({zeroTime:this.zeroTime$.pipe(fv(dl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(it(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(_e(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Fe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&gv(r),min:s&&gv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.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 pv(r.to)}},t)).add(bv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,i$(["init"])).pipe(e$(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),xe(this.video)}createLiveDashPlayer(){let e=new Gr({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,h,p,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(),i=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&dl(t)?t:Ot(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,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=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;hv(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;hv(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(),i=this.videoState.getState(),r=t==="paused"&&i==="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)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var vv=Yr;var qy=D(Be(),1);var Wi=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as UD,assertNonNullable as HD,debounce as jD,ErrorCategory as By,filter as _y,filterChanged as Oa,fromEvent as QD,isNonNullable as Ny,map as ec,merge as Rn,observableFrom as tc,once as Fy,Subscription as GD}from"@vkontakte/videoplayer-shared/es2018";var ln=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];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}},Yi=class extends ln{constructor(){super(),this.listeners||ln.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)}},zr=class{constructor(){Object.defineProperty(this,"signal",{value:new Yi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(zr.prototype[Symbol.toStringTag]="AbortController",Yi.prototype[Symbol.toStringTag]="AbortSignal");function cn(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 ml(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!cn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(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(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Kr=cn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Sv=Kr?ml({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,at=Kr?Sv.fetch:window.fetch,uq=Kr?Sv.Request:window.Request,me=Kr?zr:window.AbortController,lq=Kr?Yi:window.AbortSignal;var Kl=D(bl(),1);var sS=D(aS(),1);import{ErrorCategory as Jr}from"@vkontakte/videoplayer-shared/es2018";var nS=a=>{if(!a)return{id:"EmptyResponse",category:Jr.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Jr.NETWORK,message:`UV Error ${a}`};let e=(0,sS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Jr.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:Jr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Jr.PARSER,message:"Response is valid XML, but parser failed"}};var Bt=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Wl,assertNonNullable as er,combine as tr,ErrorCategory as st,filter as In,filterChanged as Da,flattenObject as Ca,fromEvent as gt,getTraceSubscriptionMethod as xD,interval as Yl,isNonNullable as Va,isNullable as Ly,map as ir,merge as mi,now as zl,Subject as En,Subscription as $y,tap as PD,throttle as wD,ValueSubject as Z}from"@vkontakte/videoplayer-shared/es2018";var pn=D(Be(),1),Ji=D(Ct(),1),hn=D(bl(),1);var G$=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},W$=a=>window.clearTimeout(a),oS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),uS=!oS(window.requestIdleCallback)||!oS(window.cancelIdleCallback),Tl=uS?G$:window.requestIdleCallback,Zr=uS?W$:window.cancelIdleCallback;var gy=D(Hs(),1);import{assertNever as Y$,ErrorCategory as lS,Subject as cS}from"@vkontakte/videoplayer-shared/es2018";var z$=18,dS=!1;try{dS=N.browser.isSafari&&!!N.browser.safariVersion&&N.browser.safariVersion<=z$}catch(a){console.error(a)}var Il=class{constructor(e){this.bufferFull$=new cS;this.error$=new cS;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:lS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};dS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),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 r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.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:lS.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:Y$(t)}}},pS=Il;var El=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 Nt,assertNonNullable as Re,ErrorCategory as bt,fromEvent as Fl,getExponentialDelay as ql,isNonNullable as Xi,isNullable as fe,now as dn,once as dD,Subject as pD,Subscription as hD,ValueSubject as di}from"@vkontakte/videoplayer-shared/es2018";var j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=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,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 zi=class extends j{};var ea=class extends j{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ta=class extends j{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var ia=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends j{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ra=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 aa=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sa=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var li=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 i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var na=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var oa=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=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 la=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ca=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 da=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=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 ha=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ma=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ba=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=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 va=class extends J{constructor(t,i){super(t,i);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 Sa=class extends J{constructor(t,i){super(t,i);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 r=0;r<this.sampleCount;r++)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 ya=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=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 Ia=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var X$={ftyp:ta,moov:ia,mvhd:ra,moof:aa,mdat:sa,sidx:li,trak:na,mdia:da,mfhd:fa,tkhd:pa,traf:ba,tfhd:ga,tfdt:va,trun:Sa,minf:ha,sv3d:oa,st3d:ua,prhd:la,proj:ma,equi:ca,uuid:ea,stbl:ya,stsd:Ta,avc1:Ia,unknown:zi},mt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=X$[e];return i?new i(t,new a):new zi(t,new a)}};var _t=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 Z$=new TextDecoder("ascii"),eM=a=>Z$.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",tM=a=>{let e=new li(a,new mt),t=e.earliestPresentationTime/e.timescale*1e3,i=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:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},iM=(a,e)=>{let i=new mt().parse(a),r=new _t(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.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)},rM=a=>{let t=new mt().parse(a),i=new _t(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},aM=a=>{var r;let t=new mt().parse(a);return(r=new _t(t).find("sidx"))==null?void 0:r.timescale},sM=(a,e)=>{let i=new mt().parse(a),s=new _t(i).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,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},nM=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}}},i=new mt().parse(a),r=new _t(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.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},hS={validateData:eM,parseInit:nM,getIndexRange:()=>{},parseSegments:tM,parseFeedableSegmentChunk:iM,getChunkEndTime:sM,getServerLatencyTimestamps:rM,getTimescaleFromIndex:aM};var xa=D(Be(),1);import{assertNonNullable as Pl,isNonNullable as gS,isNullable as uM}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as oM}from"@vkontakte/videoplayer-shared/es2018";var mS={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"}},fS=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 i=Ea(a,t),r=i in mS,s=r?mS[i].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=Ea(u),d=l*2**((o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},Ea=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*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 Ea(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:oM(e)}},ci=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=fS(i);if(!e(r))return;r.type==="master"&&ci(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},bS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=fS(a);return ci(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ze(o,n):s===17026?t=ze(o,n):s===17029&&(i=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var vS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],lM=[231,22612,22743,167,171,163,160,175],cM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ci(a,({tag:h,type:p,value:m,valueSize:b})=>{if(h===21419){let g=ze(m,p);l=Ea(g)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=ze(m,p):h===17545?r=ze(m,p):h===21420&&l===475249515?u=ze(m,p):h===374648427?ci(m,({tag:g,type:v,value:S})=>g===30321?(c=ze(S,v)===1,!1):!0):s&&n&&(0,xa.default)(vS,h)&&(o=!0),!o}),Pl(e,"Failed to parse webm Segment start"),Pl(t,"Failed to parse webm Segment end"),Pl(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*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}}}},dM=a=>{if(uM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},pM=(a,e)=>{let t=!1,i=!1,r=o=>gS(o.time)&&gS(o.position),s=[],n;return ci(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(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,xa.default)(vS,o)&&(i=!0)}return!(t&&i)}),n&&r(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}}})},hM=a=>{let e=0,t=!1;try{ci(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,xa.default)(lM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,xa.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},SS={validateData:bS,parseInit:cM,getIndexRange:dM,parseSegments:pM,parseFeedableSegmentChunk:hM};var Pa=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return SS;case"mp4":return hS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Bl=D(NS(),1),dy=D(Di(),1),py=D(ty(),1),hy=D(Ct(),1),_l=D(ji(),1);var iy=D(Be(),1),$l=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,iy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as cD,isNullable as ly}from"@vkontakte/videoplayer-shared/es2018";var ry=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var ay=a=>{var e;try{let t=uD(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.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=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.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 uD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
63
+ `}),S};var oe=a=>new URL(a).hostname;import{assertNever as hv,assertNonNullable as mv,combine as e$,debounce as t$,ErrorCategory as fv,filter as bv,filterChanged as i$,isNonNullable as dl,map as un,merge as gv,observableFrom as r$,once as a$,Subscription as s$,ValueSubject as pl,videoQualityToHeight as vv,videoSizeToQuality as n$}from"@vkontakte/videoplayer-shared/es2018";var lv=D(Ct(),1);var av=D(Be(),1),rv=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"))},ke=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!rv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return rv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as sn,isNullable as OL,assertNonNullable as Qr}from"@vkontakte/videoplayer-shared/es2018";var nv=D(ji(),1);import{isNonNullable as sv,assertNonNullable as an,now as CL}from"@vkontakte/videoplayer-shared/es2018";function ue(){return CL()}function ol(a){return ue()-a}function ul(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(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 i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Gi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;an(c);let L=ol(c),U;if(L<b){U=b-L,setTimeout(g,U);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,k()},v=L=>(s=L,q),S=L=>(d=L,q),y=()=>(p="json",q),E=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},T=L=>(h=L,q),k=()=>{c=ue(),n=new r,n.open("get",a);let L=0,U,te=0,H=()=>(an(c),Math.max(c,Math.max(U||0,te||0)));if(s&&n.addEventListener("progress",I=>{let $=ue();s.updateChunk&&I.loaded>L&&(s.updateChunk(H(),I.loaded-L),L=I.loaded,U=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;an(n);let I=n.status;if(I>=200&&I<300){let{response:$,responseType:Y}=n,x=$==null?void 0:$.byteLength;if(typeof x=="number"&&s){let R=x-L;R&&s.updateChunk&&s.updateChunk(H(),R)}Y==="json"&&(!$||!(0,nv.default)($).length)?E():(d&&d(),e($))}else E()}),n.addEventListener("error",()=>{E()}),h){let I=()=>{an(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(te=ue(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=p,n.send(),q},q={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:L=>(l=L,q),withRetryInterval:(L,U)=>(sv(L)&&(b=L),sv(U)&&(m=U),q),withTimeout:L=>(o=L,q),withFinally:S,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var Hr=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,i){return{start:e,end:t,bytes:i}}_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 i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/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(r)}/${Math.round(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),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=D(ji(),1);var jr=class{constructor(e,t,i,r,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=i,this.MAX_PARALLEL_REQUESTS=r,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 i=ue(),r=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()-i,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=Gi(t,s,()=>r("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 i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,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}`),i(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=i,s._retryCB=r,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 BL}from"@vkontakte/videoplayer-shared/es2018";var nn=1e4,ll=3;var _L=6e4,NL=10,FL=1,qL=500,Gr=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 BL,this.chunkRateEstimator=new Hr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ul(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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=ul(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,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,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)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||sn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ov(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 jr(ll,nn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=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},h=(E,T,k)=>{u&&u.abort(),u=Gi(this.urlResolver.resolve(E,!1),T,k,()=>this._retryCallback()).withTimeout(nn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ll).withFinally(()=>{u=null}).send()},p=(E,T,k)=>{Qr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let T=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),i.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 k=ue()-1e4,B=0;for(let _=0;_<this.bufferStates.length;_++){let A=this.bufferStates[_];E=Math.min(E,A.buf),A.ts<k&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${E} drop=${B} jitter=${this.sourceJitter}`);let O=E-FL;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},v=E=>{let T,k=()=>T&&T.start?T.start.length:0,B=I=>T.start[I]/1e3,O=I=>T.dur[I]/1e3,_=I=>T.fragIndex+I,A=(I,$)=>({chunkIdx:_(I),startTS:B(I),dur:O(I),discontinuity:$}),q=()=>{let I=0;if(T&&T.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=$;this.sourceJitter>1&&(x+=this.sourceJitter-1);let R=T.dur.length-1;for(;R>=0&&(x-=T.dur[R],!(x<=0));--R);I=Math.min(R,T.dur.length-1-Y),I=Math.max(I,0)}return A(I,!0)},L=I=>{let $=k();if(!($<=0)){if(sn(I)){for(let Y=0;Y<$;Y++)if(B(Y)>I)return A(Y)}return q()}},U=I=>{let $=k(),Y=I?I.chunkIdx+1:0,x=Y-T.fragIndex;if(!($<=0)){if(!I||x<0||x-$>NL)return t(`Resync: offset=${x} bChunks=${$} chunk=`+JSON.stringify(I)),q();if(!(x>=$))return A(Y-T.fragIndex,!1)}},te=(I,$,Y)=>{l&&l.abort(),l=Gi(this.urlResolver.resolve(I,!0,this.lowLatency),$,Y,()=>this._retryCallback()).withTimeout(nn).withRetryCount(ll).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(I,$)=>{te(E,Y=>{if(!d())return;T=Y;let x=!!T.lowLatency;x!==this.lowLatency&&b(x);let R=0;for(let ce=0;ce<T.dur.length;++ce)R+=T.dur[ce];R>0&&(Qr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(R/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,I(L($))},()=>this._handleNetworkError())},nextChunk:U}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Qr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:T,logger:k}=this.params,B=v(e.jidxUrl),O,_,A,q,L=0,U,te,H,I=()=>{U&&(clearTimeout(U),U=void 0);let G=Math.max(qL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=L+G,Te=ue(),Ie=Math.min(1e4,be-Te);L=Te;let Xe=()=>{l||d()&&B.seek(()=>{d()&&(L=ue(),$(),I())})};Ie>0?U=window.setTimeout(()=>{this.paused?I():Xe()},Ie):Xe()},$=()=>{let G;for(;G=B.nextChunk(q);)q=G,bi(G);let be=B.nextChunk(A);if(be){if(A&&be.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?I():(S(),this._initPlayerWith(e));return}ce(be)}else I()},Y=(G,be)=>{if(!d()||!this.sourceBuffer)return;let Te,Ie,Xe,ot=yt=>{window.setTimeout(()=>{d()&&Y(G,be)},yt)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),ot(100);else{let yt=ue(),jt=T.currentTime;!this.paused&&T.buffered.length>1&&te===jt&&yt-H>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),te!==jt&&(te=jt,H=yt);let gi=this._getBufferSizeSec();if(gi>30)k(`Buffered ${gi} seconds; delaying appendBuffer`),ot(2e3);else try{this.sourceBuffer.appendBuffer(G),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:gi}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(sr){if(sr.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),Xe=this.sourceBuffer.buffered.length,Xe!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=jt,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),ot(1e3);else throw sr}}},x=()=>{_&&O&&(k([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(A)]),Y(_,function(){_=null,$()}))},R=G=>e.fragUrlTemplate.replace("%%id%%",G.chunkIdx),ce=G=>{d()&&p(R(G),(be,Te)=>{if(d()){if(Te/=1e3,_=be,A=G,n=G.startTS,Te){let Ie=Math.min(10,G.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}x()}},()=>this._handleNetworkError())},bi=G=>{d()&&(Qr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(R(G),!1)))},nt=G=>{d()&&(e.cachedHeader=G,Y(G,()=>{O=!0,x()}))};s=!0,B.seek(G=>{if(d()){if(L=ue(),!G){I();return}q=G,!OL(E)||G.startTS>E?ce(G):(A=G,$())}},E),e.cachedHeader?nt(e.cachedHeader):h(e.headerUrl,nt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),sn(r)&&(r+=.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,Qr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return sn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=ue();if(this.chunkRateEstimator.addInterval(h,m,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ol(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ue();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Gi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(nn).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:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.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):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},_L))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var pv=D(Di(),1);import{debounce as UL,filter as cv,fromEvent as HL,interval as jL,isHigher as QL,isInvariantQuality as GL,isLower as WL,merge as YL,Subject as dv,Subscription as zL}from"@vkontakte/videoplayer-shared/es2018";var cl=class{constructor(){this.onDroopedVideoFramesLimit$=new dv;this.subscription=new zL;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&&!GL(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&QL(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(HL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=jL(this.droppedFramesChecker.checkTime).pipe(cv(()=>this.playing),cv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(UL(this.droppedFramesChecker.checkTime)),i=YL(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),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 i,r;let t=(r=(i=(0,pv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>WL(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[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}},on=cl;import{map as KL,Observable as XL}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as JL}from"@vkontakte/videoplayer-shared/es2018";var Wr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var ZL=(a,e)=>new XL(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Wr()))},{...i,...e});r.observe(a);let s=JL(document,"visibilitychange").pipe(KL(n=>!document.hidden||Wr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Fe=ZL;var o$=["paused","playing","ready"],u$=["paused","playing","ready"],Yr=class{constructor(e){this.subscription=new s$;this.videoState=new C("stopped");this.representations$=new pl([]);this.droppedFramesManager=new on;this.maxSeekBackTime$=new pl(1/0);this.zeroTime$=new pl(void 0);this.liveOffset=new ui;this._dashCb=e=>{var t,i,r,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=(i=Dt(u.name))!=null?i:n$(u.video),d=u.bitrate/1e3,h={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.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),dl(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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="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,hl.default)(u$,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,hl.default)(o$,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(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="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 hv(e)}};this.textTracksManager=new Ne(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:fv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(gv(this.videoState.stateChangeStarted$.pipe(un(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(un(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ee(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 i=Ae(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(un(r=>r.map(({track:s})=>s)),bv(r=>!!r.length),a$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(i$(),un(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(e$({zeroTime:this.zeroTime$.pipe(bv(dl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(it(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(_e(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Fe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&vv(r),min:s&&vv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.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(r.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$,r$(["init"])).pipe(t$(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),xe(this.video)}createLiveDashPlayer(){let e=new Gr({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,h,p,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(),i=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&dl(t)?t:Ot(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,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=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),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,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.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(),i=this.videoState.getState(),r=t==="paused"&&i==="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)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Sv=Yr;var qy=D(Be(),1);var Wi=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as HD,assertNonNullable as jD,debounce as QD,ErrorCategory as _y,filter as ec,filterChanged as Oa,fromEvent as GD,isNonNullable as Ny,map as tc,merge as Rn,observableFrom as ic,once as Fy,Subscription as WD}from"@vkontakte/videoplayer-shared/es2018";var ln=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];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}},Yi=class extends ln{constructor(){super(),this.listeners||ln.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)}},zr=class{constructor(){Object.defineProperty(this,"signal",{value:new Yi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(zr.prototype[Symbol.toStringTag]="AbortController",Yi.prototype[Symbol.toStringTag]="AbortSignal");function cn(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 ml(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!cn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(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(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Kr=cn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),yv=Kr?ml({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,at=Kr?yv.fetch:window.fetch,uq=Kr?yv.Request:window.Request,me=Kr?zr:window.AbortController,lq=Kr?Yi:window.AbortSignal;var Kl=D(bl(),1);var nS=D(sS(),1);import{ErrorCategory as Jr}from"@vkontakte/videoplayer-shared/es2018";var oS=a=>{if(!a)return{id:"EmptyResponse",category:Jr.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Jr.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:Jr.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:Jr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Jr.PARSER,message:"Response is valid XML, but parser failed"}};var Bt=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Wl,assertNonNullable as er,combine as tr,ErrorCategory as st,filter as In,filterChanged as Da,flattenObject as Ca,fromEvent as gt,getTraceSubscriptionMethod as PD,interval as Yl,isNonNullable as Va,isNullable as $y,map as ir,merge as mi,now as zl,Subject as En,Subscription as My,tap as wD,throttle as AD,ValueSubject as Z}from"@vkontakte/videoplayer-shared/es2018";var pn=D(Be(),1),Ji=D(Ct(),1),hn=D(bl(),1);var W$=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Y$=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),Tl=lS?W$:window.requestIdleCallback,Zr=lS?Y$:window.cancelIdleCallback;var vy=D(Hs(),1);import{assertNever as z$,ErrorCategory as cS,Subject as dS}from"@vkontakte/videoplayer-shared/es2018";var K$=18,pS=!1;try{pS=N.browser.isSafari&&!!N.browser.safariVersion&&N.browser.safariVersion<=K$}catch(a){console.error(a)}var Il=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)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};pS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),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 r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.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:z$(t)}}},hS=Il;var El=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 Nt,assertNonNullable as Re,ErrorCategory as bt,fromEvent as Fl,getExponentialDelay as ql,isNonNullable as Xi,isNullable as fe,now as dn,once as pD,Subject as hD,Subscription as mD,ValueSubject as di}from"@vkontakte/videoplayer-shared/es2018";var j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=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,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}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 zi=class extends j{};var ea=class extends j{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ta=class extends j{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var ia=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends j{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ra=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 aa=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sa=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var li=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 i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var na=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var oa=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=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 la=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ca=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 da=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=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 ha=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ma=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ba=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=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 va=class extends J{constructor(t,i){super(t,i);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 Sa=class extends J{constructor(t,i){super(t,i);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 r=0;r<this.sampleCount;r++)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 ya=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=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 Ia=class extends j{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var J$={ftyp:ta,moov:ia,mvhd:ra,moof:aa,mdat:sa,sidx:li,trak:na,mdia:da,mfhd:fa,tkhd:pa,traf:ba,tfhd:ga,tfdt:va,trun:Sa,minf:ha,sv3d:oa,st3d:ua,prhd:la,proj:ma,equi:ca,uuid:ea,stbl:ya,stsd:Ta,avc1:Ia,unknown:zi},mt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=J$[e];return i?new i(t,new a):new zi(t,new a)}};var _t=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 eM=new TextDecoder("ascii"),tM=a=>eM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",iM=a=>{let e=new li(a,new mt),t=e.earliestPresentationTime/e.timescale*1e3,i=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:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},rM=(a,e)=>{let i=new mt().parse(a),r=new _t(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.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)},aM=a=>{let t=new mt().parse(a),i=new _t(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},sM=a=>{var r;let t=new mt().parse(a);return(r=new _t(t).find("sidx"))==null?void 0:r.timescale},nM=(a,e)=>{let i=new mt().parse(a),s=new _t(i).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,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},oM=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}}},i=new mt().parse(a),r=new _t(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.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:tM,parseInit:oM,getIndexRange:()=>{},parseSegments:iM,parseFeedableSegmentChunk:rM,getChunkEndTime:nM,getServerLatencyTimestamps:aM,getTimescaleFromIndex:sM};var xa=D(Be(),1);import{assertNonNullable as Pl,isNonNullable as vS,isNullable as lM}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as uM}from"@vkontakte/videoplayer-shared/es2018";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 i=Ea(a,t),r=i in fS,s=r?fS[i].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=Ea(u),d=l*2**((o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},Ea=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*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 Ea(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:uM(e)}},ci=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=bS(i);if(!e(r))return;r.type==="master"&&ci(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},gS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=bS(a);return ci(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ze(o,n):s===17026?t=ze(o,n):s===17029&&(i=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var SS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],cM=[231,22612,22743,167,171,163,160,175],dM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ci(a,({tag:h,type:p,value:m,valueSize:b})=>{if(h===21419){let g=ze(m,p);l=Ea(g)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=ze(m,p):h===17545?r=ze(m,p):h===21420&&l===475249515?u=ze(m,p):h===374648427?ci(m,({tag:g,type:v,value:S})=>g===30321?(c=ze(S,v)===1,!1):!0):s&&n&&(0,xa.default)(SS,h)&&(o=!0),!o}),Pl(e,"Failed to parse webm Segment start"),Pl(t,"Failed to parse webm Segment end"),Pl(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*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}}}},pM=a=>{if(lM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hM=(a,e)=>{let t=!1,i=!1,r=o=>vS(o.time)&&vS(o.position),s=[],n;return ci(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(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,xa.default)(SS,o)&&(i=!0)}return!(t&&i)}),n&&r(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{ci(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,xa.default)(cM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,xa.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},yS={validateData:gS,parseInit:dM,getIndexRange:pM,parseSegments:hM,parseFeedableSegmentChunk:mM};var Pa=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return yS;case"mp4":return mS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Bl=D(FS(),1),py=D(Di(),1),hy=D(iy(),1),my=D(Ct(),1),_l=D(ji(),1);var ry=D(Be(),1),$l=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,ry.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as dD,isNullable as cy}from"@vkontakte/videoplayer-shared/es2018";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=lD(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.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=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.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 lD(){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 Dl=D(Ct(),1);import{videoSizeToQuality as lD}from"@vkontakte/videoplayer-shared/es2018";var sy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Dt(s):void 0)!=null?u:lD({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},ny=({id:a,bitrate:e})=>({id:a,bitrate:e}),oy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),uy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Cl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Dl.default)(i.split("."),0),isDefault:r}),Vl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Dl.default)(r.split("."),0)}),Ol=a=>"url"in a,ye=a=>a.type==="template",wa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var cy=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},i=/^(-|\+)?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),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ft=(a,e)=>{let t=a;t=(0,Bl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,dy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Bl.default)(t,n,(o,u)=>ly(s)?o:ly(u)?s:(0,py.default)(s,parseInt(u,10),"0"))}return t},my=(a,e)=>{var _,A,q,L,U,te,H,I,$,Y,x,R,ce,bi,nt,G,be,Te,Ie,Xe,ot,yt,jt,gi,sr,Ic,Ec,xc,Pc,wc,Ac,kc,Rc,Lc,$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,id,rd;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(qe=>{var X,Qt;return(Qt=(X=qe.textContent)==null?void 0:X.trim())!=null?Qt:""}),o=(_=(0,hy.default)(n,0))!=null?_:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],h=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],E=y.reduce((qe,X)=>({...qe,[X.id]:X.children}),{}),T=y.reduce((qe,X)=>({...qe,[X.id]:X.getAttribute("duration")}),{});S?v=cy(S):(0,_l.default)(T).filter(qe=>qe).length&&!u?v=(0,_l.default)(T).reduce((qe,X)=>{var Qt;return qe+((Qt=cy(X))!=null?Qt:0)},0):b&&(v=parseInt(b,10));let k=0,B=(q=(A=s.getAttribute("profiles"))==null?void 0:A.split(","))!=null?q:[];for(let qe of y.map(X=>X.id))for(let X of E[qe]){let Qt=(L=X.getAttribute("id"))!=null?L:"id"+(k++).toString(10),nr=(U=X.getAttribute("mimeType"))!=null?U:"",Qn=(te=X.getAttribute("codecs"))!=null?te:"",Gn=(H=X.getAttribute("contentType"))!=null?H:nr==null?void 0:nr.split("/")[0],BT=($=(I=X.getAttribute("profiles"))==null?void 0:I.split(","))!=null?$:[],ad=(x=ay((Y=X.getAttribute("lang"))!=null?Y:""))!=null?x:{},za=(bi=(ce=(R=X.querySelector("Label"))==null?void 0:R.textContent)==null?void 0:ce.trim())!=null?bi:void 0,_T=X.querySelectorAll("Representation"),NT=X.querySelector("SegmentTemplate"),FT=(G=(nt=X.querySelector("Role"))==null?void 0:nt.getAttribute("value"))!=null?G:void 0,vi=Gn,ie={id:Qt,language:ad.language,isDefault:FT==="main",label:za,codecs:Qn,hdr:vi==="video"&&$l(Qn),mime:nr,representations:[]};for(let K of _T){let Tt=(be=K.getAttribute("lang"))!=null?be:void 0,or=(Ie=(Te=za!=null?za:X.getAttribute("label"))!=null?Te:K.getAttribute("label"))!=null?Ie:void 0,Ka=(yt=(ot=(Xe=K.querySelector("BaseURL"))==null?void 0:Xe.textContent)==null?void 0:ot.trim())!=null?yt:"",Gt=new URL(Ka||o,e).toString(),It=(jt=K.getAttribute("mimeType"))!=null?jt:nr,Xa=(sr=(gi=K.getAttribute("codecs"))!=null?gi:Qn)!=null?sr:"",Ja;if(Gn==="text"){let Et=K.getAttribute("id")||"",Za=((Ic=ad.privateuse)==null?void 0:Ic.includes("x-auto"))||Et.includes("_auto"),Wt=K.querySelector("SegmentTemplate");if(Wt){let ur={representationId:(Ec=K.getAttribute("id"))!=null?Ec:void 0,bandwidth:(xc=K.getAttribute("bandwidth"))!=null?xc:void 0},es=parseInt((Pc=K.getAttribute("bandwidth"))!=null?Pc:"",10)/1e3,ts=(Ac=parseInt((wc=Wt.getAttribute("startNumber"))!=null?wc:"",10))!=null?Ac:1,Si=parseInt((kc=Wt.getAttribute("timescale"))!=null?kc:"",10),Wn=(Rc=Wt.querySelectorAll("SegmentTimeline S"))!=null?Rc:[],yi=Wt.getAttribute("media");if(!yi)continue;let is=[],rs=0,as="",Ti=0,lr=ts,ge=0;for(let Ue of Wn){let Yt=parseInt((Lc=Ue.getAttribute("d"))!=null?Lc:"",10),Oe=parseInt(($c=Ue.getAttribute("r"))!=null?$c:"",10)||0,xt=parseInt((Mc=Ue.getAttribute("t"))!=null?Mc:"",10);ge=Number.isFinite(xt)?xt:ge;let zt=Yt/Si*1e3,Pt=ge/Si*1e3;for(let Je=0;Je<Oe+1;Je++){let wt=ft(yi,{...ur,segmentNumber:lr.toString(10),segmentTime:(ge+Je*Yt).toString(10)}),Ii=(Pt!=null?Pt:0)+Je*zt,dr=Ii+zt;lr++,is.push({time:{from:Ii,to:dr},url:wt})}ge+=(Oe+1)*Yt,rs+=(Oe+1)*zt}Ti=ge/Si*1e3,as=ft(yi,{...ur,segmentNumber:lr.toString(10),segmentTime:ge.toString(10)});let cr={time:{from:Ti,to:1/0},url:as},ut={type:"template",baseUrl:Gt,segmentTemplateUrl:yi,initUrl:"",totalSegmentsDurationMs:rs,segments:is,nextSegmentBeyondManifest:cr,timescale:Si};Ja={id:Et,kind:"text",segmentReference:ut,profiles:[],duration:v,bitrate:es,mime:"",codecs:"",width:0,height:0,isAuto:Za}}else Ja={id:Et,isAuto:Za,kind:"text",url:Gt}}else{let Et=(Cc=(Dc=K.getAttribute("contentType"))!=null?Dc:It==null?void 0:It.split("/")[0])!=null?Cc:Gn,Za=(Oc=(Vc=X.getAttribute("profiles"))==null?void 0:Vc.split(","))!=null?Oc:[],Wt=parseInt((Bc=K.getAttribute("width"))!=null?Bc:"",10),ur=parseInt((_c=K.getAttribute("height"))!=null?_c:"",10),es=parseInt((Nc=K.getAttribute("bandwidth"))!=null?Nc:"",10)/1e3,ts=(Fc=K.getAttribute("frameRate"))!=null?Fc:"",Si=(qc=K.getAttribute("quality"))!=null?qc:void 0,Wn=ts?ry(ts):void 0,yi=(Uc=K.getAttribute("id"))!=null?Uc:"id"+(k++).toString(10),is=Et==="video"?`${ur}p`:Et==="audio"?`${es}Kbps`:Xa,rs=`${yi}@${is}`,as=[...B,...BT,...Za],Ti,lr=K.querySelector("SegmentBase"),ge=(Hc=K.querySelector("SegmentTemplate"))!=null?Hc:NT;if(lr){let ut=(Qc=(jc=K.querySelector("SegmentBase Initialization"))==null?void 0:jc.getAttribute("range"))!=null?Qc:"",[Ue,Yt]=ut.split("-").map(wt=>parseInt(wt,10)),Oe={from:Ue,to:Yt},xt=(Gc=K.querySelector("SegmentBase"))==null?void 0:Gc.getAttribute("indexRange"),[zt,Pt]=xt?xt.split("-").map(wt=>parseInt(wt,10)):[],Je=xt?{from:zt,to:Pt}:void 0;Ti={type:"byteRange",url:Gt,initRange:Oe,indexRange:Je}}else if(ge){let ut={representationId:(Wc=K.getAttribute("id"))!=null?Wc:void 0,bandwidth:(Yc=K.getAttribute("bandwidth"))!=null?Yc:void 0},Ue=parseInt((zc=ge.getAttribute("timescale"))!=null?zc:"",10),Yt=(Kc=ge.getAttribute("initialization"))!=null?Kc:"",Oe=ge.getAttribute("media"),xt=(Jc=parseInt((Xc=ge.getAttribute("startNumber"))!=null?Xc:"",10))!=null?Jc:1,zt=ft(Yt,ut);if(!Oe)throw new ReferenceError("No media attribute in SegmentTemplate");let Pt=(Zc=ge.querySelectorAll("SegmentTimeline S"))!=null?Zc:[],Je=[],wt=0,Ii="",dr=0;if(Pt.length){let ss=xt,He=0;for(let Ei of Pt){let Ze=parseInt((ed=Ei.getAttribute("d"))!=null?ed:"",10),Kt=parseInt((td=Ei.getAttribute("r"))!=null?td:"",10)||0,ns=parseInt((id=Ei.getAttribute("t"))!=null?id:"",10);He=Number.isFinite(ns)?ns:He;let Yn=Ze/Ue*1e3,zn=He/Ue*1e3;for(let os=0;os<Kt+1;os++){let UT=ft(Oe,{...ut,segmentNumber:ss.toString(10),segmentTime:(He+os*Ze).toString(10)}),sd=(zn!=null?zn:0)+os*Yn,HT=sd+Yn;ss++,Je.push({time:{from:sd,to:HT},url:UT})}He+=(Kt+1)*Ze,wt+=(Kt+1)*Yn}dr=He/Ue*1e3,Ii=ft(Oe,{...ut,segmentNumber:ss.toString(10),segmentTime:He.toString(10)})}else if(cD(v)){let He=parseInt((rd=ge.getAttribute("duration"))!=null?rd:"",10)/Ue*1e3,Ei=Math.ceil(v/He),Ze=0;for(let Kt=1;Kt<Ei;Kt++){let ns=ft(Oe,{...ut,segmentNumber:Kt.toString(10),segmentTime:Ze.toString(10)});Je.push({time:{from:Ze,to:Ze+He},url:ns}),Ze+=He}dr=Ze,Ii=ft(Oe,{...ut,segmentNumber:Ei.toString(10),segmentTime:Ze.toString(10)})}let qT={time:{from:dr,to:1/0},url:Ii};Ti={type:"template",baseUrl:Gt,segmentTemplateUrl:Oe,initUrl:zt,totalSegmentsDurationMs:wt,segments:Je,nextSegmentBeyondManifest:qT,timescale:Ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Et||!It)continue;let cr={video:"video",audio:"audio",text:"text"}[Et];if(!cr)continue;vi||(vi=cr),Ja={id:rs,kind:cr,segmentReference:Ti,profiles:as,duration:v,bitrate:es,mime:It,codecs:Xa,width:Wt,height:ur,fps:Wn,quality:Si}}ie.language||(ie.language=Tt),ie.label||(ie.label=or),ie.mime||(ie.mime=It),ie.codecs||(ie.codecs=Xa),ie.hdr||(ie.hdr=vi==="video"&&$l(Xa)),ie.representations.push(Ja)}if(vi){let K=r[vi].find(Tt=>Tt.id===ie.id);if(K&&ie.representations.every(Tt=>ye(Tt.segmentReference)))for(let Tt of K.representations){let or=ie.representations.find(It=>It.id===Tt.id),Ka=or==null?void 0:or.segmentReference,Gt=Tt.segmentReference;Gt.segments.push(...Ka.segments),Gt.nextSegmentBeyondManifest=Ka.nextSegmentBeyondManifest}else r[vi].push(ie)}}return{duration:v,streams:r,baseUrls:n,live:g}};var by=D(Be(),1);import{isNonNullable as fy}from"@vkontakte/videoplayer-shared/es2018";var ae=(a,e)=>fy(a)&&fy(e)&&a.readyState==="open"&&(0,by.default)([...a.activeSourceBuffers],e);var Aa=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new di(0);this.currentLowLatencySegmentLength$=new di(0);this.currentSegmentLength$=new di(0);this.onLastSegment$=new di(!1);this.fullyBuffered$=new di(!1);this.playingRepresentation$=new di(void 0);this.playingRepresentationInit$=new di(void 0);this.error$=new pD;this.gaps=[];this.subscription=new hD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new me;this.switchAbortController=new me;this.destroyAbortController=new me;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=Nt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new pS(this.sourceBuffer),this.subscription.add(Fl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Fl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:bt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ae(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,El(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(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 i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Re(i,"No init buffer for starting representation"),Re(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Nt(this.destroyAbortController.signal,async function*(e,t=!1){if(!ae(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ae(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();Xi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Nt(this.destroyAbortController.signal,async function*(e,t=!1){if(!ae(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ae(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();Xi(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Nt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,hn.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 h=this.representations.get(c);if(!h||!ye(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Re(r);let s=this.segments.get(i);Re(s,"No segments for starting representation");let n=this.initData.get(i);if(Re(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,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ae(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new me,Nt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Re(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(fe(o)||fe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Re(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Xi(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!fe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(fe(e)||fe(this.downloadingRepresentationId)||fe(this.playingRepresentationId)||fe(this.sourceBuffer)||!ae(this.mediaSource,this.sourceBuffer)||Xi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Xi(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&El(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,pn.default)(u,r))c="high";else{let d=(0,Ji.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ji.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Xi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,hn.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,hn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];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(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,Ji.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!ye(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],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=ft(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 i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.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&&Zr&&Zr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Zr&&Zr(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,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let b=h<=i&&p>=i,g=h>i||b||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+v||p<=i+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&ae(this.mediaSource,this.sourceBuffer)&&!(Bt(this.sourceBuffer.buffered,h)&&Bt(this.sourceBuffer.buffered,p)))&&g&&S});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+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=r;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){ye(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Nt(o,async function*(){let c=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=dn(),!c)return;let d=new DataView(c),h=Pa(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),wa(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}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Nt(n,async function*(){let u=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Fl(window,"online").pipe(dD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=dn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),wa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ye(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ji.default)(e,0).byte.from,to:(0,Ji.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=dn(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:bt.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 i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=dn();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:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,pn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!ae(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Pa(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ae(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,h=d-c+1,p=c<r,m=d<=r;if(!p)continue;let b=Pa(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===h?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(fe(this.sourceBuffer)||!ae(this.mediaSource,this.sourceBuffer))){!this.isLive&&N.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Bt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Bt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:bt.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",Ol(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])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[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tl(()=>(0,gy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Nt(this.destroyAbortController.signal,async function*(){let o=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Pa(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&ye(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:bt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||fe(e))return!1;let r=[],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:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Ol(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 h of this.segments.values())for(let p of h)(0,pn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){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 r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ae(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||!ae(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(e=this.getCurrentPosition()){return!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||fe(e)?0:Wi(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.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<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tl(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:bt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(fe(this.sourceBuffer)||!ae(this.mediaSource,this.sourceBuffer)||fe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.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?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:bt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ka=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var vy=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as Ra,assertNever as yy,fromEvent as Ty,merge as mD,now as La,Subscription as fD,Subject as Iy,ValueSubject as Ul,flattenObject as Zi,ErrorCategory as $a}from"@vkontakte/videoplayer-shared/es2018";var Sy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var fn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Ul(void 0);this.lastConnectionReused$=new Ul(void 0);this.lastRequestFirstBytes$=new Ul(void 0);this.recoverableError$=new Iy;this.error$=new Iy;this.abortAllController=new me;this.subscription=new fD;this.fetchManifest=Ra(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ka(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Sy(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(mn);return r?(t.log("success",Zi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Zi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ra(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,U,te;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let H=new URL(l,location.href);H.searchParams.append("bytes",`${i.from}-${i.to}`),l=H.toString();break}default:yy(t)}this.requestQuic&&(l=ka(l));let h=this.abortAllController.signal,p;if(n){let H=new me;if(p=mD(Ty(this.abortAllController.signal,"abort"),Ty(n,"abort")).subscribe(()=>{try{H.abort()}catch(I){mn(I)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{H.abort()}catch(I){mn(I)}h=H.signal}let m=La();d.log("startRequest",Zi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:h}),g=La();if(!b)return d.error("error",{message:"No response in request"}),d.end(),p==null||p.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(g-m),!b.ok||!b.body){p==null||p.unsubscribe();let H=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:H}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){p==null||p.unsubscribe();let H=La(),I={requestStartedAt:m,requestEndedAt:H,duration:H-m};return d.log("endRequest",Zi(I)),d.end(),b.arrayBuffer()}let v=b.body;if(o){let H;[v,H]=b.body.tee(),(U=this.throughputEstimator)==null||U.trackStream(H,u)}let S=v.getReader(),y,E=parseInt((te=b.headers.get("content-length"))!=null?te:"",10);Number.isFinite(E)&&(y=E),!y&&i&&(y=i.to-i.from+1);let T=0,k=y?new Uint8Array(y):new Uint8Array(0),B=!1,O=H=>{p==null||p.unsubscribe(),B=!0,mn(H)},_=Ra(h,async function*({done:H,value:I}){if(T===0&&this.lastRequestFirstBytes$.next(La()-m),h.aborted){p==null||p.unsubscribe();return}if(!H&&I){if(y)k.set(I,T),T+=I.byteLength;else{let $=new Uint8Array(k.length+I.length);$.set(k),$.set(I,k.length),k=$,T+=I.byteLength}r==null||r(new DataView(k.buffer),T),yield S==null?void 0:S.read().then(_,O)}}.bind(this));yield S==null?void 0:S.read().then(_,O),p==null||p.unsubscribe();let A=La(),q={failed:B,requestStartedAt:m,requestEndedAt:A,duration:A-m};return B?(d.error("endRequest",Zi(q)),d.end(),null):(d.log("endRequest",Zi(q)),d.end(),k.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ra(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,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,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(v=e.indexRange)!=null?v:t.getIndexRange(p);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:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,p,m);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ra(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=vy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:yy(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await at(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:$a.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:$a.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:$a.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:$a.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:$a.FATAL})}}},mn=a=>{if(!wa(a))throw a};var pi=(a,e,t)=>t*e+(1-t)*a,Hl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Ey=(a,e,t,i)=>{let r=0,s=t,n=Hl(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as bD,ValueSubject as xy}from"@vkontakte/videoplayer-shared/es2018";var Ft=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new xy(e.initial),this.debounced$=new xy(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;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)&&(bD(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 bn=class extends Ft{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=pi(this.slow,e,this.params.emaAlphaSlow),this.fast=pi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var gn=class extends Ft{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Hl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pi(this.emaSmoothed,e,this.params.emaAlpha);let i=Ey(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var vn=class extends Ft{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?pi(this.smoothed,t,this.params.emaAlpha):t}};var hi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new bn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new gn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new vn({initial:e,label:"liveEdgeDelay",...t})}};var jl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as gD,ValueSubject as vD}from"@vkontakte/videoplayer-shared/es2018";var Ma=class a{constructor(e,t){this.currentRepresentation$=new vD(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(!gD(e))for(let i of this.representations)for(let r of i){let s=r.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,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 i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,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 yn=D(Ct(),1);import{assertNever as Tn}from"@vkontakte/videoplayer-shared/es2018";var Py=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=N.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(r.mp4||r.webm);default:return Tn(c)}})},Sn=a=>{let{webmDecodingInfo:e}=N.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Tn(a)}return[t,i]},wy=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Sn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(N.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Sn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Sn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Sn(a),...r,"HLS","HLS_ONDEMAND"];default:Tn(e)}return N.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Ay=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],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:Tn(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"]},Ql=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ky=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,yn.default)(t.value.split("."),0)}for(let t of a){let i=(0,yn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,yn.default)(e.value.split("."),0)};var AD=["timeupdate","progress","play","seeked","stalled","waiting"],kD=["timeupdate","progress","loadeddata","playing","seeked"];var xn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new $y;this.representationSubscription=new $y;this.state$=new C("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new En;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new En;this.fetcherError$=new En;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new En;this.gapWatchdogActive=!1;this.destroyController=new me;this.initManifest=Wl(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=he(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:st.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Wl(this.destroyController.signal,async 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:st.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=my(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=nS(e))!=null?n:{id:"ManifestParsing",category:st.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=Ye())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>i(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=ky(d);if(h&&(r[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=r.video.some(g=>g.hdr),b=r.video.some(g=>!g.hdr);N.display.isHDR&&p&&m?r.video=r.video.filter(g=>g.hdr):b&&(r.video=r.video.filter(g=>!g.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",Ca(s)),s}.bind(this));this.initRepresentations=Wl(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",Ca({initialVideo:e,initialAudio:t,sourceHls:i})),er(this.manifest),er(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(gt(p,"error").pipe(In(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:st.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Ag():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ks())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.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,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new Aa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Va(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new Aa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ma.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ma(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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(mi(...kD.map(p=>gt(this.element,p))).pipe(ir(p=>this.element?Wi(this.element.buffered,this.element.currentTime*1e3):0),Da(),PD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(mi(gt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Da()).subscribe(m=>this.liveStreamEndTimestamp=zl())),this.subscription.add(gt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Yl(1e3).subscribe(m=>{let b=js(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(gt(this.element,"play").subscribe(m=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add(tr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ir(({isActiveLive:m,isLowLatency:b})=>m&&b),Da()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||jl(this.element,1)})),this.representationSubscription.add(tr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(In(({bufferLength:m,isActiveLive:b,isLowLatency:g})=>b&&g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(m=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!m)return;let b=this.liveSeekableDuration$.getValue()-m/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+m/1e3)})),this.representationSubscription.add(tr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(In(({isLive:m})=>m),Da((m,b)=>b.bufferLength<m.bufferLength),ir(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=js(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(tr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:m,isActiveLive:b,isLowLatency:g})=>{if(!g||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=m-v;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(E)>S&&(T=1+Math.sign(E)*y),jl(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let b=0;if(m){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var T,k;return(k=(T=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?k:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(tr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(wD(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:b})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=js(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,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,k=isFinite(m)?m:b,B=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let _="none";if(B?_="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(A=>A.proceedLowLatencyLive()),_="active_low_latency"):v!==0&&k<y?_="live_forward_buffering":k<y+T&&(_="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),_==="live_forward_buffering"||_==="live_with_target_offset"){let A=p-(y+E),q=this.normolizeLiveOffset(Math.trunc(v+A/g)),L=Math.abs(q-v),U=0;!m||L<=this.tuning.dashCmafLive.offsetCalculationError?U=v:q>0&&L>this.tuning.dashCmafLive.offsetCalculationError&&(U=q),this.manifestUrlString=he(this.manifestUrlString,U,2)}(_==="live_with_target_offset"||_==="live_forward_buffering")&&(p=0,await this.updateLive())},m=>{this.error$.next({id:"updateLive",category:st.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=mi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ir(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=mi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ir(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=tr({allBuffersFull:l,someBufferEnded:c}).pipe(Da(),ir(({allBuffersFull:p,someBufferEnded:m})=>p&&m),In(p=>p));if(this.representationSubscription.add(mi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:st.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add(mi(...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"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((m,b)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){m();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):m()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),m()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,Kl.default)((0,Kl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let b=[];return m.duration&&b.push(m.duration),ye(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&b.push(m.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Va(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,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Yl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:st.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new fn({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=hi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;er(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?zl()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=he(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){er(this.element),this.state$.setState("running"),this.subscription.add(mi(...AD.map(e=>gt(this.element,e)),gt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:st.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(gt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(gt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Bt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,b,g,v,S,y,E,T,k,B;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=zl(),n=100,o=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(y=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?y:0,c=(T=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?T:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let O=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(O).catch(_=>{this.error$.next({id:"stallIntervalCallback",category:st.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:_})}),r.liveLastOffset=O}else{let O=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(O),(B=this.audioBufferManager)==null||B.maintain(O),r.position=O}this.tracer.log("stallIntervalCallback",Ca(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Yl(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:st.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;er(this.element),er(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Bt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Ly(this.element)||Ly(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ca({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Va(this.element)&&Va(this.source)&&Va(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=xD(this.tracer.error.bind(this.tracer));this.subscription.add(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}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.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(),i={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 r=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<=r&&u.to+n>r&&(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,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ca(i)))}}};var Pn=class{constructor(e,t){this.fov=e,this.orientation=t}};var wn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i: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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var My=`attribute vec2 a_vertex;
70
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Dl=D(Ct(),1);import{videoSizeToQuality as cD}from"@vkontakte/videoplayer-shared/es2018";var ny=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Dt(s):void 0)!=null?u:cD({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},oy=({id:a,bitrate:e})=>({id:a,bitrate:e}),uy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),ly=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Cl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Dl.default)(i.split("."),0),isDefault:r}),Vl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Dl.default)(r.split("."),0)}),Ol=a=>"url"in a,ye=a=>a.type==="template",wa=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},i=/^(-|\+)?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),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ft=(a,e)=>{let t=a;t=(0,Bl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,py.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Bl.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 _,A,q,L,U,te,H,I,$,Y,x,R,ce,bi,nt,G,be,Te,Ie,Xe,ot,yt,jt,gi,sr,Ec,xc,Pc,wc,Ac,kc,Rc,Lc,$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,id,rd,ad;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(qe=>{var X,Qt;return(Qt=(X=qe.textContent)==null?void 0:X.trim())!=null?Qt:""}),o=(_=(0,my.default)(n,0))!=null?_:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],h=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],E=y.reduce((qe,X)=>({...qe,[X.id]:X.children}),{}),T=y.reduce((qe,X)=>({...qe,[X.id]:X.getAttribute("duration")}),{});S?v=dy(S):(0,_l.default)(T).filter(qe=>qe).length&&!u?v=(0,_l.default)(T).reduce((qe,X)=>{var Qt;return qe+((Qt=dy(X))!=null?Qt:0)},0):b&&(v=parseInt(b,10));let k=0,B=(q=(A=s.getAttribute("profiles"))==null?void 0:A.split(","))!=null?q:[];for(let qe of y.map(X=>X.id))for(let X of E[qe]){let Qt=(L=X.getAttribute("id"))!=null?L:"id"+(k++).toString(10),nr=(U=X.getAttribute("mimeType"))!=null?U:"",Qn=(te=X.getAttribute("codecs"))!=null?te:"",Gn=(H=X.getAttribute("contentType"))!=null?H:nr==null?void 0:nr.split("/")[0],_T=($=(I=X.getAttribute("profiles"))==null?void 0:I.split(","))!=null?$:[],sd=(x=sy((Y=X.getAttribute("lang"))!=null?Y:""))!=null?x:{},za=(bi=(ce=(R=X.querySelector("Label"))==null?void 0:R.textContent)==null?void 0:ce.trim())!=null?bi:void 0,NT=X.querySelectorAll("Representation"),FT=X.querySelector("SegmentTemplate"),qT=(G=(nt=X.querySelector("Role"))==null?void 0:nt.getAttribute("value"))!=null?G:void 0,vi=Gn,ie={id:Qt,language:sd.language,isDefault:qT==="main",label:za,codecs:Qn,hdr:vi==="video"&&$l(Qn),mime:nr,representations:[]};for(let K of NT){let Tt=(be=K.getAttribute("lang"))!=null?be:void 0,or=(Ie=(Te=za!=null?za:X.getAttribute("label"))!=null?Te:K.getAttribute("label"))!=null?Ie:void 0,Ka=(yt=(ot=(Xe=K.querySelector("BaseURL"))==null?void 0:Xe.textContent)==null?void 0:ot.trim())!=null?yt:"",Gt=new URL(Ka||o,e).toString(),It=(jt=K.getAttribute("mimeType"))!=null?jt:nr,Xa=(sr=(gi=K.getAttribute("codecs"))!=null?gi:Qn)!=null?sr:"",Ja;if(Gn==="text"){let Et=K.getAttribute("id")||"",Za=((Ec=sd.privateuse)==null?void 0:Ec.includes("x-auto"))||Et.includes("_auto"),Wt=K.querySelector("SegmentTemplate");if(Wt){let ur={representationId:(xc=K.getAttribute("id"))!=null?xc:void 0,bandwidth:(Pc=K.getAttribute("bandwidth"))!=null?Pc:void 0},es=parseInt((wc=K.getAttribute("bandwidth"))!=null?wc:"",10)/1e3,ts=(kc=parseInt((Ac=Wt.getAttribute("startNumber"))!=null?Ac:"",10))!=null?kc:1,Si=parseInt((Rc=Wt.getAttribute("timescale"))!=null?Rc:"",10),Wn=(Lc=Wt.querySelectorAll("SegmentTimeline S"))!=null?Lc:[],yi=Wt.getAttribute("media");if(!yi)continue;let is=[],rs=0,as="",Ti=0,lr=ts,ge=0;for(let Ue of Wn){let Yt=parseInt(($c=Ue.getAttribute("d"))!=null?$c:"",10),Oe=parseInt((Mc=Ue.getAttribute("r"))!=null?Mc:"",10)||0,xt=parseInt((Dc=Ue.getAttribute("t"))!=null?Dc:"",10);ge=Number.isFinite(xt)?xt:ge;let zt=Yt/Si*1e3,Pt=ge/Si*1e3;for(let Je=0;Je<Oe+1;Je++){let wt=ft(yi,{...ur,segmentNumber:lr.toString(10),segmentTime:(ge+Je*Yt).toString(10)}),Ii=(Pt!=null?Pt:0)+Je*zt,dr=Ii+zt;lr++,is.push({time:{from:Ii,to:dr},url:wt})}ge+=(Oe+1)*Yt,rs+=(Oe+1)*zt}Ti=ge/Si*1e3,as=ft(yi,{...ur,segmentNumber:lr.toString(10),segmentTime:ge.toString(10)});let cr={time:{from:Ti,to:1/0},url:as},ut={type:"template",baseUrl:Gt,segmentTemplateUrl:yi,initUrl:"",totalSegmentsDurationMs:rs,segments:is,nextSegmentBeyondManifest:cr,timescale:Si};Ja={id:Et,kind:"text",segmentReference:ut,profiles:[],duration:v,bitrate:es,mime:"",codecs:"",width:0,height:0,isAuto:Za}}else Ja={id:Et,isAuto:Za,kind:"text",url:Gt}}else{let Et=(Vc=(Cc=K.getAttribute("contentType"))!=null?Cc:It==null?void 0:It.split("/")[0])!=null?Vc:Gn,Za=(Bc=(Oc=X.getAttribute("profiles"))==null?void 0:Oc.split(","))!=null?Bc:[],Wt=parseInt((_c=K.getAttribute("width"))!=null?_c:"",10),ur=parseInt((Nc=K.getAttribute("height"))!=null?Nc:"",10),es=parseInt((Fc=K.getAttribute("bandwidth"))!=null?Fc:"",10)/1e3,ts=(qc=K.getAttribute("frameRate"))!=null?qc:"",Si=(Uc=K.getAttribute("quality"))!=null?Uc:void 0,Wn=ts?ay(ts):void 0,yi=(Hc=K.getAttribute("id"))!=null?Hc:"id"+(k++).toString(10),is=Et==="video"?`${ur}p`:Et==="audio"?`${es}Kbps`:Xa,rs=`${yi}@${is}`,as=[...B,..._T,...Za],Ti,lr=K.querySelector("SegmentBase"),ge=(jc=K.querySelector("SegmentTemplate"))!=null?jc:FT;if(lr){let ut=(Gc=(Qc=K.querySelector("SegmentBase Initialization"))==null?void 0:Qc.getAttribute("range"))!=null?Gc:"",[Ue,Yt]=ut.split("-").map(wt=>parseInt(wt,10)),Oe={from:Ue,to:Yt},xt=(Wc=K.querySelector("SegmentBase"))==null?void 0:Wc.getAttribute("indexRange"),[zt,Pt]=xt?xt.split("-").map(wt=>parseInt(wt,10)):[],Je=xt?{from:zt,to:Pt}:void 0;Ti={type:"byteRange",url:Gt,initRange:Oe,indexRange:Je}}else if(ge){let ut={representationId:(Yc=K.getAttribute("id"))!=null?Yc:void 0,bandwidth:(zc=K.getAttribute("bandwidth"))!=null?zc:void 0},Ue=parseInt((Kc=ge.getAttribute("timescale"))!=null?Kc:"",10),Yt=(Xc=ge.getAttribute("initialization"))!=null?Xc:"",Oe=ge.getAttribute("media"),xt=(Zc=parseInt((Jc=ge.getAttribute("startNumber"))!=null?Jc:"",10))!=null?Zc:1,zt=ft(Yt,ut);if(!Oe)throw new ReferenceError("No media attribute in SegmentTemplate");let Pt=(ed=ge.querySelectorAll("SegmentTimeline S"))!=null?ed:[],Je=[],wt=0,Ii="",dr=0;if(Pt.length){let ss=xt,He=0;for(let Ei of Pt){let Ze=parseInt((td=Ei.getAttribute("d"))!=null?td:"",10),Kt=parseInt((id=Ei.getAttribute("r"))!=null?id:"",10)||0,ns=parseInt((rd=Ei.getAttribute("t"))!=null?rd:"",10);He=Number.isFinite(ns)?ns:He;let Yn=Ze/Ue*1e3,zn=He/Ue*1e3;for(let os=0;os<Kt+1;os++){let HT=ft(Oe,{...ut,segmentNumber:ss.toString(10),segmentTime:(He+os*Ze).toString(10)}),nd=(zn!=null?zn:0)+os*Yn,jT=nd+Yn;ss++,Je.push({time:{from:nd,to:jT},url:HT})}He+=(Kt+1)*Ze,wt+=(Kt+1)*Yn}dr=He/Ue*1e3,Ii=ft(Oe,{...ut,segmentNumber:ss.toString(10),segmentTime:He.toString(10)})}else if(dD(v)){let He=parseInt((ad=ge.getAttribute("duration"))!=null?ad:"",10)/Ue*1e3,Ei=Math.ceil(v/He),Ze=0;for(let Kt=1;Kt<Ei;Kt++){let ns=ft(Oe,{...ut,segmentNumber:Kt.toString(10),segmentTime:Ze.toString(10)});Je.push({time:{from:Ze,to:Ze+He},url:ns}),Ze+=He}dr=Ze,Ii=ft(Oe,{...ut,segmentNumber:Ei.toString(10),segmentTime:Ze.toString(10)})}let UT={time:{from:dr,to:1/0},url:Ii};Ti={type:"template",baseUrl:Gt,segmentTemplateUrl:Oe,initUrl:zt,totalSegmentsDurationMs:wt,segments:Je,nextSegmentBeyondManifest:UT,timescale:Ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Et||!It)continue;let cr={video:"video",audio:"audio",text:"text"}[Et];if(!cr)continue;vi||(vi=cr),Ja={id:rs,kind:cr,segmentReference:Ti,profiles:as,duration:v,bitrate:es,mime:It,codecs:Xa,width:Wt,height:ur,fps:Wn,quality:Si}}ie.language||(ie.language=Tt),ie.label||(ie.label=or),ie.mime||(ie.mime=It),ie.codecs||(ie.codecs=Xa),ie.hdr||(ie.hdr=vi==="video"&&$l(Xa)),ie.representations.push(Ja)}if(vi){let K=r[vi].find(Tt=>Tt.id===ie.id);if(K&&ie.representations.every(Tt=>ye(Tt.segmentReference)))for(let Tt of K.representations){let or=ie.representations.find(It=>It.id===Tt.id),Ka=or==null?void 0:or.segmentReference,Gt=Tt.segmentReference;Gt.segments.push(...Ka.segments),Gt.nextSegmentBeyondManifest=Ka.nextSegmentBeyondManifest}else r[vi].push(ie)}}return{duration:v,streams:r,baseUrls:n,live:g}};var gy=D(Be(),1);import{isNonNullable as by}from"@vkontakte/videoplayer-shared/es2018";var ae=(a,e)=>by(a)&&by(e)&&a.readyState==="open"&&(0,gy.default)([...a.activeSourceBuffers],e);var Aa=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new di(0);this.currentLowLatencySegmentLength$=new di(0);this.currentSegmentLength$=new di(0);this.onLastSegment$=new di(!1);this.fullyBuffered$=new di(!1);this.playingRepresentation$=new di(void 0);this.playingRepresentationInit$=new di(void 0);this.error$=new hD;this.gaps=[];this.subscription=new mD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new me;this.switchAbortController=new me;this.destroyAbortController=new me;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=Nt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(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(Fl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Fl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:bt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ae(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,El(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(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 i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Re(i,"No init buffer for starting representation"),Re(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Nt(this.destroyAbortController.signal,async function*(e,t=!1){if(!ae(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ae(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();Xi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Nt(this.destroyAbortController.signal,async function*(e,t=!1){if(!ae(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ae(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();Xi(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Nt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,hn.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 h=this.representations.get(c);if(!h||!ye(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Re(r);let s=this.segments.get(i);Re(s,"No segments for starting representation");let n=this.initData.get(i);if(Re(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,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ae(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new me,Nt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Re(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(fe(o)||fe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Re(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Xi(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!fe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(fe(e)||fe(this.downloadingRepresentationId)||fe(this.playingRepresentationId)||fe(this.sourceBuffer)||!ae(this.mediaSource,this.sourceBuffer)||Xi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Xi(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&El(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,pn.default)(u,r))c="high";else{let d=(0,Ji.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ji.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Xi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,hn.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,hn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];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(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,Ji.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!ye(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],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=ft(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 i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.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&&Zr&&Zr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Zr&&Zr(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,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let b=h<=i&&p>=i,g=h>i||b||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+v||p<=i+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&ae(this.mediaSource,this.sourceBuffer)&&!(Bt(this.sourceBuffer.buffered,h)&&Bt(this.sourceBuffer.buffered,p)))&&g&&S});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+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=r;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){ye(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Nt(o,async function*(){let c=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=dn(),!c)return;let d=new DataView(c),h=Pa(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),wa(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}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Nt(n,async function*(){let u=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Fl(window,"online").pipe(pD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=dn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),wa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ye(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ji.default)(e,0).byte.from,to:(0,Ji.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=dn(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:bt.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 i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=dn();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:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,pn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!ae(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Pa(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ae(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,h=d-c+1,p=c<r,m=d<=r;if(!p)continue;let b=Pa(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===h?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(fe(this.sourceBuffer)||!ae(this.mediaSource,this.sourceBuffer))){!this.isLive&&N.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Bt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Bt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:bt.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",Ol(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])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[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tl(()=>(0,vy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Nt(this.destroyAbortController.signal,async function*(){let o=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Pa(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&ye(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:bt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||fe(e))return!1;let r=[],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:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Ol(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 h of this.segments.values())for(let p of h)(0,pn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){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 r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ae(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||!ae(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(e=this.getCurrentPosition()){return!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||fe(e)?0:Wi(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.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<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ae(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tl(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:bt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(fe(this.sourceBuffer)||!ae(this.mediaSource,this.sourceBuffer)||fe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.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?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:bt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ka=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"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as Ra,assertNever as Ty,fromEvent as Iy,merge as fD,now as La,Subscription as bD,Subject as Ey,ValueSubject as Ul,flattenObject as Zi,ErrorCategory as $a}from"@vkontakte/videoplayer-shared/es2018";var yy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var fn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Ul(void 0);this.lastConnectionReused$=new Ul(void 0);this.lastRequestFirstBytes$=new Ul(void 0);this.recoverableError$=new Ey;this.error$=new Ey;this.abortAllController=new me;this.subscription=new bD;this.fetchManifest=Ra(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ka(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=yy(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(mn);return r?(t.log("success",Zi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Zi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ra(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,U,te;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let H=new URL(l,location.href);H.searchParams.append("bytes",`${i.from}-${i.to}`),l=H.toString();break}default:Ty(t)}this.requestQuic&&(l=ka(l));let h=this.abortAllController.signal,p;if(n){let H=new me;if(p=fD(Iy(this.abortAllController.signal,"abort"),Iy(n,"abort")).subscribe(()=>{try{H.abort()}catch(I){mn(I)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{H.abort()}catch(I){mn(I)}h=H.signal}let m=La();d.log("startRequest",Zi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:h}),g=La();if(!b)return d.error("error",{message:"No response in request"}),d.end(),p==null||p.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(g-m),!b.ok||!b.body){p==null||p.unsubscribe();let H=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:H}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){p==null||p.unsubscribe();let H=La(),I={requestStartedAt:m,requestEndedAt:H,duration:H-m};return d.log("endRequest",Zi(I)),d.end(),b.arrayBuffer()}let v=b.body;if(o){let H;[v,H]=b.body.tee(),(U=this.throughputEstimator)==null||U.trackStream(H,u)}let S=v.getReader(),y,E=parseInt((te=b.headers.get("content-length"))!=null?te:"",10);Number.isFinite(E)&&(y=E),!y&&i&&(y=i.to-i.from+1);let T=0,k=y?new Uint8Array(y):new Uint8Array(0),B=!1,O=H=>{p==null||p.unsubscribe(),B=!0,mn(H)},_=Ra(h,async function*({done:H,value:I}){if(T===0&&this.lastRequestFirstBytes$.next(La()-m),h.aborted){p==null||p.unsubscribe();return}if(!H&&I){if(y)k.set(I,T),T+=I.byteLength;else{let $=new Uint8Array(k.length+I.length);$.set(k),$.set(I,k.length),k=$,T+=I.byteLength}r==null||r(new DataView(k.buffer),T),yield S==null?void 0:S.read().then(_,O)}}.bind(this));yield S==null?void 0:S.read().then(_,O),p==null||p.unsubscribe();let A=La(),q={failed:B,requestStartedAt:m,requestEndedAt:A,duration:A-m};return B?(d.error("endRequest",Zi(q)),d.end(),null):(d.log("endRequest",Zi(q)),d.end(),k.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ra(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,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,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(v=e.indexRange)!=null?v:t.getIndexRange(p);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:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,p,m);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ra(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Sy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:Ty(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await at(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:$a.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:$a.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:$a.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:$a.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:$a.FATAL})}}},mn=a=>{if(!wa(a))throw a};var pi=(a,e,t)=>t*e+(1-t)*a,Hl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,xy=(a,e,t,i)=>{let r=0,s=t,n=Hl(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as gD,ValueSubject as Py}from"@vkontakte/videoplayer-shared/es2018";var Ft=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;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=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;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)&&(gD(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 bn=class extends Ft{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=pi(this.slow,e,this.params.emaAlphaSlow),this.fast=pi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var gn=class extends Ft{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Hl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pi(this.emaSmoothed,e,this.params.emaAlpha);let i=xy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var vn=class extends Ft{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?pi(this.smoothed,t,this.params.emaAlpha):t}};var hi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new bn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new gn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new vn({initial:e,label:"liveEdgeDelay",...t})}};var jl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as vD,ValueSubject as SD}from"@vkontakte/videoplayer-shared/es2018";var Ma=class a{constructor(e,t){this.currentRepresentation$=new SD(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(!vD(e))for(let i of this.representations)for(let r of i){let s=r.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,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 i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,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 yn=D(Ct(),1);import{assertNever as Tn}from"@vkontakte/videoplayer-shared/es2018";var wy=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=N.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(r.mp4||r.webm);default:return Tn(c)}})},Sn=a=>{let{webmDecodingInfo:e}=N.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Tn(a)}return[t,i]},Ay=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Sn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(N.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Sn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Sn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Sn(a),...r,"HLS","HLS_ONDEMAND"];default:Tn(e)}return N.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},ky=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],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:Tn(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"]},Ql=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ry=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,yn.default)(t.value.split("."),0)}for(let t of a){let i=(0,yn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,yn.default)(e.value.split("."),0)};var kD=["timeupdate","progress","play","seeked","stalled","waiting"],RD=["timeupdate","progress","loadeddata","playing","seeked"];var xn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new My;this.representationSubscription=new My;this.state$=new C("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new En;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new En;this.fetcherError$=new En;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new En;this.gapWatchdogActive=!1;this.destroyController=new me;this.initManifest=Wl(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=he(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:st.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Wl(this.destroyController.signal,async 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:st.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:st.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=Ye())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>i(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Ry(d);if(h&&(r[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=r.video.some(g=>g.hdr),b=r.video.some(g=>!g.hdr);N.display.isHDR&&p&&m?r.video=r.video.filter(g=>g.hdr):b&&(r.video=r.video.filter(g=>!g.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",Ca(s)),s}.bind(this));this.initRepresentations=Wl(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",Ca({initialVideo:e,initialAudio:t,sourceHls:i})),er(this.manifest),er(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(gt(p,"error").pipe(In(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:st.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?kg():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ks())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.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,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new Aa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Va(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new Aa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ma.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ma(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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(mi(...RD.map(p=>gt(this.element,p))).pipe(ir(p=>this.element?Wi(this.element.buffered,this.element.currentTime*1e3):0),Da(),wD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(mi(gt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Da()).subscribe(m=>this.liveStreamEndTimestamp=zl())),this.subscription.add(gt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Yl(1e3).subscribe(m=>{let b=js(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(gt(this.element,"play").subscribe(m=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add(tr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ir(({isActiveLive:m,isLowLatency:b})=>m&&b),Da()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||jl(this.element,1)})),this.representationSubscription.add(tr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(In(({bufferLength:m,isActiveLive:b,isLowLatency:g})=>b&&g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(m=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!m)return;let b=this.liveSeekableDuration$.getValue()-m/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+m/1e3)})),this.representationSubscription.add(tr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(In(({isLive:m})=>m),Da((m,b)=>b.bufferLength<m.bufferLength),ir(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=js(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(tr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:m,isActiveLive:b,isLowLatency:g})=>{if(!g||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=m-v;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(E)>S&&(T=1+Math.sign(E)*y),jl(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let b=0;if(m){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var T,k;return(k=(T=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?k:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(tr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(AD(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:b})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=js(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,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,k=isFinite(m)?m:b,B=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let _="none";if(B?_="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(A=>A.proceedLowLatencyLive()),_="active_low_latency"):v!==0&&k<y?_="live_forward_buffering":k<y+T&&(_="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),_==="live_forward_buffering"||_==="live_with_target_offset"){let A=p-(y+E),q=this.normolizeLiveOffset(Math.trunc(v+A/g)),L=Math.abs(q-v),U=0;!m||L<=this.tuning.dashCmafLive.offsetCalculationError?U=v:q>0&&L>this.tuning.dashCmafLive.offsetCalculationError&&(U=q),this.manifestUrlString=he(this.manifestUrlString,U,2)}(_==="live_with_target_offset"||_==="live_forward_buffering")&&(p=0,await this.updateLive())},m=>{this.error$.next({id:"updateLive",category:st.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=mi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ir(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=mi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ir(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=tr({allBuffersFull:l,someBufferEnded:c}).pipe(Da(),ir(({allBuffersFull:p,someBufferEnded:m})=>p&&m),In(p=>p));if(this.representationSubscription.add(mi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:st.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add(mi(...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"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((m,b)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){m();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):m()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),m()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,Kl.default)((0,Kl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let b=[];return m.duration&&b.push(m.duration),ye(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&b.push(m.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Va(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,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Yl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:st.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new fn({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=hi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;er(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?zl()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=he(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){er(this.element),this.state$.setState("running"),this.subscription.add(mi(...kD.map(e=>gt(this.element,e)),gt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:st.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(gt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(gt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Bt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,b,g,v,S,y,E,T,k,B;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=zl(),n=100,o=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(y=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?y:0,c=(T=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?T:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let O=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(O).catch(_=>{this.error$.next({id:"stallIntervalCallback",category:st.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:_})}),r.liveLastOffset=O}else{let O=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(O),(B=this.audioBufferManager)==null||B.maintain(O),r.position=O}this.tracer.log("stallIntervalCallback",Ca(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Yl(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:st.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;er(this.element),er(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Bt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!($y(this.element)||$y(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ca({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Va(this.element)&&Va(this.source)&&Va(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=PD(this.tracer.error.bind(this.tracer));this.subscription.add(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}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.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(),i={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 r=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<=r&&u.to+n>r&&(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,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ca(i)))}}};var Pn=class{constructor(e,t){this.fov=e,this.orientation=t}};var wn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i: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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(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 Dy=`#ifdef GL_ES
81
+ `;var Cy=`#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 An=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Pn(this.params.fov,this.params.orientation),this.cameraRotationManager=new wn(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"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),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(i,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(r,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(My,this.gl.VERTEX_SHADER),i=this.createShader(Dy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,h=t+r;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as $D,now as Cy,Subscription as MD,filter as DD,combine as Vy,debounce as CD,ValueSubject as Xl,isNonNullable as VD}from"@vkontakte/videoplayer-shared/es2018";var Jl=class{constructor(){this.isSeeked$=new Xl(!1);this.isBuffering$=new Xl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new MD;this.severeStallOccurred$=new Xl(!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(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(Vy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(CD(this.qualityLimitsOnStall.stallDurationToBeCount),DD(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Vy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if($D(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Cy(),d=r&&this.currentStallsCount>=r,h=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,VD(this.lastUniqueVideoTrackSelected.bitrate)&&u>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=Cy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Oy=Jl;import{combine as OD,map as BD,observeElementSize as _D,Subscription as ND,ValueSubject as Zl,noop as FD}from"@vkontakte/videoplayer-shared/es2018";var kn=class{constructor(){this.subscription=new ND;this.pipSize$=new Zl(void 0);this.videoSize$=new Zl(void 0);this.elementSize$=new Zl(void 0);this.pictureInPictureWindowRemoveEventListener=FD}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(_D(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(OD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(BD(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).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 fi=class{constructor(e){this.subscription=new GD;this.videoState=new C("stopped");this.droppedFramesManager=new on;this.stallsManager=new Oy;this.elementSizeManager=new kn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ur;this.audioTrackSwitchHistory=new Ur;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),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()):(i==null?void 0:i.to)==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return UD(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new An(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.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 Ne(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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 xn({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,i=Ae(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:By.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(_y(l=>!!l.length),Fy()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ec(l=>l.to.state!=="none"),Oa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Oa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$,looped$:i.looped$}),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.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.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(_y(Ny),Fy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ec(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(it(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Fe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),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(HD(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of c.audio){h.push(Cl(p));let m=[];for(let b of p.representations){let g=ny(b);m.push(g),this.audioTracksMap.set(g,{stream:p,representation:b})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(Vl(h));let p=[];for(let m of h.representations){let b=sy({...m,streamId:h.id});b&&(p.push(b),this.videoTracksMap.set(b,{stream:h,representation:m}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let p of h.representations){let m=oy(h,p);this.textTracksMap.set(m,{stream:h,representation:p})}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())},r)),this.subscription.add(Rn(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$,QD(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,qy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[h,p]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===h.id});Ny(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,g)}},r)),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(Oa()).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:h}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Vl(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Oa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Cl(h))},r)),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(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(ec(({to:l})=>l==="ready"),Oa());this.subscription.add(Rn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,tc(["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(Rn(o,this.player.state$.stateChangeEnded$,tc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Rn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,tc(["init"])).pipe(jD(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var B,O,_,A,q,L,U,te,H,I,$,Y,x;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(B=e.videoTrack.getState())==null?void 0:B.id,n=[...this.videoTracksMap.keys()].find(({id:R})=>R===r),o=t.currentVideoTrack$.getValue(),u=((A=(_=e.videoStream.getState())!=null?_:n&&((O=this.videoTracksMap.get(n))==null?void 0:O.stream))!=null?A:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Wi(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let p=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(h,p||1/0),1),b=(q=e.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(L=[...this.audioStreamsMap.keys()].find(({id:R})=>R===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!i){let R=rn(n,c,(U=this.audioStreamsMap.get(g))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(te=R==null?void 0:R.bitrate)!=null?te:-1/0)}if(o){let R=rn(o,c,(H=this.audioStreamsMap.get(g))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(I=R==null?void 0:R.bitrate)!=null?I:-1/0)}}let S=Ot(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,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=i?S!=null?S:n:n!=null?n:S,E=g&&tv(y,c,($=this.audioStreamsMap.get(g))!=null?$:[],{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}),T=(Y=this.videoTracksMap.get(y))==null?void 0:Y.representation,k=E&&((x=this.audioTracksMap.get(E))==null?void 0:x.representation);if(T&&k)return[T,k];if(T&&!k&&this.audioTracksMap.size===0)return[T,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=>{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:By.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),xe(this.video),this.tracer.end()}};var Ba=class extends fi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ic,merge as Uy,filter as Hy,filterChanged as WD,isNullable as rc,map as jy,ValueSubject as ac,isNonNullable as YD}from"@vkontakte/videoplayer-shared/es2018";var _a=class extends fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new ac(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(jy(o=>o.to)).subscribe(this.player.isLowLatency$)).add(ic({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jy(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Hy(o=>YD(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(ic({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Uy(i.playbackRateState$,new ac(1))}).pipe(Hy(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||rc(l)||(e=o-l)})).add(ic({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Uy(i.playbackRateState$,new ac(1))}).pipe(WD((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||rc(o)||rc(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=uy(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Gy=D(Hs(),1);import{assertNever as Na,assertNonNullable as Qy,debounce as zD,ErrorCategory as Ln,filter as KD,isNonNullable as XD,isNullable as JD,map as $n,merge as ZD,Observable as eC,observableFrom as tC,Subscription as iC,videoSizeToQuality as rC}from"@vkontakte/videoplayer-shared/es2018";var Ke={};var rr=(a,e)=>new eC(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Fa=class{constructor(e){this.subscription=new iC;this.videoState=new C("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Na(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Na(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Na(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:Na(e)}break;default:Na(t)}};this.textTracksManager=new Ne(e.source.url),this.video=Ee(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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),xe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ln.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Gy.default)(import("hls.js").then(r=>{e||(Ke.Hls=r.default,Ke.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){Qy(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Qy(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Ln.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(it(this.video,e.isLooped,i)),this.subscription.add(Pe(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(_e(this.video,e.playbackRate,r.playbackRateState$,i)),s(Fe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe($n(l=>l.to)),this.params.output.playbackState$),this.subscription.add(rr(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Ln.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(rr(this.hls,Ke.Events.MANIFEST_PARSED).pipe($n(({levels:l})=>l.reduce((c,d)=>{var S,y;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(y=Dt((S=d.attrs.QUALITY)!=null?S:""))!=null?y:rC({width:p,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(rr(this.hls,Ke.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(rr(this.hls,Ke.Events.LEVEL_LOADING).pipe($n(({url:l})=>oe(l))),t.hostname$),s(rr(this.hls,Ke.Events.FRAG_CHANGED),l=>{var h,p,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p: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(Lt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=rr(this.hls,Ke.Events.LEVEL_SWITCHED).pipe($n(({level:l})=>n(this.hls.levels[l])));o.pipe(KD(XD)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Lt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(JD(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),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=ZD(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,tC(["init"])).pipe(zD(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ln.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 Wy="X-Playback-Duration",sc=async a=>{var r;let e=await at(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Wy)?parseInt(e.headers.get(Wy),10):void 0};import{assertNever as mC,combine as fC,debounce as bC,ErrorCategory as Cn,filter as gC,filterChanged as vC,isNonNullable as Ky,isNullable as Vn,map as Xy,merge as SC,observableFrom as yC,Subscription as TC,ValueSubject as uc,VideoQuality as IC}from"@vkontakte/videoplayer-shared/es2018";var oc=D(au(),1);import{videoSizeToQuality as aC,getExponentialDelay as sC}from"@vkontakte/videoplayer-shared/es2018";var nC=a=>{let e=null;if(a.QUALITY&&(e=Dt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=aC({width:t,height:i})}return e!=null?e:null},oC=(a,e)=>{var s,n;let t=a.split(`
125
- `),i=[],r=[];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,oc.default)(l[1].split(",").map(S=>S.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=nC(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();p&&i.push({id:h,quality:p,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,oc.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,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&r.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},uC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),nc=0,Yy=async(a,e=a,t,i)=>{let s=await(await at(a,i)).text();nc+=1;try{let{qualityManifests:n,textTracks:o}=oC(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(nc<=t.manifestRetryMaxCount)return await uC(sC(nc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Yy(a,e,t)}return{qualityManifests:[],textTracks:[]}},Mn=Yy;import{isNonNullable as lC,Subscription as cC,throttle as dC,ValueSubject as zy,Subject as pC,ErrorCategory as hC}from"@vkontakte/videoplayer-shared/es2018";var Dn=class{constructor(e,t,i,r,s){this.subscription=new cC;this.abortControllers={destroy:new me,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new zy(null);this.getCurrentTime$=new zy(null);this.error$=new pC;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(dC(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()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await at(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
126
- `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.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);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(lC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:hC.WTF,thrown:t,message:e})}};var qa=class{constructor(e){this.subscription=new TC;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new uc([]);this.liveOffset=new ui;this.manifestStartTime$=new uc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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((r==null?void 0:r.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":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.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":if(i==="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(r==null?void 0:r.to)==="paused"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return mC(t)}};var i;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:IC.INVARIANT,url:this.params.source.url};let t=(r,s)=>Mn(r,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 Dn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ne(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Cn.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,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Cn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new uc((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Cn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),s(Fe(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(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(vC(),Xy(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.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&&Ky(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(oe(h.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)},i)),this.subscription.add(r.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)},i)),this.subscription.add(fC({startTime:this.manifestStartTime$.pipe(gC(Ky)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Xy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=SC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,yC(["init"])).pipe(bC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Vn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=he(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),sc(n).then(c=>{var d;if(!Vn(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Vn(h)||!isFinite(h))&&at(n).then(p=>p.text()).then(p=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();sc(g).then(v=>{Vn(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:Cn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/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 EC,debounce as xC,ErrorCategory as lc,fromEvent as cc,isNonNullable as PC,isNullable as wC,map as Jy,merge as Zy,observableFrom as eT,Subscription as AC,ValueSubject as kC,VideoQuality as RC}from"@vkontakte/videoplayer-shared/es2018";var Ua=class{constructor(e){this.subscription=new AC;this.videoState=new C("stopped");this.manifests$=new kC([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="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":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return EC(t)}};this.textTracksManager=new Ne(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:RC.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),Mn(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:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:lc.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,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:lc.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Jy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(it(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;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&&PC(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(oe(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){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)},i))),this.subscription.add(this.manifests$.pipe(Jy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!N.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Zy(cc(o,"addtrack"),cc(o,"removetrack"),cc(o,"change"),eT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=Zy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,eT(["init"])).pipe(xC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(wC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.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:lc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var rT=D(Di(),1),dc=D(ji(),1),aT=D(Ct(),1);import{assertNever as LC,assertNonNullable as tT,debounce as $C,ErrorCategory as iT,isHigherOrEqual as MC,isLowerOrEqual as DC,isNonNullable as CC,merge as VC,observableFrom as OC,Subscription as BC,map as _C}from"@vkontakte/videoplayer-shared/es2018";var Ha=class{constructor(e){this.subscription=new BC;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Ne;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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((i==null?void 0:i.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()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return LC(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,rT.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,dc.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,i=o=>{e.error$.next({id:"MpegProvider",category:iT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(_C(o=>o.to)),this.params.output.playbackState$),this.subscription.add(it(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),s(Fe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.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&&CC(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 h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=VC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,OC(["init"])).pipe($C(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),xe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;tT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];tT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ka(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: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)},i=d=>{let h=Ot(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,dc.default)(this.trackUrls).map(d=>d.track);if(!r||!s||qr({limits:e,lowestAvailableQuality:(c=(0,aT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?DC(r,e.max):!0,u=e.min?MC(r,e.min):!0;o&&u||i(e)}};import{assertNever as nT,debounce as UC,merge as oT,observableFrom as HC,Subscription as jC,map as uT,ValueSubject as QC,ErrorCategory as hc,VideoQuality as GC}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as NC}from"@vkontakte/videoplayer-shared/es2018";var sT=["stun:videostun.mycdn.me:80"],FC=1e3,qC=3,pc=()=>null,On=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=pc;this.externalStopCallback=pc;this.externalErrorCallback=pc;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:sT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:NC.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))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),FC)}normalizeOptions(e={}){let t={stunServerList:sT,maxRetryNumber:qC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ja=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new QC(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return nT(e)}};this.subscription=new jC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new On(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:hc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(oT(this.videoState.stateChangeStarted$.pipe(uT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(uT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),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(Fe(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Pe(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).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 nT(n.to)}},i)).add(oT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,HC(["init"])).pipe(UC(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}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:GC.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:hc.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:hc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qa=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 Wa,assertNonNullable as qt,ErrorCategory as Bn,filter as mT,isNonNullable as fT,isNullable as ZC,map as e0,merge as t0,once as i0,Subject as le,Subscription as bT,ValueSubject as V,flattenObject as gT}from"@vkontakte/videoplayer-shared/es2018";import{Observable as WC,map as lT,Subscription as YC,Subject as zC}from"@vkontakte/videoplayer-shared/es2018";var cT=a=>new WC(e=>{let t=new YC,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(lT(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(lT(({type:l})=>l!==void 0)),n=new zC,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.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 KC,Subscription as XC,combine as JC,filter as pT,once as hT}from"@vkontakte/videoplayer-shared/es2018";function dT(){return new(window.AudioContext||window.webkitAudioContext)}var Ga=class Ga{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new me;this.subscriptions=new XC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(pT(s=>!!s.type),hT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){N.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(JC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(pT(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),hT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=dT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!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:Ga.errorId,category:KC.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ga.errorId} exception`,thrown:e})}};Ga.errorId="VolumeMultiplierManager";var ar=Ga;var r0={chunkDuration:5e3,maxParallelRequests:5},Ya=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new le;this.noAvailableProvidersError$=new le;this.volumeMultiplierError$=new le;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new le,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 V(void 0),isLiveEnded$:new V(null),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),severeStallOccurred$:new le,availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new bT;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=Py([...Ay(this.params.tuning),...wy(this.params.tuning)],this.params.tuning).filter(l=>fT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,mc.default)(r,l)),...t.filter(l=>(0,mc.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",gT(s)),this.screenFormatsIterator=new Qa(s);let n=[...Ql(!0),...Ql(!1)];this.chromecastFormatsIterator=new Qa(n.filter(l=>fT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ar.isSupported()&&(this.volumeMultiplierManager=new ar(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(ZC(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Bn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,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,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.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 Wa(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qt(u),new Ba({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qt(u),new _a({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return qt(u),N.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Ua({...o,source:u}):new Fa({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qt(u),new qa({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return qt(u),new Ha({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return qt(u),new vv({...o,source:u,config:{...r0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return qt(u),new ja({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Wa(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return qt(o),new Vr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,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 Wa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Wa(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 Wa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,ST.default)((0,vT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new bT,t=!1,i=0;return e.add(t0(this.providerOutput.error$.pipe(mT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),cT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(e0(r=>({id:`ProviderHangup:${r}`,category:Bn.WTF,message:`A ${r} 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 r=this.params.desiredState.playbackState.transitionEnded$.pipe(mT(({to:s})=>s==="playing"),i0()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Bn.NETWORK,u=r.category===Bn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}this.tracer.error("providerError",gT(n))})),e}};import{fromEvent as _n,once as a0,combine as s0,Subscription as yT,ValueSubject as fc,map as n0,filter as o0,isNonNullable as Nn,now as Ve,safeStorage as bc}from"@vkontakte/videoplayer-shared/es2018";var u0=5e3,TT="one_video_throughput",IT="one_video_rtt",vt=window.navigator.connection,ET=()=>{let a=vt==null?void 0:vt.downlink;if(Nn(a)&&a!==10)return a*1e3},xT=()=>{let a=vt==null?void 0:vt.rtt;if(Nn(a)&&a!==3e3)return a},PT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},gc=class a{constructor(e){this.subscription=new yT;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(TT)||(e.useBrowserEstimation?ET():void 0)||u0,i=(s=(r=a.load(IT))!=null?r:e.useBrowserEstimation?xT():void 0)!=null?s:0;if(this.throughput$=new fc(t),this.rtt$=new fc(i),this.rttAdjustedThroughput$=new fc(PT(t,i,e.rttPenaltyRequestSize)),this.throughput=hi.getSmoothedValue(t,-1,e),this.rtt=hi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=ET();u&&this.throughput.next(u);let l=xT();Nn(l)&&this.rtt.next(l)};vt&&"onchange"in vt&&this.subscription.add(_n(vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{bc.set(TT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{bc.set(IT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(s0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(n0(({throughput:n,rtt:o})=>PT(n,o,e.rttPenaltyRequestSize)),o0(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,i=Ve(),r=new yT;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(_n(e,"progress").pipe(a0()).subscribe(s=>{t=s.loaded,i=Ve()}));break;case 1:case 0:r.add(_n(e,"loadstart").subscribe(()=>{t=0,i=Ve()}));break}r.add(_n(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ve(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Ve(),n=0,o=Ve(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,Ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Ve();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=Ve()}else n+=d.byteLength;o=Ve()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ve()-o,this.concurrentDownloads.size),n=0,o=Ve());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=bc.get(e);if(Nn(t))return(i=parseInt(t,10))!=null?i:void 0}},wT=gc;import{fillWithDefault as l0,VideoQuality as Fn}from"@vkontakte/videoplayer-shared/es2018";var AT={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:Fn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Fn.Q_720P,trafficSavingLimit:Fn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Fn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,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,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,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,seekNearDurationBias:1,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,autostartOnlyIfVisible:!1},kT=a=>{var e;return{...l0(a,AT),configName:[...(e=a.configName)!=null?e:[],...AT.configName]}};import{assertNonNullable as qn,combine as St,ErrorCategory as Un,filter as M,filterChanged as W,fromEvent as Sc,isNonNullable as b0,isNullable as g0,Logger as v0,map as Q,mapTo as MT,merge as Ut,now as Hn,once as F,Subject as z,Subscription as DT,tap as yc,ValueSubject as P,isHigher as S0,isInvariantQuality as CT,flattenObject as Ht,throttle as Tc,getTraceSubscriptionMethod as VT,Tracer as y0,InternalsExposure as T0}from"@vkontakte/videoplayer-shared/es2018";import{merge as c0,map as d0,filter as RT,isNonNullable as p0}from"@vkontakte/videoplayer-shared/es2018";var vc=({seekState:a,position$:e})=>c0(a.stateChangeEnded$.pipe(d0(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),RT(p0)),e.pipe(RT(()=>a.getState().state==="none")));import{assertNonNullable as h0}from"@vkontakte/videoplayer-shared/es2018";var LT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return h0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as m0,once as f0}from"@vkontakte/videoplayer-shared/es2018";var $T=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(m0(r=>r.length>0),f0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var jn=class{constructor(e={configName:[]},t=y0.createRootTracer(!1)){this.subscription=new DT;this.logger=new v0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new P(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new P(void 0),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),predefinedQualityLimitType$:new P("unknown"),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),isLiveEnded$:new P(null),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,fetcherRecoverableError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z,fetcherError$:new z,severeStallOccured$:new z};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Ug,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=kT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new fs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new wT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new T0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,m)=>{let b=typeof m;return(0,OT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Un.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",Ht(o)),this.domContainer=LT(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ya({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,panelSize:e.panelSize}),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)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?N.isInited$.pipe(M(n=>!!n),F()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Sc(document,"visibilitychange").pipe(F()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),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.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,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.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),s=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{qn(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(M(i=>i.length>0),F()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Ht(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var i;qn(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.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.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Ht(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var t;$T(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(M(e=>e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(M(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(g0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return b0(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(il({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(M(({from:e})=>e==="stopped"),F()).subscribe(()=>{this.initedAt=Hn(),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",Ht(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Un.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",Ht(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Q(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Q(n=>n.destination),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(St({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Q(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>CT(u)?1:CT(l)?-1:S0(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(Q(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.isLiveEnded$.pipe(yc(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).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(St({hasLiveOffsetByPaused:Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(n=>n.to),W(),Q(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(St({atLiveEdge:St({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:vc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Q(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),W(),yc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Q(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(St({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Q(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),W(),yc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Q(n=>n.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Q(n=>n.volume),W()).subscribe(this.info.volume$)).add(vc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ut(e.providerOutput.endedEvent$.pipe(MT(!0)),e.providerOutput.seekedEvent$.pipe(MT(!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(Q(n=>({id:n?`No${n}`:"NoProviders",category:Un.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(),Q(n=>n!=null?n:Hn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(F(),Q(()=>Hn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(F(),Q(()=>Hn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new P(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(M(({to:n})=>n==="playing"),F()).subscribe(()=>i.next(!1)));let r=0,s=Ut(e.providerOutput.isBuffering$,t,i).pipe(Q(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),W());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ut(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(Ut(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(Q(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(W((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(M(i=>i.length>0),F()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Ot(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,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(Ut(this.desiredState.videoTrack.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Q(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;qn(this.providerContainer),qn(e),qg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Fg(i)),this.providerContainer.current$.subscribe(({type:i})=>Fr("provider",i)),e.duration$.subscribe(i=>Fr("duration",i)),e.availableVideoTracks$.pipe(M(i=>!!i.length),F()).subscribe(i=>Fr("tracks",i)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(Q(i=>i==null?void 0:i.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(i=>this.subscription.add(i)),Fr("codecs",N.video.supportedCodecs)}initTracerSubscription(){let e=VT(this.tracer.log.bind(this.tracer)),t=VT(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(St({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(M(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),W((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(M(i=>i>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(M(i=>i>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(St({currentBuffer:this.info.currentBuffer$.pipe(M(i=>i.end>0),W((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(W())}).pipe(Tc(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(St({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(M(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Tc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),M(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),M(i=>i===!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(),M(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(St({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(M(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Tc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),M(i=>i===!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},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Un.DOM,message:String(r)})})};this.subscription.add(Ut(Sc(document,"visibilitychange"),Sc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Ht({quality:t,availableTracks:Ht(e),track:Ht(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Wr()}};import{Subscription as m6,Observable as f6,Subject as b6,ValueSubject as g6,VideoQuality as v6}from"@vkontakte/videoplayer-shared/es2018";var S6=`@vkontakte/videoplayer-core@${od}`;export{us as ChromecastState,Kn as HttpConnectionType,f6 as Observable,Le as PlaybackState,jn as Player,ls as PredefinedQualityLimits,S6 as SDK_VERSION,b6 as Subject,m6 as Subscription,Xn as Surface,od as VERSION,g6 as ValueSubject,lt as VideoFormat,v6 as VideoQuality,N as clientChecker,_r as isMobile};
124
+ `;var An=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Pn(this.params.fov,this.params.orientation),this.cameraRotationManager=new wn(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"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),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(i,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(r,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}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),i=this.createShader(Cy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,h=t+r;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as MD,now as Vy,Subscription as DD,filter as CD,combine as Oy,debounce as VD,ValueSubject as Xl,isNonNullable as OD}from"@vkontakte/videoplayer-shared/es2018";var Jl=class{constructor(){this.isSeeked$=new Xl(!1);this.isBuffering$=new Xl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new DD;this.severeStallOccurred$=new Xl(!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(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(Oy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(VD(this.qualityLimitsOnStall.stallDurationToBeCount),CD(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Oy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(MD(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Vy(),d=r&&this.currentStallsCount>=r,h=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,OD(this.lastUniqueVideoTrackSelected.bitrate)&&u>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=Vy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},By=Jl;import{combine as BD,map as _D,observeElementSize as ND,Subscription as FD,ValueSubject as Zl,noop as qD}from"@vkontakte/videoplayer-shared/es2018";var kn=class{constructor(){this.subscription=new FD;this.pipSize$=new Zl(void 0);this.videoSize$=new Zl(void 0);this.elementSize$=new Zl(void 0);this.pictureInPictureWindowRemoveEventListener=qD}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(ND(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(BD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(_D(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).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 fi=class{constructor(e){this.subscription=new WD;this.videoState=new C("stopped");this.droppedFramesManager=new on;this.stallsManager=new By;this.elementSizeManager=new kn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ur;this.audioTrackSwitchHistory=new Ur;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),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()):(i==null?void 0:i.to)==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return HD(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new An(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.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 Ne(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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 xn({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,i=Ae(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:_y.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ec(l=>!!l.length),Fy()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(tc(l=>l.to.state!=="none"),Oa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Oa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$,looped$:i.looped$}),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.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.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(ec(Ny),Fy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(tc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(it(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Fe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),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(jD(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of c.audio){h.push(Cl(p));let m=[];for(let b of p.representations){let g=oy(b);m.push(g),this.audioTracksMap.set(g,{stream:p,representation:b})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(Vl(h));let p=[];for(let m of h.representations){let b=ny({...m,streamId:h.id});b&&(p.push(b),this.videoTracksMap.set(b,{stream:h,representation:m}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let p of h.representations){let m=uy(h,p);this.textTracksMap.set(m,{stream:h,representation:p})}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())},r)),this.subscription.add(Rn(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,GD(this.video,"progress")).pipe(ec(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,qy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[h,p]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===h.id});Ny(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,g)}},r)),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(Oa()).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:h}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Vl(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Oa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Cl(h))},r)),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(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(tc(({to:l})=>l==="ready"),Oa());this.subscription.add(Rn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ic(["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(Rn(o,this.player.state$.stateChangeEnded$,ic(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Rn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ic(["init"])).pipe(QD(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var B,O,_,A,q,L,U,te,H,I,$,Y,x;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(B=e.videoTrack.getState())==null?void 0:B.id,n=[...this.videoTracksMap.keys()].find(({id:R})=>R===r),o=t.currentVideoTrack$.getValue(),u=((A=(_=e.videoStream.getState())!=null?_:n&&((O=this.videoTracksMap.get(n))==null?void 0:O.stream))!=null?A:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Wi(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let p=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(h,p||1/0),1),b=(q=e.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(L=[...this.audioStreamsMap.keys()].find(({id:R})=>R===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!i){let R=rn(n,c,(U=this.audioStreamsMap.get(g))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(te=R==null?void 0:R.bitrate)!=null?te:-1/0)}if(o){let R=rn(o,c,(H=this.audioStreamsMap.get(g))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(I=R==null?void 0:R.bitrate)!=null?I:-1/0)}}let S=Ot(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,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=i?S!=null?S:n:n!=null?n:S,E=g&&iv(y,c,($=this.audioStreamsMap.get(g))!=null?$:[],{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}),T=(Y=this.videoTracksMap.get(y))==null?void 0:Y.representation,k=E&&((x=this.audioTracksMap.get(E))==null?void 0:x.representation);if(T&&k)return[T,k];if(T&&!k&&this.audioTracksMap.size===0)return[T,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=>{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:_y.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),xe(this.video),this.tracer.end()}};var Ba=class extends fi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as rc,merge as Uy,filter as Hy,filterChanged as YD,isNullable as ac,map as jy,ValueSubject as sc,isNonNullable as zD}from"@vkontakte/videoplayer-shared/es2018";var _a=class extends fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new sc(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(jy(o=>o.to)).subscribe(this.player.isLowLatency$)).add(rc({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jy(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Hy(o=>zD(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(rc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Uy(i.playbackRateState$,new sc(1))}).pipe(Hy(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||ac(l)||(e=o-l)})).add(rc({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Uy(i.playbackRateState$,new sc(1))}).pipe(YD((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||ac(o)||ac(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=ly(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Gy=D(Hs(),1);import{assertNever as Na,assertNonNullable as Qy,debounce as KD,ErrorCategory as Ln,filter as XD,isNonNullable as JD,isNullable as ZD,map as $n,merge as eC,Observable as tC,observableFrom as iC,Subscription as rC,videoSizeToQuality as aC}from"@vkontakte/videoplayer-shared/es2018";var Ke={};var rr=(a,e)=>new tC(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Fa=class{constructor(e){this.subscription=new rC;this.videoState=new C("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Na(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Na(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Na(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:Na(e)}break;default:Na(t)}};this.textTracksManager=new Ne(e.source.url),this.video=Ee(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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),xe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ln.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Gy.default)(import("hls.js").then(r=>{e||(Ke.Hls=r.default,Ke.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){Qy(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Qy(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Ln.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(it(this.video,e.isLooped,i)),this.subscription.add(Pe(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(_e(this.video,e.playbackRate,r.playbackRateState$,i)),s(Fe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe($n(l=>l.to)),this.params.output.playbackState$),this.subscription.add(rr(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Ln.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(rr(this.hls,Ke.Events.MANIFEST_PARSED).pipe($n(({levels:l})=>l.reduce((c,d)=>{var S,y;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(y=Dt((S=d.attrs.QUALITY)!=null?S:""))!=null?y:aC({width:p,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(rr(this.hls,Ke.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(rr(this.hls,Ke.Events.LEVEL_LOADING).pipe($n(({url:l})=>oe(l))),t.hostname$),s(rr(this.hls,Ke.Events.FRAG_CHANGED),l=>{var h,p,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p: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(Lt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=rr(this.hls,Ke.Events.LEVEL_SWITCHED).pipe($n(({level:l})=>n(this.hls.levels[l])));o.pipe(XD(JD)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Lt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(ZD(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),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=eC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,iC(["init"])).pipe(KD(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ln.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 Wy="X-Playback-Duration",nc=async a=>{var r;let e=await at(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Wy)?parseInt(e.headers.get(Wy),10):void 0};import{assertNever as fC,combine as bC,debounce as gC,ErrorCategory as Cn,filter as vC,filterChanged as SC,isNonNullable as Ky,isNullable as Vn,map as Xy,merge as yC,observableFrom as TC,Subscription as IC,ValueSubject as lc,VideoQuality as EC}from"@vkontakte/videoplayer-shared/es2018";var uc=D(au(),1);import{videoSizeToQuality as sC,getExponentialDelay as nC}from"@vkontakte/videoplayer-shared/es2018";var oC=a=>{let e=null;if(a.QUALITY&&(e=Dt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=sC({width:t,height:i})}return e!=null?e:null},uC=(a,e)=>{var s,n;let t=a.split(`
125
+ `),i=[],r=[];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("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=oC(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();p&&i.push({id:h,quality:p,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,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&r.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},lC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),oc=0,Yy=async(a,e=a,t,i)=>{let s=await(await at(a,i)).text();oc+=1;try{let{qualityManifests:n,textTracks:o}=uC(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(oc<=t.manifestRetryMaxCount)return await lC(nC(oc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Yy(a,e,t)}return{qualityManifests:[],textTracks:[]}},Mn=Yy;import{isNonNullable as cC,Subscription as dC,throttle as pC,ValueSubject as zy,Subject as hC,ErrorCategory as mC}from"@vkontakte/videoplayer-shared/es2018";var Dn=class{constructor(e,t,i,r,s){this.subscription=new dC;this.abortControllers={destroy:new me,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new zy(null);this.getCurrentTime$=new zy(null);this.error$=new hC;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(pC(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()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await at(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
126
+ `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.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);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(cC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:mC.WTF,thrown:t,message:e})}};var qa=class{constructor(e){this.subscription=new IC;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new lc([]);this.liveOffset=new ui;this.manifestStartTime$=new lc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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((r==null?void 0:r.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":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.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":if(i==="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(r==null?void 0:r.to)==="paused"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return fC(t)}};var i;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:EC.INVARIANT,url:this.params.source.url};let t=(r,s)=>Mn(r,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 Dn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ne(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Cn.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,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Cn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new lc((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Cn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),s(Fe(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(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(SC(),Xy(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.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&&Ky(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(oe(h.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)},i)),this.subscription.add(r.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)},i)),this.subscription.add(bC({startTime:this.manifestStartTime$.pipe(vC(Ky)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Xy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=yC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,TC(["init"])).pipe(gC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Vn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=he(r.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(!Vn(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Vn(h)||!isFinite(h))&&at(n).then(p=>p.text()).then(p=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();nc(g).then(v=>{Vn(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:Cn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/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 xC,debounce as PC,ErrorCategory as cc,fromEvent as dc,isNonNullable as wC,isNullable as AC,map as Jy,merge as Zy,observableFrom as eT,Subscription as kC,ValueSubject as RC,VideoQuality as LC}from"@vkontakte/videoplayer-shared/es2018";var Ua=class{constructor(e){this.subscription=new kC;this.videoState=new C("stopped");this.manifests$=new RC([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="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((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="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":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return xC(t)}};this.textTracksManager=new Ne(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:LC.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),Mn(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:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},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,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:cc.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Jy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(it(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;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&&wC(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(oe(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){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)},i))),this.subscription.add(this.manifests$.pipe(Jy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!N.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Zy(dc(o,"addtrack"),dc(o,"removetrack"),dc(o,"change"),eT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=Zy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,eT(["init"])).pipe(PC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(AC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.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:cc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var rT=D(Di(),1),pc=D(ji(),1),aT=D(Ct(),1);import{assertNever as $C,assertNonNullable as tT,debounce as MC,ErrorCategory as iT,isHigherOrEqual as DC,isLowerOrEqual as CC,isNonNullable as VC,merge as OC,observableFrom as BC,Subscription as _C,map as NC}from"@vkontakte/videoplayer-shared/es2018";var Ha=class{constructor(e){this.subscription=new _C;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Ne;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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((i==null?void 0:i.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()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return $C(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,rT.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),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,i=o=>{e.error$.next({id:"MpegProvider",category:iT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(NC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(it(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),s(Fe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.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&&VC(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 h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=OC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,BC(["init"])).pipe(MC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),xe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;tT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];tT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ka(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: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)},i=d=>{let h=Ot(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(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(!r||!s||qr({limits:e,lowestAvailableQuality:(c=(0,aT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?CC(r,e.max):!0,u=e.min?DC(r,e.min):!0;o&&u||i(e)}};import{assertNever as nT,debounce as HC,merge as oT,observableFrom as jC,Subscription as QC,map as uT,ValueSubject as GC,ErrorCategory as mc,VideoQuality as WC}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as FC}from"@vkontakte/videoplayer-shared/es2018";var sT=["stun:videostun.mycdn.me:80"],qC=1e3,UC=3,hc=()=>null,On=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 i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:sT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:FC.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))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),qC)}normalizeOptions(e={}){let t={stunServerList:sT,maxRetryNumber:UC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ja=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new GC(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=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()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return nT(e)}};this.subscription=new QC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new On(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:mc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(oT(this.videoState.stateChangeStarted$.pipe(uT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(uT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),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(Fe(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Pe(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).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 nT(n.to)}},i)).add(oT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,jC(["init"])).pipe(HC(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}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:WC.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(){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:mc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qa=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 Wa,assertNonNullable as qt,ErrorCategory as Bn,filter as mT,isNonNullable as fT,isNullable as e0,map as t0,merge as i0,once as r0,Subject as le,Subscription as bT,ValueSubject as V,flattenObject as gT}from"@vkontakte/videoplayer-shared/es2018";import{Observable as YC,map as lT,Subscription as zC,Subject as KC}from"@vkontakte/videoplayer-shared/es2018";var cT=a=>new YC(e=>{let t=new zC,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(lT(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(lT(({type:l})=>l!==void 0)),n=new KC,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.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 XC,Subscription as JC,combine as ZC,filter as pT,once as hT}from"@vkontakte/videoplayer-shared/es2018";function dT(){return new(window.AudioContext||window.webkitAudioContext)}var Ga=class Ga{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new me;this.subscriptions=new JC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(pT(s=>!!s.type),hT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){N.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(ZC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(pT(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),hT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=dT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!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:Ga.errorId,category:XC.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ga.errorId} exception`,thrown:e})}};Ga.errorId="VolumeMultiplierManager";var ar=Ga;var a0={chunkDuration:5e3,maxParallelRequests:5},Ya=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new le;this.noAvailableProvidersError$=new le;this.volumeMultiplierError$=new le;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new le,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 V(void 0),isLiveEnded$:new V(null),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),severeStallOccurred$:new le,availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new bT;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=>fT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,fc.default)(r,l)),...t.filter(l=>(0,fc.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",gT(s)),this.screenFormatsIterator=new Qa(s);let n=[...Ql(!0),...Ql(!1)];this.chromecastFormatsIterator=new Qa(n.filter(l=>fT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ar.isSupported()&&(this.volumeMultiplierManager=new ar(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 i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Bn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,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,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.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 Wa(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qt(u),new Ba({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qt(u),new _a({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return qt(u),N.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Ua({...o,source:u}):new Fa({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qt(u),new qa({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return qt(u),new Ha({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return qt(u),new Sv({...o,source:u,config:{...a0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return qt(u),new ja({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Wa(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return qt(o),new Vr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,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 Wa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Wa(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 Wa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,ST.default)((0,vT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new bT,t=!1,i=0;return e.add(i0(this.providerOutput.error$.pipe(mT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),cT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(t0(r=>({id:`ProviderHangup:${r}`,category:Bn.WTF,message:`A ${r} 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 r=this.params.desiredState.playbackState.transitionEnded$.pipe(mT(({to:s})=>s==="playing"),r0()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Bn.NETWORK,u=r.category===Bn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}this.tracer.error("providerError",gT(n))})),e}};import{fromEvent as _n,once as s0,combine as n0,Subscription as yT,ValueSubject as bc,map as o0,filter as u0,isNonNullable as Nn,now as Ve,safeStorage as gc}from"@vkontakte/videoplayer-shared/es2018";var l0=5e3,TT="one_video_throughput",IT="one_video_rtt",vt=window.navigator.connection,ET=()=>{let a=vt==null?void 0:vt.downlink;if(Nn(a)&&a!==10)return a*1e3},xT=()=>{let a=vt==null?void 0:vt.rtt;if(Nn(a)&&a!==3e3)return a},PT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},vc=class a{constructor(e){this.subscription=new yT;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(TT)||(e.useBrowserEstimation?ET():void 0)||l0,i=(s=(r=a.load(IT))!=null?r:e.useBrowserEstimation?xT():void 0)!=null?s:0;if(this.throughput$=new bc(t),this.rtt$=new bc(i),this.rttAdjustedThroughput$=new bc(PT(t,i,e.rttPenaltyRequestSize)),this.throughput=hi.getSmoothedValue(t,-1,e),this.rtt=hi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=ET();u&&this.throughput.next(u);let l=xT();Nn(l)&&this.rtt.next(l)};vt&&"onchange"in vt&&this.subscription.add(_n(vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{gc.set(TT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{gc.set(IT,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})=>PT(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,i=Ve(),r=new yT;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(_n(e,"progress").pipe(s0()).subscribe(s=>{t=s.loaded,i=Ve()}));break;case 1:case 0:r.add(_n(e,"loadstart").subscribe(()=>{t=0,i=Ve()}));break}r.add(_n(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ve(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Ve(),n=0,o=Ve(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,Ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Ve();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=Ve()}else n+=d.byteLength;o=Ve()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ve()-o,this.concurrentDownloads.size),n=0,o=Ve());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=gc.get(e);if(Nn(t))return(i=parseInt(t,10))!=null?i:void 0}},wT=vc;import{fillWithDefault as c0,VideoQuality as Fn}from"@vkontakte/videoplayer-shared/es2018";var AT={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:Fn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Fn.Q_720P,trafficSavingLimit:Fn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Fn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,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,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,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,seekNearDurationBias:1,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,autostartOnlyIfVisible:!1},kT=a=>{var e;return{...c0(a,AT),configName:[...(e=a.configName)!=null?e:[],...AT.configName]}};import{assertNonNullable as qn,combine as St,ErrorCategory as Un,filter as M,filterChanged as W,fromEvent as yc,isNonNullable as MT,isNullable as g0,Logger as v0,map as Q,mapTo as DT,merge as Ut,now as Hn,once as F,Subject as z,Subscription as CT,tap as Tc,ValueSubject as P,isHigher as S0,isInvariantQuality as VT,flattenObject as Ht,throttle as Ic,getTraceSubscriptionMethod as OT,Tracer as y0,InternalsExposure as T0}from"@vkontakte/videoplayer-shared/es2018";import{merge as d0,map as p0,filter as RT,isNonNullable as h0}from"@vkontakte/videoplayer-shared/es2018";var Sc=({seekState:a,position$:e})=>d0(a.stateChangeEnded$.pipe(p0(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),RT(h0)),e.pipe(RT(()=>a.getState().state==="none")));import{assertNonNullable as m0}from"@vkontakte/videoplayer-shared/es2018";var LT=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/es2018";var $T=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(f0(r=>r.length>0),b0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var jn=class{constructor(e={configName:[]},t=y0.createRootTracer(!1)){this.subscription=new CT;this.logger=new v0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new P(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new P(void 0),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),predefinedQualityLimitType$:new P("unknown"),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),isLiveEnded$:new P(null),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,fetcherRecoverableError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z,fetcherError$:new z,severeStallOccured$:new z};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Hg,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=kT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new fs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new wT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new T0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,m)=>{let b=typeof m;return(0,BT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Un.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",Ht(o)),this.domContainer=LT(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ya({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,panelSize:e.panelSize}),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)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?N.isInited$.pipe(M(n=>!!n),F()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};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.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),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.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,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.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),s=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{qn(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(M(i=>i.length>0),F()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Ht(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var i;qn(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.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.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Ht(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var t;$T(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(M(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.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(M(e=>e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(M(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(g0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return MT(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Q(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(il({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(M(({from:e})=>e==="stopped"),F()).subscribe(()=>{this.initedAt=Hn(),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",Ht(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Un.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",Ht(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Q(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Q(n=>n.destination),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(St({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Q(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>VT(u)?1:VT(l)?-1:S0(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$.pipe(M(n=>MT(n))).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(Q(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.isLiveEnded$.pipe(Tc(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).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(St({hasLiveOffsetByPaused:Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Q(n=>n.to),W(),Q(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(St({atLiveEdge:St({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Q(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),W(),Tc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Q(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(St({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Q(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),W(),Tc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Q(n=>n.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Q(n=>n.volume),W()).subscribe(this.info.volume$)).add(Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ut(e.providerOutput.endedEvent$.pipe(DT(!0)),e.providerOutput.seekedEvent$.pipe(DT(!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(Q(n=>({id:n?`No${n}`:"NoProviders",category:Un.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(),Q(n=>n!=null?n:Hn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(F(),Q(()=>Hn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(F(),Q(()=>Hn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new P(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(M(({to:n})=>n==="playing"),F()).subscribe(()=>i.next(!1)));let r=0,s=Ut(e.providerOutput.isBuffering$,t,i).pipe(Q(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),W());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ut(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(Ut(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(Q(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 CT;this.subscription.add(t),this.subscription.add(e.current$.pipe(W((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(M(i=>i.length>0),F()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Ot(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,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(Ut(this.desiredState.videoTrack.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Q(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Q(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;qn(this.providerContainer),qn(e),Ug(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>qg(i)),this.providerContainer.current$.subscribe(({type:i})=>Fr("provider",i)),e.duration$.subscribe(i=>Fr("duration",i)),e.availableVideoTracks$.pipe(M(i=>!!i.length),F()).subscribe(i=>Fr("tracks",i)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(Q(i=>i==null?void 0:i.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(i=>this.subscription.add(i)),Fr("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(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(St({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(M(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),W((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(M(i=>i>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(M(i=>i>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(St({currentBuffer:this.info.currentBuffer$.pipe(M(i=>i.end>0),W((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(W())}).pipe(Ic(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(W()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(W()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(W()).subscribe(e("canChangePlaybackSpeed"))).add(St({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(M(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Ic(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),M(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),M(i=>i===!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(),M(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(St({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(M(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Ic(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),M(i=>i===!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},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Un.DOM,message:String(r)})})};this.subscription.add(Ut(yc(document,"visibilitychange"),yc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Ht({quality:t,availableTracks:Ht(e),track:Ht(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Wr()}};import{Subscription as mK,Observable as fK,Subject as bK,ValueSubject as gK,VideoQuality as vK}from"@vkontakte/videoplayer-shared/es2018";var SK=`@vkontakte/videoplayer-core@${ud}`;export{us as ChromecastState,Kn as HttpConnectionType,fK as Observable,Le as PlaybackState,jn as Player,ls as PredefinedQualityLimits,SK as SDK_VERSION,bK as Subject,mK as Subscription,Xn as Surface,ud as VERSION,gK as ValueSubject,lt as VideoFormat,vK as VideoQuality,N as clientChecker,_r as isMobile};