@vkontakte/videoplayer-core 2.0.124-dev.99952f80.0 → 2.0.124-dev.b0f19b8d.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,19 +1,19 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.124-dev.99952f80.0
3
- * Wed, 29 Jan 2025 14:26:50 GMT
2
+ * @vkontakte/videoplayer-core v2.0.124-dev.b0f19b8d.0
3
+ * Wed, 05 Feb 2025 12:19:15 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-124/doc/
5
5
  */
6
- var zT=Object.create;var io=Object.defineProperty,KT=Object.defineProperties,XT=Object.getOwnPropertyDescriptor,JT=Object.getOwnPropertyDescriptors,ZT=Object.getOwnPropertyNames,gs=Object.getOwnPropertySymbols,eI=Object.getPrototypeOf,ao=Object.prototype.hasOwnProperty,ad=Object.prototype.propertyIsEnumerable;var tI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,id=(a,e,t)=>e in a?io(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,I=(a,e)=>{for(var t in e||(e={}))ao.call(e,t)&&id(a,t,e[t]);if(gs)for(var t of gs(e))ad.call(e,t)&&id(a,t,e[t]);return a},$=(a,e)=>KT(a,JT(e));var sd=(a,e)=>{var t={};for(var r in a)ao.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&gs)for(var r of gs(a))e.indexOf(r)<0&&ad.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var rI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ZT(e))!ao.call(a,i)&&i!==t&&io(a,i,{get:()=>e[i],enumerable:!(r=XT(e,i))||r.enumerable});return a};var O=(a,e,t)=>(t=a!=null?zT(eI(a)):{},rI(e||!a||!a.__esModule?io(t,"default",{value:a,enumerable:!0}):t,a));var w=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),vs=function(a,e){this[0]=a,this[1]=e},ae=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof vs,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[tI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var re=m((oo,od)=>{"use strict";var Ti=function(a){return a&&a.Math===Math&&a};od.exports=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof global=="object"&&global)||Ti(typeof oo=="object"&&oo)||function(){return this}()||Function("return this")()});var pe=m((LC,ud)=>{"use strict";ud.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ii=m((MC,ld)=>{"use strict";var iI=pe();ld.exports=!iI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var uo=m((DC,hd)=>{"use strict";var aI=Ii(),pd=Function.prototype,cd=pd.apply,dd=pd.call;hd.exports=typeof Reflect=="object"&&Reflect.apply||(aI?dd.bind(cd):function(){return dd.apply(cd,arguments)})});var ne=m((CC,bd)=>{"use strict";var fd=Ii(),md=Function.prototype,lo=md.call,sI=fd&&md.bind.bind(lo,lo);bd.exports=fd?sI:function(a){return function(){return lo.apply(a,arguments)}}});var ir=m((BC,vd)=>{"use strict";var gd=ne(),nI=gd({}.toString),oI=gd("".slice);vd.exports=function(a){return oI(nI(a),8,-1)}});var co=m((VC,Sd)=>{"use strict";var uI=ir(),lI=ne();Sd.exports=function(a){if(uI(a)==="Function")return lI(a)}});var ee=m((OC,yd)=>{"use strict";var po=typeof document=="object"&&document.all;yd.exports=typeof po=="undefined"&&po!==void 0?function(a){return typeof a=="function"||a===po}:function(a){return typeof a=="function"}});var Me=m((_C,Td)=>{"use strict";var cI=pe();Td.exports=!cI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var De=m((NC,Id)=>{"use strict";var dI=Ii(),ys=Function.prototype.call;Id.exports=dI?ys.bind(ys):function(){return ys.apply(ys,arguments)}});var ho=m(Pd=>{"use strict";var Ed={}.propertyIsEnumerable,xd=Object.getOwnPropertyDescriptor,pI=xd&&!Ed.call({1:2},1);Pd.f=pI?function(e){var t=xd(this,e);return!!t&&t.enumerable}:Ed});var Ei=m((qC,wd)=>{"use strict";wd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var kd=m((UC,Ad)=>{"use strict";var hI=ne(),fI=pe(),mI=ir(),fo=Object,bI=hI("".split);Ad.exports=fI(function(){return!fo("z").propertyIsEnumerable(0)})?function(a){return mI(a)==="String"?bI(a,""):fo(a)}:fo});var Dr=m((HC,Rd)=>{"use strict";Rd.exports=function(a){return a==null}});var Mt=m((jC,$d)=>{"use strict";var gI=Dr(),vI=TypeError;$d.exports=function(a){if(gI(a))throw new vI("Can't call method on "+a);return a}});var ar=m((GC,Ld)=>{"use strict";var SI=kd(),yI=Mt();Ld.exports=function(a){return SI(yI(a))}});var Ce=m((QC,Md)=>{"use strict";var TI=ee();Md.exports=function(a){return typeof a=="object"?a!==null:TI(a)}});var Cr=m((WC,Dd)=>{"use strict";Dd.exports={}});var pt=m((YC,Bd)=>{"use strict";var mo=Cr(),bo=re(),II=ee(),Cd=function(a){return II(a)?a:void 0};Bd.exports=function(a,e){return arguments.length<2?Cd(mo[a])||Cd(bo[a]):mo[a]&&mo[a][e]||bo[a]&&bo[a][e]}});var xi=m((zC,Vd)=>{"use strict";var EI=ne();Vd.exports=EI({}.isPrototypeOf)});var sr=m((KC,Nd)=>{"use strict";var xI=re(),Od=xI.navigator,_d=Od&&Od.userAgent;Nd.exports=_d?String(_d):""});var vo=m((XC,Gd)=>{"use strict";var jd=re(),go=sr(),Fd=jd.process,qd=jd.Deno,Ud=Fd&&Fd.versions||qd&&qd.version,Hd=Ud&&Ud.v8,Ye,Ts;Hd&&(Ye=Hd.split("."),Ts=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!Ts&&go&&(Ye=go.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=go.match(/Chrome\/(\d+)/),Ye&&(Ts=+Ye[1])));Gd.exports=Ts});var So=m((JC,Wd)=>{"use strict";var Qd=vo(),PI=pe(),wI=re(),AI=wI.String;Wd.exports=!!Object.getOwnPropertySymbols&&!PI(function(){var a=Symbol("symbol detection");return!AI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Qd&&Qd<41})});var yo=m((ZC,Yd)=>{"use strict";var kI=So();Yd.exports=kI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var To=m((eB,zd)=>{"use strict";var RI=pt(),$I=ee(),LI=xi(),MI=yo(),DI=Object;zd.exports=MI?function(a){return typeof a=="symbol"}:function(a){var e=RI("Symbol");return $I(e)&&LI(e.prototype,DI(a))}});var Pi=m((tB,Kd)=>{"use strict";var CI=String;Kd.exports=function(a){try{return CI(a)}catch(e){return"Object"}}});var st=m((rB,Xd)=>{"use strict";var BI=ee(),VI=Pi(),OI=TypeError;Xd.exports=function(a){if(BI(a))return a;throw new OI(VI(a)+" is not a function")}});var wi=m((iB,Jd)=>{"use strict";var _I=st(),NI=Dr();Jd.exports=function(a,e){var t=a[e];return NI(t)?void 0:_I(t)}});var ep=m((aB,Zd)=>{"use strict";var Io=De(),Eo=ee(),xo=Ce(),FI=TypeError;Zd.exports=function(a,e){var t,r;if(e==="string"&&Eo(t=a.toString)&&!xo(r=Io(t,a))||Eo(t=a.valueOf)&&!xo(r=Io(t,a))||e!=="string"&&Eo(t=a.toString)&&!xo(r=Io(t,a)))return r;throw new FI("Can't convert object to primitive value")}});var ze=m((sB,tp)=>{"use strict";tp.exports=!0});var ap=m((nB,ip)=>{"use strict";var rp=re(),qI=Object.defineProperty;ip.exports=function(a,e){try{qI(rp,a,{value:e,configurable:!0,writable:!0})}catch(t){rp[a]=e}return e}});var Ai=m((oB,op)=>{"use strict";var UI=ze(),HI=re(),jI=ap(),sp="__core-js_shared__",np=op.exports=HI[sp]||jI(sp,{});(np.versions||(np.versions=[])).push({version:"3.38.0",mode:UI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Po=m((uB,lp)=>{"use strict";var up=Ai();lp.exports=function(a,e){return up[a]||(up[a]=e||{})}});var Br=m((lB,cp)=>{"use strict";var GI=Mt(),QI=Object;cp.exports=function(a){return QI(GI(a))}});var Ke=m((cB,dp)=>{"use strict";var WI=ne(),YI=Br(),zI=WI({}.hasOwnProperty);dp.exports=Object.hasOwn||function(e,t){return zI(YI(e),t)}});var wo=m((dB,pp)=>{"use strict";var KI=ne(),XI=0,JI=Math.random(),ZI=KI(1 .toString);pp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+ZI(++XI+JI,36)}});var he=m((pB,fp)=>{"use strict";var eE=re(),tE=Po(),hp=Ke(),rE=wo(),iE=So(),aE=yo(),Vr=eE.Symbol,Ao=tE("wks"),sE=aE?Vr.for||Vr:Vr&&Vr.withoutSetter||rE;fp.exports=function(a){return hp(Ao,a)||(Ao[a]=iE&&hp(Vr,a)?Vr[a]:sE("Symbol."+a)),Ao[a]}});var vp=m((hB,gp)=>{"use strict";var nE=De(),mp=Ce(),bp=To(),oE=wi(),uE=ep(),lE=he(),cE=TypeError,dE=lE("toPrimitive");gp.exports=function(a,e){if(!mp(a)||bp(a))return a;var t=oE(a,dE),r;if(t){if(e===void 0&&(e="default"),r=nE(t,a,e),!mp(r)||bp(r))return r;throw new cE("Can't convert object to primitive value")}return e===void 0&&(e="number"),uE(a,e)}});var ko=m((fB,Sp)=>{"use strict";var pE=vp(),hE=To();Sp.exports=function(a){var e=pE(a,"string");return hE(e)?e:e+""}});var Is=m((mB,Tp)=>{"use strict";var fE=re(),yp=Ce(),Ro=fE.document,mE=yp(Ro)&&yp(Ro.createElement);Tp.exports=function(a){return mE?Ro.createElement(a):{}}});var $o=m((bB,Ip)=>{"use strict";var bE=Me(),gE=pe(),vE=Is();Ip.exports=!bE&&!gE(function(){return Object.defineProperty(vE("div"),"a",{get:function(){return 7}}).a!==7})});var Pp=m(xp=>{"use strict";var SE=Me(),yE=De(),TE=ho(),IE=Ei(),EE=ar(),xE=ko(),PE=Ke(),wE=$o(),Ep=Object.getOwnPropertyDescriptor;xp.f=SE?Ep:function(e,t){if(e=EE(e),t=xE(t),wE)try{return Ep(e,t)}catch(r){}if(PE(e,t))return IE(!yE(TE.f,e,t),e[t])}});var Lo=m((vB,wp)=>{"use strict";var AE=pe(),kE=ee(),RE=/#|\.prototype\./,ki=function(a,e){var t=LE[$E(a)];return t===DE?!0:t===ME?!1:kE(e)?AE(e):!!e},$E=ki.normalize=function(a){return String(a).replace(RE,".").toLowerCase()},LE=ki.data={},ME=ki.NATIVE="N",DE=ki.POLYFILL="P";wp.exports=ki});var Or=m((SB,kp)=>{"use strict";var Ap=co(),CE=st(),BE=Ii(),VE=Ap(Ap.bind);kp.exports=function(a,e){return CE(a),e===void 0?a:BE?VE(a,e):function(){return a.apply(e,arguments)}}});var Mo=m((yB,Rp)=>{"use strict";var OE=Me(),_E=pe();Rp.exports=OE&&_E(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=m((TB,$p)=>{"use strict";var NE=Ce(),FE=String,qE=TypeError;$p.exports=function(a){if(NE(a))return a;throw new qE(FE(a)+" is not an object")}});var nr=m(Mp=>{"use strict";var UE=Me(),HE=$o(),jE=Mo(),Es=nt(),Lp=ko(),GE=TypeError,Do=Object.defineProperty,QE=Object.getOwnPropertyDescriptor,Co="enumerable",Bo="configurable",Vo="writable";Mp.f=UE?jE?function(e,t,r){if(Es(e),t=Lp(t),Es(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Vo in r&&!r[Vo]){var i=QE(e,t);i&&i[Vo]&&(e[t]=r.value,r={configurable:Bo in r?r[Bo]:i[Bo],enumerable:Co in r?r[Co]:i[Co],writable:!1})}return Do(e,t,r)}:Do:function(e,t,r){if(Es(e),t=Lp(t),Es(r),HE)try{return Do(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new GE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=m((EB,Dp)=>{"use strict";var WE=Me(),YE=nr(),zE=Ei();Dp.exports=WE?function(a,e,t){return YE.f(a,e,zE(1,t))}:function(a,e,t){return a[e]=t,a}});var se=m((xB,Bp)=>{"use strict";var Ri=re(),KE=uo(),XE=co(),JE=ee(),ZE=Pp().f,ex=Lo(),Nr=Cr(),tx=Or(),Fr=_r(),Cp=Ke();Ai();var rx=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return KE(a,this,arguments)};return e.prototype=a.prototype,e};Bp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Ri:i?Ri[t]:Ri[t]&&Ri[t].prototype,o=r?Nr:Nr[t]||Fr(Nr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,v;for(p in e)l=ex(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Cp(n,p),f=o[p],c&&(a.dontCallGetSet?(v=ZE(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=tx(h,Ri):a.wrap&&c?g=rx(h):s&&JE(h)?g=XE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Fr(g,"sham",!0),Fr(o,p,g),s&&(d=t+"Prototype",Cp(Nr,d)||Fr(Nr,d,{}),Fr(Nr[d],p,h),a.real&&u&&(l||!u[p])&&Fr(u,p,h)))}});var Op=m((PB,Vp)=>{"use strict";var ix=Math.ceil,ax=Math.floor;Vp.exports=Math.trunc||function(e){var t=+e;return(t>0?ax:ix)(t)}});var $i=m((wB,_p)=>{"use strict";var sx=Op();_p.exports=function(a){var e=+a;return e!==e||e===0?0:sx(e)}});var Fp=m((AB,Np)=>{"use strict";var nx=$i(),ox=Math.max,ux=Math.min;Np.exports=function(a,e){var t=nx(a);return t<0?ox(t+e,0):ux(t,e)}});var Oo=m((kB,qp)=>{"use strict";var lx=$i(),cx=Math.min;qp.exports=function(a){var e=lx(a);return e>0?cx(e,9007199254740991):0}});var qr=m((RB,Up)=>{"use strict";var dx=Oo();Up.exports=function(a){return dx(a.length)}});var _o=m(($B,jp)=>{"use strict";var px=ar(),hx=Fp(),fx=qr(),Hp=function(a){return function(e,t,r){var i=px(e),s=fx(i);if(s===0)return!a&&-1;var n=hx(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};jp.exports={includes:Hp(!0),indexOf:Hp(!1)}});var Li=m((LB,Gp)=>{"use strict";Gp.exports=function(){}});var Qp=m(()=>{"use strict";var mx=se(),bx=_o().includes,gx=pe(),vx=Li(),Sx=gx(function(){return!Array(1).includes()});mx({target:"Array",proto:!0,forced:Sx},{includes:function(e){return bx(this,e,arguments.length>1?arguments[1]:void 0)}});vx("includes")});var Dt=m((CB,Wp)=>{"use strict";var yx=pt();Wp.exports=yx});var zp=m((BB,Yp)=>{"use strict";Qp();var Tx=Dt();Yp.exports=Tx("Array","includes")});var Xp=m((VB,Kp)=>{"use strict";var Ix=zp();Kp.exports=Ix});var Xe=m((OB,Jp)=>{"use strict";var Ex=Xp();Jp.exports=Ex});var ws=m((zB,nh)=>{"use strict";var Lx=Po(),Mx=wo(),sh=Lx("keys");nh.exports=function(a){return sh[a]||(sh[a]=Mx(a))}});var uh=m((KB,oh)=>{"use strict";var Dx=pe();oh.exports=!Dx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var As=m((XB,ch)=>{"use strict";var Cx=Ke(),Bx=ee(),Vx=Br(),Ox=ws(),_x=uh(),lh=Ox("IE_PROTO"),qo=Object,Nx=qo.prototype;ch.exports=_x?qo.getPrototypeOf:function(a){var e=Vx(a);if(Cx(e,lh))return e[lh];var t=e.constructor;return Bx(t)&&e instanceof t?t.prototype:e instanceof qo?Nx:null}});var ks=m((JB,dh)=>{"use strict";dh.exports={}});var fh=m((ZB,hh)=>{"use strict";var Fx=ne(),Uo=Ke(),qx=ar(),Ux=_o().indexOf,Hx=ks(),ph=Fx([].push);hh.exports=function(a,e){var t=qx(a),r=0,i=[],s;for(s in t)!Uo(Hx,s)&&Uo(t,s)&&ph(i,s);for(;e.length>r;)Uo(t,s=e[r++])&&(~Ux(i,s)||ph(i,s));return i}});var Ho=m((eV,mh)=>{"use strict";mh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var jo=m((tV,bh)=>{"use strict";var jx=fh(),Gx=Ho();bh.exports=Object.keys||function(e){return jx(e,Gx)}});var Go=m((rV,Th)=>{"use strict";var vh=Me(),Qx=pe(),Sh=ne(),Wx=As(),Yx=jo(),zx=ar(),Kx=ho().f,yh=Sh(Kx),Xx=Sh([].push),Jx=vh&&Qx(function(){var a=Object.create(null);return a[2]=2,!yh(a,2)}),gh=function(a){return function(e){for(var t=zx(e),r=Yx(t),i=Jx&&Wx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!vh||(i?u in t:yh(t,u)))&&Xx(o,a?[u,t[u]]:t[u]);return o}};Th.exports={entries:gh(!0),values:gh(!1)}});var Ih=m(()=>{"use strict";var Zx=se(),eP=Go().entries;Zx({target:"Object",stat:!0},{entries:function(e){return eP(e)}})});var xh=m((sV,Eh)=>{"use strict";Ih();var tP=Cr();Eh.exports=tP.Object.entries});var wh=m((nV,Ph)=>{"use strict";var rP=xh();Ph.exports=rP});var Ur=m((oV,Ah)=>{"use strict";var iP=wh();Ah.exports=iP});var or=m((uV,kh)=>{"use strict";kh.exports={}});var Lh=m((lV,$h)=>{"use strict";var aP=re(),sP=ee(),Rh=aP.WeakMap;$h.exports=sP(Rh)&&/native code/.test(String(Rh))});var zo=m((cV,Ch)=>{"use strict";var nP=Lh(),Dh=re(),oP=Ce(),uP=_r(),Qo=Ke(),Wo=Ai(),lP=ws(),cP=ks(),Mh="Object already initialized",Yo=Dh.TypeError,dP=Dh.WeakMap,Rs,Mi,$s,pP=function(a){return $s(a)?Mi(a):Rs(a,{})},hP=function(a){return function(e){var t;if(!oP(e)||(t=Mi(e)).type!==a)throw new Yo("Incompatible receiver, "+a+" required");return t}};nP||Wo.state?(Je=Wo.state||(Wo.state=new dP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,Rs=function(a,e){if(Je.has(a))throw new Yo(Mh);return e.facade=a,Je.set(a,e),e},Mi=function(a){return Je.get(a)||{}},$s=function(a){return Je.has(a)}):(ur=lP("state"),cP[ur]=!0,Rs=function(a,e){if(Qo(a,ur))throw new Yo(Mh);return e.facade=a,uP(a,ur,e),e},Mi=function(a){return Qo(a,ur)?a[ur]:{}},$s=function(a){return Qo(a,ur)});var Je,ur;Ch.exports={set:Rs,get:Mi,has:$s,enforce:pP,getterFor:hP}});var Jo=m((dV,Vh)=>{"use strict";var Ko=Me(),fP=Ke(),Bh=Function.prototype,mP=Ko&&Object.getOwnPropertyDescriptor,Xo=fP(Bh,"name"),bP=Xo&&function(){}.name==="something",gP=Xo&&(!Ko||Ko&&mP(Bh,"name").configurable);Vh.exports={EXISTS:Xo,PROPER:bP,CONFIGURABLE:gP}});var _h=m(Oh=>{"use strict";var vP=Me(),SP=Mo(),yP=nr(),TP=nt(),IP=ar(),EP=jo();Oh.f=vP&&!SP?Object.defineProperties:function(e,t){TP(e);for(var r=IP(t),i=EP(t),s=i.length,n=0,o;s>n;)yP.f(e,o=i[n++],r[o]);return e}});var Zo=m((hV,Nh)=>{"use strict";var xP=pt();Nh.exports=xP("document","documentElement")});var iu=m((fV,Qh)=>{"use strict";var PP=nt(),wP=_h(),Fh=Ho(),AP=ks(),kP=Zo(),RP=Is(),$P=ws(),qh=">",Uh="<",tu="prototype",ru="script",jh=$P("IE_PROTO"),eu=function(){},Gh=function(a){return Uh+ru+qh+a+Uh+"/"+ru+qh},Hh=function(a){a.write(Gh("")),a.close();var e=a.parentWindow.Object;return a=null,e},LP=function(){var a=RP("iframe"),e="java"+ru+":",t;return a.style.display="none",kP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Gh("document.F=Object")),t.close(),t.F},Ls,Ms=function(){try{Ls=new ActiveXObject("htmlfile")}catch(e){}Ms=typeof document!="undefined"?document.domain&&Ls?Hh(Ls):LP():Hh(Ls);for(var a=Fh.length;a--;)delete Ms[tu][Fh[a]];return Ms()};AP[jh]=!0;Qh.exports=Object.create||function(e,t){var r;return e!==null?(eu[tu]=PP(e),r=new eu,eu[tu]=null,r[jh]=e):r=Ms(),t===void 0?r:wP.f(r,t)}});var Hr=m((mV,Wh)=>{"use strict";var MP=_r();Wh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:MP(a,e,t),a}});var ou=m((bV,Kh)=>{"use strict";var DP=pe(),CP=ee(),BP=Ce(),VP=iu(),Yh=As(),OP=Hr(),_P=he(),NP=ze(),nu=_P("iterator"),zh=!1,ht,au,su;[].keys&&(su=[].keys(),"next"in su?(au=Yh(Yh(su)),au!==Object.prototype&&(ht=au)):zh=!0);var FP=!BP(ht)||DP(function(){var a={};return ht[nu].call(a)!==a});FP?ht={}:NP&&(ht=VP(ht));CP(ht[nu])||OP(ht,nu,function(){return this});Kh.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:zh}});var Ds=m((gV,Jh)=>{"use strict";var qP=he(),UP=qP("toStringTag"),Xh={};Xh[UP]="z";Jh.exports=String(Xh)==="[object z]"});var Di=m((vV,Zh)=>{"use strict";var HP=Ds(),jP=ee(),Cs=ir(),GP=he(),QP=GP("toStringTag"),WP=Object,YP=Cs(function(){return arguments}())==="Arguments",zP=function(a,e){try{return a[e]}catch(t){}};Zh.exports=HP?Cs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=zP(e=WP(a),QP))=="string"?t:YP?Cs(e):(r=Cs(e))==="Object"&&jP(e.callee)?"Arguments":r}});var tf=m((SV,ef)=>{"use strict";var KP=Ds(),XP=Di();ef.exports=KP?{}.toString:function(){return"[object "+XP(this)+"]"}});var Ci=m((yV,af)=>{"use strict";var JP=Ds(),ZP=nr().f,ew=_r(),tw=Ke(),rw=tf(),iw=he(),rf=iw("toStringTag");af.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(tw(i,rf)||ZP(i,rf,{configurable:!0,value:e}),r&&!JP&&ew(i,"toString",rw))}});var nf=m((TV,sf)=>{"use strict";var aw=ou().IteratorPrototype,sw=iu(),nw=Ei(),ow=Ci(),uw=or(),lw=function(){return this};sf.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=sw(aw,{next:nw(+!r,t)}),ow(a,i,!1,!0),uw[i]=lw,a}});var uf=m((IV,of)=>{"use strict";var cw=ne(),dw=st();of.exports=function(a,e,t){try{return cw(dw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var cf=m((EV,lf)=>{"use strict";var pw=Ce();lf.exports=function(a){return pw(a)||a===null}});var pf=m((xV,df)=>{"use strict";var hw=cf(),fw=String,mw=TypeError;df.exports=function(a){if(hw(a))return a;throw new mw("Can't set "+fw(a)+" as a prototype")}});var uu=m((PV,hf)=>{"use strict";var bw=uf(),gw=Ce(),vw=Mt(),Sw=pf();hf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=bw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return vw(i),Sw(s),gw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var xf=m((wV,Ef)=>{"use strict";var yw=se(),Tw=De(),Bs=ze(),Tf=Jo(),Iw=ee(),Ew=nf(),ff=As(),mf=uu(),xw=Ci(),Pw=_r(),lu=Hr(),ww=he(),bf=or(),If=ou(),Aw=Tf.PROPER,kw=Tf.CONFIGURABLE,gf=If.IteratorPrototype,Vs=If.BUGGY_SAFARI_ITERATORS,Bi=ww("iterator"),vf="keys",Vi="values",Sf="entries",yf=function(){return this};Ef.exports=function(a,e,t,r,i,s,n){Ew(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Vs&&v&&v in c)return c[v];switch(v){case vf:return function(){return new t(this,v)};case Vi:return function(){return new t(this,v)};case Sf:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Bi]||c["@@iterator"]||i&&c[i],p=!Vs&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=ff(h.call(new a)),f!==Object.prototype&&f.next&&(!Bs&&ff(f)!==gf&&(mf?mf(f,gf):Iw(f[Bi])||lu(f,Bi,yf)),xw(f,u,!0,!0),Bs&&(bf[u]=yf))),Aw&&i===Vi&&d&&d.name!==Vi&&(!Bs&&kw?Pw(c,"name",Vi):(l=!0,p=function(){return Tw(d,this)})),i)if(b={values:o(Vi),keys:s?p:o(vf),entries:o(Sf)},n)for(g in b)(Vs||l||!(g in c))&&lu(c,g,b[g]);else yw({target:e,proto:!0,forced:Vs||l},b);return(!Bs||n)&&c[Bi]!==p&&lu(c,Bi,p,{name:i}),bf[e]=p,b}});var wf=m((AV,Pf)=>{"use strict";Pf.exports=function(a,e){return{value:a,done:e}}});var du=m((kV,Lf)=>{"use strict";var Rw=ar(),cu=Li(),Af=or(),Rf=zo(),$w=nr().f,Lw=xf(),Os=wf(),Mw=ze(),Dw=Me(),$f="Array Iterator",Cw=Rf.set,Bw=Rf.getterFor($f);Lf.exports=Lw(Array,"Array",function(a,e){Cw(this,{type:$f,target:Rw(a),index:0,kind:e})},function(){var a=Bw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Os(void 0,!0);switch(a.kind){case"keys":return Os(t,!1);case"values":return Os(e[t],!1)}return Os([t,e[t]],!1)},"values");var kf=Af.Arguments=Af.Array;cu("keys");cu("values");cu("entries");if(!Mw&&Dw&&kf.name!=="values")try{$w(kf,"name",{value:"values"})}catch(a){}});var Df=m((RV,Mf)=>{"use strict";var Vw=he(),Ow=or(),_w=Vw("iterator"),Nw=Array.prototype;Mf.exports=function(a){return a!==void 0&&(Ow.Array===a||Nw[_w]===a)}});var pu=m(($V,Bf)=>{"use strict";var Fw=Di(),Cf=wi(),qw=Dr(),Uw=or(),Hw=he(),jw=Hw("iterator");Bf.exports=function(a){if(!qw(a))return Cf(a,jw)||Cf(a,"@@iterator")||Uw[Fw(a)]}});var Of=m((LV,Vf)=>{"use strict";var Gw=De(),Qw=st(),Ww=nt(),Yw=Pi(),zw=pu(),Kw=TypeError;Vf.exports=function(a,e){var t=arguments.length<2?zw(a):e;if(Qw(t))return Ww(Gw(t,a));throw new Kw(Yw(a)+" is not iterable")}});var Ff=m((MV,Nf)=>{"use strict";var Xw=De(),_f=nt(),Jw=wi();Nf.exports=function(a,e,t){var r,i;_f(a);try{if(r=Jw(a,"return"),!r){if(e==="throw")throw t;return t}r=Xw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return _f(r),t}});var Ns=m((DV,jf)=>{"use strict";var Zw=Or(),eA=De(),tA=nt(),rA=Pi(),iA=Df(),aA=qr(),qf=xi(),sA=Of(),nA=pu(),Uf=Ff(),oA=TypeError,_s=function(a,e){this.stopped=a,this.result=e},Hf=_s.prototype;jf.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Zw(e,r),l,c,d,p,h,f,b,g=function(S){return l&&Uf(l,"normal",S),new _s(!0,S)},v=function(S){return i?(tA(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=nA(a),!c)throw new oA(rA(a)+" is not iterable");if(iA(c)){for(d=0,p=aA(a);p>d;d++)if(h=v(a[d]),h&&qf(Hf,h))return h;return new _s(!1)}l=sA(a,c)}for(f=s?a.next:l.next;!(b=eA(f,l)).done;){try{h=v(b.value)}catch(S){Uf(l,"throw",S)}if(typeof h=="object"&&h&&qf(Hf,h))return h}return new _s(!1)}});var Qf=m((CV,Gf)=>{"use strict";var uA=Me(),lA=nr(),cA=Ei();Gf.exports=function(a,e,t){uA?lA.f(a,e,cA(0,t)):a[e]=t}});var Wf=m(()=>{"use strict";var dA=se(),pA=Ns(),hA=Qf();dA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return pA(e,function(r,i){hA(t,r,i)},{AS_ENTRIES:!0}),t}})});var zf=m((OV,Yf)=>{"use strict";du();Wf();var fA=Cr();Yf.exports=fA.Object.fromEntries});var Xf=m((_V,Kf)=>{"use strict";Kf.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Zf=m(()=>{"use strict";du();var mA=Xf(),bA=re(),gA=Ci(),Jf=or();for(Fs in mA)gA(bA[Fs],Fs),Jf[Fs]=Jf.Array;var Fs});var tm=m((qV,em)=>{"use strict";var vA=zf();Zf();em.exports=vA});var hu=m((UV,rm)=>{"use strict";var SA=tm();rm.exports=SA});var im=m(()=>{"use strict"});var fu=m((GV,am)=>{"use strict";var Oi=re(),yA=sr(),TA=ir(),qs=function(a){return yA.slice(0,a.length)===a};am.exports=function(){return qs("Bun/")?"BUN":qs("Cloudflare-Workers")?"CLOUDFLARE":qs("Deno/")?"DENO":qs("Node.js/")?"NODE":Oi.Bun&&typeof Bun.version=="string"?"BUN":Oi.Deno&&typeof Deno.version=="object"?"DENO":TA(Oi.process)==="process"?"NODE":Oi.window&&Oi.document?"BROWSER":"REST"}()});var Us=m((QV,sm)=>{"use strict";var IA=fu();sm.exports=IA==="NODE"});var om=m((WV,nm)=>{"use strict";var EA=nr();nm.exports=function(a,e,t){return EA.f(a,e,t)}});var cm=m((YV,lm)=>{"use strict";var xA=pt(),PA=om(),wA=he(),AA=Me(),um=wA("species");lm.exports=function(a){var e=xA(a);AA&&e&&!e[um]&&PA(e,um,{configurable:!0,get:function(){return this}})}});var pm=m((zV,dm)=>{"use strict";var kA=xi(),RA=TypeError;dm.exports=function(a,e){if(kA(e,a))return a;throw new RA("Incorrect invocation")}});var bu=m((KV,hm)=>{"use strict";var $A=ne(),LA=ee(),mu=Ai(),MA=$A(Function.toString);LA(mu.inspectSource)||(mu.inspectSource=function(a){return MA(a)});hm.exports=mu.inspectSource});var vu=m((XV,vm)=>{"use strict";var DA=ne(),CA=pe(),fm=ee(),BA=Di(),VA=pt(),OA=bu(),mm=function(){},bm=VA("Reflect","construct"),gu=/^\s*(?:class|function)\b/,_A=DA(gu.exec),NA=!gu.test(mm),_i=function(e){if(!fm(e))return!1;try{return bm(mm,[],e),!0}catch(t){return!1}},gm=function(e){if(!fm(e))return!1;switch(BA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return NA||!!_A(gu,OA(e))}catch(t){return!0}};gm.sham=!0;vm.exports=!bm||CA(function(){var a;return _i(_i.call)||!_i(Object)||!_i(function(){a=!0})||a})?gm:_i});var ym=m((JV,Sm)=>{"use strict";var FA=vu(),qA=Pi(),UA=TypeError;Sm.exports=function(a){if(FA(a))return a;throw new UA(qA(a)+" is not a constructor")}});var Su=m((ZV,Im)=>{"use strict";var Tm=nt(),HA=ym(),jA=Dr(),GA=he(),QA=GA("species");Im.exports=function(a,e){var t=Tm(a).constructor,r;return t===void 0||jA(r=Tm(t)[QA])?e:HA(r)}});var xm=m((eO,Em)=>{"use strict";var WA=ne();Em.exports=WA([].slice)});var wm=m((tO,Pm)=>{"use strict";var YA=TypeError;Pm.exports=function(a,e){if(a<e)throw new YA("Not enough arguments");return a}});var yu=m((rO,Am)=>{"use strict";var zA=sr();Am.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(zA)});var Ru=m((iO,Vm)=>{"use strict";var Be=re(),KA=uo(),XA=Or(),km=ee(),JA=Ke(),Bm=pe(),Rm=Zo(),ZA=xm(),$m=Is(),ek=wm(),tk=yu(),rk=Us(),wu=Be.setImmediate,Au=Be.clearImmediate,ik=Be.process,Tu=Be.Dispatch,ak=Be.Function,Lm=Be.MessageChannel,sk=Be.String,Iu=0,Ni={},Mm="onreadystatechange",Fi,lr,Eu,xu;Bm(function(){Fi=Be.location});var ku=function(a){if(JA(Ni,a)){var e=Ni[a];delete Ni[a],e()}},Pu=function(a){return function(){ku(a)}},Dm=function(a){ku(a.data)},Cm=function(a){Be.postMessage(sk(a),Fi.protocol+"//"+Fi.host)};(!wu||!Au)&&(wu=function(e){ek(arguments.length,1);var t=km(e)?e:ak(e),r=ZA(arguments,1);return Ni[++Iu]=function(){KA(t,void 0,r)},lr(Iu),Iu},Au=function(e){delete Ni[e]},rk?lr=function(a){ik.nextTick(Pu(a))}:Tu&&Tu.now?lr=function(a){Tu.now(Pu(a))}:Lm&&!tk?(Eu=new Lm,xu=Eu.port2,Eu.port1.onmessage=Dm,lr=XA(xu.postMessage,xu)):Be.addEventListener&&km(Be.postMessage)&&!Be.importScripts&&Fi&&Fi.protocol!=="file:"&&!Bm(Cm)?(lr=Cm,Be.addEventListener("message",Dm,!1)):Mm in $m("script")?lr=function(a){Rm.appendChild($m("script"))[Mm]=function(){Rm.removeChild(this),ku(a)}}:lr=function(a){setTimeout(Pu(a),0)});Vm.exports={set:wu,clear:Au}});var Nm=m((aO,_m)=>{"use strict";var Om=re(),nk=Me(),ok=Object.getOwnPropertyDescriptor;_m.exports=function(a){if(!nk)return Om[a];var e=ok(Om,a);return e&&e.value}});var $u=m((sO,qm)=>{"use strict";var Fm=function(){this.head=null,this.tail=null};Fm.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};qm.exports=Fm});var Hm=m((nO,Um)=>{"use strict";var uk=sr();Um.exports=/ipad|iphone|ipod/i.test(uk)&&typeof Pebble!="undefined"});var Gm=m((oO,jm)=>{"use strict";var lk=sr();jm.exports=/web0s(?!.*chrome)/i.test(lk)});var Jm=m((uO,Xm)=>{"use strict";var Gr=re(),ck=Nm(),Qm=Or(),Lu=Ru().set,dk=$u(),pk=yu(),hk=Hm(),fk=Gm(),Mu=Us(),Wm=Gr.MutationObserver||Gr.WebKitMutationObserver,Ym=Gr.document,zm=Gr.process,Hs=Gr.Promise,Bu=ck("queueMicrotask"),jr,Du,Cu,js,Km;Bu||(qi=new dk,Ui=function(){var a,e;for(Mu&&(a=zm.domain)&&a.exit();e=qi.get();)try{e()}catch(t){throw qi.head&&jr(),t}a&&a.enter()},!pk&&!Mu&&!fk&&Wm&&Ym?(Du=!0,Cu=Ym.createTextNode(""),new Wm(Ui).observe(Cu,{characterData:!0}),jr=function(){Cu.data=Du=!Du}):!hk&&Hs&&Hs.resolve?(js=Hs.resolve(void 0),js.constructor=Hs,Km=Qm(js.then,js),jr=function(){Km(Ui)}):Mu?jr=function(){zm.nextTick(Ui)}:(Lu=Qm(Lu,Gr),jr=function(){Lu(Ui)}),Bu=function(a){qi.head||jr(),qi.add(a)});var qi,Ui;Xm.exports=Bu});var eb=m((lO,Zm)=>{"use strict";Zm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Gs=m((cO,tb)=>{"use strict";tb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var cr=m((dO,rb)=>{"use strict";var mk=re();rb.exports=mk.Promise});var Qr=m((pO,nb)=>{"use strict";var bk=re(),Hi=cr(),gk=ee(),vk=Lo(),Sk=bu(),yk=he(),ib=fu(),Tk=ze(),Vu=vo(),ab=Hi&&Hi.prototype,Ik=yk("species"),Ou=!1,sb=gk(bk.PromiseRejectionEvent),Ek=vk("Promise",function(){var a=Sk(Hi),e=a!==String(Hi);if(!e&&Vu===66||Tk&&!(ab.catch&&ab.finally))return!0;if(!Vu||Vu<51||!/native code/.test(a)){var t=new Hi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Ik]=r,Ou=t.then(function(){})instanceof r,!Ou)return!0}return!e&&(ib==="BROWSER"||ib==="DENO")&&!sb});nb.exports={CONSTRUCTOR:Ek,REJECTION_EVENT:sb,SUBCLASSING:Ou}});var Wr=m((hO,ub)=>{"use strict";var ob=st(),xk=TypeError,Pk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new xk("Bad Promise constructor");e=r,t=i}),this.resolve=ob(e),this.reject=ob(t)};ub.exports.f=function(a){return new Pk(a)}});var Ab=m(()=>{"use strict";var wk=se(),Ak=ze(),zs=Us(),Ct=re(),Xr=De(),lb=Hr(),cb=uu(),kk=Ci(),Rk=cm(),$k=st(),Ys=ee(),Lk=Ce(),Mk=pm(),Dk=Su(),mb=Ru().set,Uu=Jm(),Ck=eb(),Bk=Gs(),Vk=$u(),bb=zo(),Ks=cr(),Hu=Qr(),gb=Wr(),Xs="Promise",vb=Hu.CONSTRUCTOR,Ok=Hu.REJECTION_EVENT,_k=Hu.SUBCLASSING,_u=bb.getterFor(Xs),Nk=bb.set,Yr=Ks&&Ks.prototype,dr=Ks,Qs=Yr,Sb=Ct.TypeError,Nu=Ct.document,ju=Ct.process,Fu=gb.f,Fk=Fu,qk=!!(Nu&&Nu.createEvent&&Ct.dispatchEvent),yb="unhandledrejection",Uk="rejectionhandled",db=0,Tb=1,Hk=2,Gu=1,Ib=2,Ws,pb,jk,hb,Eb=function(a){var e;return Lk(a)&&Ys(e=a.then)?e:!1},xb=function(a,e){var t=e.value,r=e.state===Tb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Ib&&Qk(e),e.rejection=Gu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Sb("Promise-chain cycle")):(l=Eb(u))?Xr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Pb=function(a,e){a.notified||(a.notified=!0,Uu(function(){for(var t=a.reactions,r;r=t.get();)xb(r,a);a.notified=!1,e&&!a.rejection&&Gk(a)}))},wb=function(a,e,t){var r,i;qk?(r=Nu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Ct.dispatchEvent(r)):r={promise:e,reason:t},!Ok&&(i=Ct["on"+a])?i(r):a===yb&&Ck("Unhandled promise rejection",t)},Gk=function(a){Xr(mb,Ct,function(){var e=a.facade,t=a.value,r=fb(a),i;if(r&&(i=Bk(function(){zs?ju.emit("unhandledRejection",t,e):wb(yb,e,t)}),a.rejection=zs||fb(a)?Ib:Gu,i.error))throw i.value})},fb=function(a){return a.rejection!==Gu&&!a.parent},Qk=function(a){Xr(mb,Ct,function(){var e=a.facade;zs?ju.emit("rejectionHandled",e):wb(Uk,e,a.value)})},zr=function(a,e,t){return function(r){a(e,r,t)}},Kr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Hk,Pb(a,!0))},qu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Sb("Promise can't be resolved itself");var r=Eb(e);r?Uu(function(){var i={done:!1};try{Xr(r,e,zr(qu,i,a),zr(Kr,i,a))}catch(s){Kr(i,s,a)}}):(a.value=e,a.state=Tb,Pb(a,!1))}catch(i){Kr({done:!1},i,a)}}};if(vb&&(dr=function(e){Mk(this,Qs),$k(e),Xr(Ws,this);var t=_u(this);try{e(zr(qu,t),zr(Kr,t))}catch(r){Kr(t,r)}},Qs=dr.prototype,Ws=function(e){Nk(this,{type:Xs,done:!1,notified:!1,parent:!1,reactions:new Vk,rejection:!1,state:db,value:void 0})},Ws.prototype=lb(Qs,"then",function(e,t){var r=_u(this),i=Fu(Dk(this,dr));return r.parent=!0,i.ok=Ys(e)?e:!0,i.fail=Ys(t)&&t,i.domain=zs?ju.domain:void 0,r.state===db?r.reactions.add(i):Uu(function(){xb(i,r)}),i.promise}),pb=function(){var a=new Ws,e=_u(a);this.promise=a,this.resolve=zr(qu,e),this.reject=zr(Kr,e)},gb.f=Fu=function(a){return a===dr||a===jk?new pb(a):Fk(a)},!Ak&&Ys(Ks)&&Yr!==Object.prototype)){hb=Yr.then,_k||lb(Yr,"then",function(e,t){var r=this;return new dr(function(i,s){Xr(hb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Yr.constructor}catch(a){}cb&&cb(Yr,Qs)}wk({global:!0,constructor:!0,wrap:!0,forced:vb},{Promise:dr});kk(dr,Xs,!1,!0);Rk(Xs)});var Mb=m((bO,Lb)=>{"use strict";var Wk=he(),Rb=Wk("iterator"),$b=!1;try{kb=0,Qu={next:function(){return{done:!!kb++}},return:function(){$b=!0}},Qu[Rb]=function(){return this},Array.from(Qu,function(){throw 2})}catch(a){}var kb,Qu;Lb.exports=function(a,e){try{if(!e&&!$b)return!1}catch(i){return!1}var t=!1;try{var r={};r[Rb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Wu=m((gO,Db)=>{"use strict";var Yk=cr(),zk=Mb(),Kk=Qr().CONSTRUCTOR;Db.exports=Kk||!zk(function(a){Yk.all(a).then(void 0,function(){})})});var Cb=m(()=>{"use strict";var Xk=se(),Jk=De(),Zk=st(),eR=Wr(),tR=Gs(),rR=Ns(),iR=Wu();Xk({target:"Promise",stat:!0,forced:iR},{all:function(e){var t=this,r=eR.f(t),i=r.resolve,s=r.reject,n=tR(function(){var o=Zk(t.resolve),u=[],l=0,c=1;rR(e,function(d){var p=l++,h=!1;c++,Jk(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Vb=m(()=>{"use strict";var aR=se(),sR=ze(),nR=Qr().CONSTRUCTOR,zu=cr(),oR=pt(),uR=ee(),lR=Hr(),Bb=zu&&zu.prototype;aR({target:"Promise",proto:!0,forced:nR,real:!0},{catch:function(a){return this.then(void 0,a)}});!sR&&uR(zu)&&(Yu=oR("Promise").prototype.catch,Bb.catch!==Yu&&lR(Bb,"catch",Yu,{unsafe:!0}));var Yu});var Ob=m(()=>{"use strict";var cR=se(),dR=De(),pR=st(),hR=Wr(),fR=Gs(),mR=Ns(),bR=Wu();cR({target:"Promise",stat:!0,forced:bR},{race:function(e){var t=this,r=hR.f(t),i=r.reject,s=fR(function(){var n=pR(t.resolve);mR(e,function(o){dR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var _b=m(()=>{"use strict";var gR=se(),vR=Wr(),SR=Qr().CONSTRUCTOR;gR({target:"Promise",stat:!0,forced:SR},{reject:function(e){var t=vR.f(this),r=t.reject;return r(e),t.promise}})});var Ku=m((wO,Nb)=>{"use strict";var yR=nt(),TR=Ce(),IR=Wr();Nb.exports=function(a,e){if(yR(a),TR(e)&&e.constructor===a)return e;var t=IR.f(a),r=t.resolve;return r(e),t.promise}});var Ub=m(()=>{"use strict";var ER=se(),xR=pt(),Fb=ze(),PR=cr(),qb=Qr().CONSTRUCTOR,wR=Ku(),AR=xR("Promise"),kR=Fb&&!qb;ER({target:"Promise",stat:!0,forced:Fb||qb},{resolve:function(e){return wR(kR&&this===AR?PR:this,e)}})});var Hb=m(()=>{"use strict";Ab();Cb();Vb();Ob();_b();Ub()});var Wb=m(()=>{"use strict";var RR=se(),$R=ze(),Js=cr(),LR=pe(),Gb=pt(),Qb=ee(),MR=Su(),jb=Ku(),DR=Hr(),Ju=Js&&Js.prototype,CR=!!Js&&LR(function(){Ju.finally.call({then:function(){}},function(){})});RR({target:"Promise",proto:!0,real:!0,forced:CR},{finally:function(a){var e=MR(this,Gb("Promise")),t=Qb(a);return this.then(t?function(r){return jb(e,a()).then(function(){return r})}:a,t?function(r){return jb(e,a()).then(function(){throw r})}:a)}});!$R&&Qb(Js)&&(Xu=Gb("Promise").prototype.finally,Ju.finally!==Xu&&DR(Ju,"finally",Xu,{unsafe:!0}));var Xu});var zb=m((DO,Yb)=>{"use strict";im();Hb();Wb();var BR=Dt();Yb.exports=BR("Promise","finally")});var Xb=m((CO,Kb)=>{"use strict";var VR=zb();Kb.exports=VR});var Zs=m((BO,Jb)=>{"use strict";var OR=Xb();Jb.exports=OR});var dg=m(()=>{"use strict";var XR=se(),JR=Go().values;XR({target:"Object",stat:!0},{values:function(e){return JR(e)}})});var hg=m((S_,pg)=>{"use strict";dg();var ZR=Cr();pg.exports=ZR.Object.values});var mg=m((y_,fg)=>{"use strict";var e$=hg();fg.exports=e$});var Zr=m((T_,bg)=>{"use strict";var t$=mg();bg.exports=t$});var Rg=m(()=>{"use strict";var g$=se(),v$=Br(),S$=qr(),y$=$i(),T$=Li();g$({target:"Array",proto:!0},{at:function(e){var t=v$(this),r=S$(t),i=y$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});T$("at")});var Lg=m((z_,$g)=>{"use strict";Rg();var I$=Dt();$g.exports=I$("Array","at")});var Dg=m((K_,Mg)=>{"use strict";var E$=Lg();Mg.exports=E$});var ti=m((X_,Cg)=>{"use strict";var x$=Dg();Cg.exports=x$});var Tl=m((wF,cv)=>{"use strict";var sL=ir();cv.exports=Array.isArray||function(e){return sL(e)==="Array"}});var pv=m((AF,dv)=>{"use strict";var nL=TypeError,oL=9007199254740991;dv.exports=function(a){if(a>oL)throw nL("Maximum allowed index exceeded");return a}});var mv=m((kF,fv)=>{"use strict";var uL=Tl(),lL=qr(),cL=pv(),dL=Or(),hv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?dL(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&uL(d)?(p=lL(d),u=hv(a,e,d,p,u,s-1)-1):(cL(u+1),a[u]=d),u++),l++;return u};fv.exports=hv});var Sv=m((RF,vv)=>{"use strict";var bv=Tl(),pL=vu(),hL=Ce(),fL=he(),mL=fL("species"),gv=Array;vv.exports=function(a){var e;return bv(a)&&(e=a.constructor,pL(e)&&(e===gv||bv(e.prototype))?e=void 0:hL(e)&&(e=e[mL],e===null&&(e=void 0))),e===void 0?gv:e}});var Tv=m(($F,yv)=>{"use strict";var bL=Sv();yv.exports=function(a,e){return new(bL(a))(e===0?0:e)}});var Iv=m(()=>{"use strict";var gL=se(),vL=mv(),SL=st(),yL=Br(),TL=qr(),IL=Tv();gL({target:"Array",proto:!0},{flatMap:function(e){var t=yL(this),r=TL(t),i;return SL(e),i=IL(t,0),i.length=vL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Ev=m(()=>{"use strict";var EL=Li();EL("flatMap")});var Pv=m((BF,xv)=>{"use strict";Iv();Ev();var xL=Dt();xv.exports=xL("Array","flatMap")});var Av=m((VF,wv)=>{"use strict";var PL=Pv();wv.exports=PL});var Il=m((OF,kv)=>{"use strict";var wL=Av();kv.exports=wL});var aa=m((YF,Yv)=>{"use strict";var CL=Di(),BL=String;Yv.exports=function(a){if(CL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return BL(a)}});var xl=m((zF,zv)=>{"use strict";zv.exports=`
7
- \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Jv=m((KF,Xv)=>{"use strict";var VL=ne(),OL=Mt(),_L=aa(),wl=xl(),Kv=VL("".replace),NL=RegExp("^["+wl+"]+"),FL=RegExp("(^|[^"+wl+"])["+wl+"]+$"),Pl=function(a){return function(e){var t=_L(OL(e));return a&1&&(t=Kv(t,NL,"")),a&2&&(t=Kv(t,FL,"$1")),t}};Xv.exports={start:Pl(1),end:Pl(2),trim:Pl(3)}});var rS=m((XF,tS)=>{"use strict";var qL=Jo().PROPER,UL=pe(),Zv=xl(),eS="\u200B\x85\u180E";tS.exports=function(a){return UL(function(){return!!Zv[a]()||eS[a]()!==eS||qL&&Zv[a].name!==a})}});var Al=m((JF,iS)=>{"use strict";var HL=Jv().start,jL=rS();iS.exports=jL("trimStart")?function(){return HL(this)}:"".trimStart});var sS=m(()=>{"use strict";var GL=se(),aS=Al();GL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==aS},{trimLeft:aS})});var oS=m(()=>{"use strict";sS();var QL=se(),nS=Al();QL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==nS},{trimStart:nS})});var lS=m((iq,uS)=>{"use strict";oS();var WL=Dt();uS.exports=WL("String","trimLeft")});var dS=m((aq,cS)=>{"use strict";var YL=lS();cS.exports=YL});var hS=m((sq,pS)=>{"use strict";var zL=dS();pS.exports=zL});var RS=m(()=>{"use strict"});var $S=m(()=>{"use strict"});var MS=m((q1,LS)=>{"use strict";var vM=Ce(),SM=ir(),yM=he(),TM=yM("match");LS.exports=function(a){var e;return vM(a)&&((e=a[TM])!==void 0?!!e:SM(a)==="RegExp")}});var CS=m((U1,DS)=>{"use strict";var IM=nt();DS.exports=function(){var a=IM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var OS=m((H1,VS)=>{"use strict";var EM=De(),xM=Ke(),PM=xi(),wM=CS(),BS=RegExp.prototype;VS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in BS)&&!xM(a,"flags")&&PM(BS,a)?EM(wM,a):e}});var NS=m((j1,_S)=>{"use strict";var Vl=ne(),AM=Br(),kM=Math.floor,Cl=Vl("".charAt),RM=Vl("".replace),Bl=Vl("".slice),$M=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,LM=/\$([$&'`]|\d{1,2})/g;_S.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=LM;return i!==void 0&&(i=AM(i),u=$M),RM(s,u,function(l,c){var d;switch(Cl(c,0)){case"$":return"$";case"&":return a;case"`":return Bl(e,0,t);case"'":return Bl(e,n);case"<":d=i[Bl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=kM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Cl(c,1):r[h-1]+Cl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var US=m(()=>{"use strict";var MM=se(),DM=De(),_l=ne(),FS=Mt(),CM=ee(),BM=Dr(),VM=MS(),oi=aa(),OM=wi(),_M=OS(),NM=NS(),FM=he(),qM=ze(),UM=FM("replace"),HM=TypeError,Ol=_l("".indexOf),jM=_l("".replace),qS=_l("".slice),GM=Math.max;MM({target:"String",proto:!0},{replaceAll:function(e,t){var r=FS(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!BM(e)){if(i=VM(e),i&&(s=oi(FS(_M(e))),!~Ol(s,"g")))throw new HM("`.replaceAll` does not allow non-global regexes");if(n=OM(e,UM),n)return DM(n,e,r,t);if(qM&&i)return jM(oi(r),e,t)}for(o=oi(r),u=oi(e),l=CM(t),l||(t=oi(t)),c=u.length,d=GM(1,c),p=Ol(o,u);p!==-1;)h=l?oi(t(u,p,o)):NM(u,o,p,[],void 0,t),b+=qS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Ol(o,u,p+d);return f<o.length&&(b+=qS(o,f)),b}})});var jS=m((W1,HS)=>{"use strict";RS();$S();US();var QM=Dt();HS.exports=QM("String","replaceAll")});var QS=m((Y1,GS)=>{"use strict";var WM=jS();GS.exports=WM});var YS=m((z1,WS)=>{"use strict";var YM=QS();WS.exports=YM});var KS=m((K1,zS)=>{"use strict";var zM=$i(),KM=aa(),XM=Mt(),JM=RangeError;zS.exports=function(e){var t=KM(XM(this)),r="",i=zM(e);if(i<0||i===1/0)throw new JM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var ty=m((X1,ey)=>{"use strict";var ZS=ne(),ZM=Oo(),XS=aa(),eD=KS(),tD=Mt(),rD=ZS(eD),iD=ZS("".slice),aD=Math.ceil,JS=function(a){return function(e,t,r){var i=XS(tD(e)),s=ZM(t),n=i.length,o=r===void 0?" ":XS(r),u,l;return s<=n||o===""?i:(u=s-n,l=rD(o,aD(u/o.length)),l.length>u&&(l=iD(l,0,u)),a?i+l:l+i)}};ey.exports={start:JS(!1),end:JS(!0)}});var iy=m((J1,ry)=>{"use strict";var sD=sr();ry.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(sD)});var ay=m(()=>{"use strict";var nD=se(),oD=ty().start,uD=iy();nD({target:"String",proto:!0,forced:uD},{padStart:function(e){return oD(this,e,arguments.length>1?arguments[1]:void 0)}})});var ny=m((tH,sy)=>{"use strict";ay();var lD=Dt();sy.exports=lD("String","padStart")});var uy=m((rH,oy)=>{"use strict";var cD=ny();oy.exports=cD});var cy=m((iH,ly)=>{"use strict";var dD=uy();ly.exports=dD});var nd="2.0.124-dev.99952f80.0";var Ie=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Ie||{}),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 Ss=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ss||{}),so=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(so||{});var no=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(no||{});var qT=O(Xe(),1);import{assertNever as ah,assertNonNullable as xx,isNonNullable as xs,ValueSubject as No,Subject as Px,Subscription as wx,merge as Ax,observableFrom as kx,fromEvent as eh,map as th,tap as rh,filterChanged as Rx,isNullable as Fo,ErrorCategory as ih}from"@vkontakte/videoplayer-shared/es2015";var Zp=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var Ps=class{constructor(e){this.connection$=new No(void 0);this.castState$=new No("NOT_AVAILABLE");this.errorEvent$=new Px;this.realCastState$=new No("NOT_AVAILABLE");this.subscription=new wx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=xs((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Zp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ih.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){xs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Fo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Fo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(eh(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return ah(i.sessionState)}})).add(Ax(eh(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(rh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),th(i=>i.castState)),kx([r.getCastState()])).pipe(Rx(),th($x),rh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=xs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();xx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Fo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?xs(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:ih.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},$x=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return ah(a)}};var bc=O(Xe(),1),TT=O(Ur(),1),IT=O(hu(),1);var ug=O(Zs(),1);import{assertNever as Zb}from"@vkontakte/videoplayer-shared/es2015";var fe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Zb(t)}return a},en=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Zb(e)}};var P=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as _R,Subject as tn,merge as eg}from"@vkontakte/videoplayer-shared/es2015";var C=class{constructor(e){this.transitionStarted$=new tn;this.transitionEnded$=new tn;this.transitionUpdated$=new tn;this.forceChanged$=new tn;this.stateChangeStarted$=eg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=eg(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||_R(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as NR}from"@vkontakte/videoplayer-shared/es2015";var tg=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return NR(a)}};import{assertNever as Jr,assertNonNullable as pr,debounce as rg,ErrorCategory as ig,fromEvent as hr,isNonNullable as ag,map as sg,merge as ng,observableFrom as FR,Subject as qR,Subscription as Zu,timeout as UR,getHighestQuality as HR}from"@vkontakte/videoplayer-shared/es2015";var jR=5,GR=5,QR=500,og=7e3,ji=class{constructor(e){this.subscription=new Zu;this.loadMediaTimeoutSubscription=new Zu;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Jr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Jr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Jr(e)}break}default:Jr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(tg(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Zu;this.subscription.add(e),this.subscription.add(ng(this.videoState.stateChangeStarted$.pipe(sg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(sg(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new qR;e.add(i.pipe(rg(QR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>jR)&&i.next(o),s=o})),e.add(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<GR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Jr(n)}}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=ng(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,FR(["init"])).pipe(rg(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];pr(c);let d=HR(Object.keys(c));pr(d);let p=c[d];pr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];pr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];pr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];pr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];pr(c),r=fe(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:ig.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Jr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return ag(o)&&(n.metadata.title=o),ag(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(UR(og).subscribe(()=>s(`timeout(${og})`)))});(0,ug.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ig.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Sl=O(Xe(),1);import{clearVideoElement as cg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as WR}from"@vkontakte/videoplayer-shared/es2015";var lg=a=>{try{a.pause(),a.playbackRate=0,WR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as YR,Subscription as zR}from"@vkontakte/videoplayer-shared/es2015";var el=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},tl=window.WeakMap?new WeakMap:new el,rl=window.WeakMap?new WeakMap:new Map,KR=(a,e=20)=>{let t=0;return YR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?cg(t):(t=document.createElement("video"),a.appendChild(t)),tl.set(t,r);let i=new zR;return i.add(KR(t,e)),rl.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},xe=a=>{let e=rl.get(a);e==null||e.unsubscribe(),rl.delete(a);let t=tl.get(a);tl.delete(a),t?cg(a):lg(a)};var al=O(Zr(),1);import{assertNonNullable as Gi,isNonNullable as ut,isNullable as a$,fromEvent as ei,merge as gg,observableFrom as vg,filterChanged as Sg,map as Qi,Subject as yg,Subscription as s$,ValueSubject as n$,ErrorCategory as o$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as il,isNullable as r$,Subscription as i$}from"@vkontakte/videoplayer-shared/es2015";var rn=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=r$(i),l=new i$;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>rn(e,()=>a.loop,r=>{il(r)&&(a.loop=r)},{onError:t}),Pe=(a,e,t,r)=>rn(e,()=>({muted:a.muted,volume:a.volume}),i=>{il(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Fe=(a,e,t,r)=>rn(e,()=>a.playbackRate,i=>{il(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Bt=rn;var u$=a=>["__",a.language,a.label].join("|"),l$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},sl=class a{constructor(e){this.available$=new yg;this.current$=new n$(void 0);this.error$=new yg;this.subscription=new s$;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:o$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Bt(t.internalTextTracks,()=>(0,al.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Qi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Bt(t.externalTextTracks,()=>(0,al.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Qi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Bt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Bt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Gi(this.video);let{textTracks:e}=this.video;this.subscription.add(ei(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(gg(ei(e,"addtrack"),ei(e,"removetrack"),vg(["init"])).pipe(Qi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Sg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(gg(ei(e,"change"),vg(["init"])).pipe(Qi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Qi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Sg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(ei(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(ei(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;ut(t.align)&&(i.align=t.align),ut(t.position)&&(i.position=t.position),ut(t.size)&&(i.size=t.size),ut(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Gi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:u$(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){Gi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(a$(e)||!l$(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Gi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Gi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},qe=sl;var mt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Tg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},nl=a=>{let e=Tg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Ig=a=>{let e=Tg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ue,map as Vt,merge as xg,filterChanged as d$,isNonNullable as Pg,Subject as p$,filter as wg,mapTo as Ag,combine as h$,once as f$,ErrorCategory as m$,ValueSubject as kg,clientChecker as b$}from"@vkontakte/videoplayer-shared/es2015";var c$=3,Eg=(a,e,t=c$)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var we=a=>{let e=y=>Ue(a,y).pipe(Ag(void 0)),r=xg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Ue(a,y))).pipe(Vt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),d$()),i=xg(Ue(a,"progress"),Ue(a,"timeupdate")).pipe(Vt(()=>Eg(a.buffered,a.currentTime))),s=b$.isSafari?h$({play:e("play").pipe(f$()),playing:e("playing")}).pipe(Ag(void 0)):e("playing"),n=Ue(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=Ue(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=Ue(a,"error").pipe(wg(()=>!!(a.error||a.played.length)),Vt(()=>{var x;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:m$.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(x=a.error)!=null?x:void 0}})),l=Ue(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new p$,d=.3,p;l.subscribe(y=>{a.loop&&Pg(p)&&Pg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(wg(()=>!a.error&&p!==a.duration)),f=Ue(a,"enterpictureinpicture"),b=Ue(a,"leavepictureinpicture"),g=new kg(Ig(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new kg(nl(a));return Ue(a,"fullscreenchange").pipe(Vt(()=>nl(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ue(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as Ot}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Ot.Q_144P;case"lowest":return Ot.Q_240P;case"low":return Ot.Q_360P;case"sd":case"medium":return Ot.Q_480P;case"hd":case"high":return Ot.Q_720P;case"fullhd":case"full":return Ot.Q_1080P;case"quadhd":case"quad":return Ot.Q_1440P;case"ultrahd":case"ultra":return Ot.Q_2160P}};var Nt=O(ti(),1),qg=O(Xe(),1),an=O(Ur(),1);import{isNonNullable as oe,isNullable as ul,now as Ug,isHigher as ll,isHigherOrEqual as cl,isInvariantQuality as _g,isLower as Ng,isLowerOrEqual as dl,videoSizeToQuality as P$,assertNotEmptyArray as Hg,assertNonNullable as w$}from"@vkontakte/videoplayer-shared/es2015";var ol=!1,bt={},Bg=a=>{ol=a},Vg=()=>{bt={}},Og=a=>{a(bt)},Wi=(a,e)=>{var t;ol&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var r,i;if(!ol)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};var A$=new ve("best_bitrate"),jg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var pl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Yi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ug()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Gg='Assertion "ABR Tracks is empty array" failed',sn=(a,e,t,r)=>{var u;let i=[...e].sort(pl(1)),s=[...t].sort(pl(1)),n=s.filter(l=>oe(l.bitrate)&&oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,qg.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},Fg=a=>"quality"in a,Qg=(a,e,t,r)=>{var n;let i=oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Ug()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Fg(o)?"video":"audio",l=Fg(o)?o.quality:o.bitrate;return e({message:`
6
+ var aI=Object.create;var oo=Object.defineProperty,sI=Object.defineProperties,nI=Object.getOwnPropertyDescriptor,oI=Object.getOwnPropertyDescriptors,uI=Object.getOwnPropertyNames,gs=Object.getOwnPropertySymbols,lI=Object.getPrototypeOf,uo=Object.prototype.hasOwnProperty,ld=Object.prototype.propertyIsEnumerable;var cI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,ud=(a,e,t)=>e in a?oo(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,I=(a,e)=>{for(var t in e||(e={}))uo.call(e,t)&&ud(a,t,e[t]);if(gs)for(var t of gs(e))ld.call(e,t)&&ud(a,t,e[t]);return a},R=(a,e)=>sI(a,oI(e));var cd=(a,e)=>{var t={};for(var r in a)uo.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&gs)for(var r of gs(a))e.indexOf(r)<0&&ld.call(a,r)&&(t[r]=a[r]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var dI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of uI(e))!uo.call(a,i)&&i!==t&&oo(a,i,{get:()=>e[i],enumerable:!(r=nI(e,i))||r.enumerable});return a};var V=(a,e,t)=>(t=a!=null?aI(lI(a)):{},dI(e||!a||!a.__esModule?oo(t,"default",{value:a,enumerable:!0}):t,a));var A=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),vs=function(a,e){this[0]=a,this[1]=e},ae=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof vs,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[cI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var re=f((po,pd)=>{"use strict";var Ti=function(a){return a&&a.Math===Math&&a};pd.exports=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof global=="object"&&global)||Ti(typeof po=="object"&&po)||function(){return this}()||Function("return this")()});var ce=f((qC,hd)=>{"use strict";hd.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ii=f((UC,md)=>{"use strict";var pI=ce();md.exports=!pI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ho=f((HC,vd)=>{"use strict";var hI=Ii(),gd=Function.prototype,fd=gd.apply,bd=gd.call;vd.exports=typeof Reflect=="object"&&Reflect.apply||(hI?bd.bind(fd):function(){return bd.apply(fd,arguments)})});var ne=f((jC,Td)=>{"use strict";var Sd=Ii(),yd=Function.prototype,mo=yd.call,mI=Sd&&yd.bind.bind(mo,mo);Td.exports=Sd?mI:function(a){return function(){return mo.apply(a,arguments)}}});var ir=f((QC,Ed)=>{"use strict";var Id=ne(),fI=Id({}.toString),bI=Id("".slice);Ed.exports=function(a){return bI(fI(a),8,-1)}});var fo=f((GC,xd)=>{"use strict";var gI=ir(),vI=ne();xd.exports=function(a){if(gI(a)==="Function")return vI(a)}});var ee=f((WC,Pd)=>{"use strict";var bo=typeof document=="object"&&document.all;Pd.exports=typeof bo=="undefined"&&bo!==void 0?function(a){return typeof a=="function"||a===bo}:function(a){return typeof a=="function"}});var De=f((YC,wd)=>{"use strict";var SI=ce();wd.exports=!SI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ce=f((zC,Ad)=>{"use strict";var yI=Ii(),Ts=Function.prototype.call;Ad.exports=yI?Ts.bind(Ts):function(){return Ts.apply(Ts,arguments)}});var go=f(Rd=>{"use strict";var kd={}.propertyIsEnumerable,Ld=Object.getOwnPropertyDescriptor,TI=Ld&&!kd.call({1:2},1);Rd.f=TI?function(e){var t=Ld(this,e);return!!t&&t.enumerable}:kd});var Ei=f((XC,$d)=>{"use strict";$d.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Dd=f((JC,Md)=>{"use strict";var II=ne(),EI=ce(),xI=ir(),vo=Object,PI=II("".split);Md.exports=EI(function(){return!vo("z").propertyIsEnumerable(0)})?function(a){return xI(a)==="String"?PI(a,""):vo(a)}:vo});var Dr=f((ZC,Cd)=>{"use strict";Cd.exports=function(a){return a==null}});var $t=f((eV,Vd)=>{"use strict";var wI=Dr(),AI=TypeError;Vd.exports=function(a){if(wI(a))throw new AI("Can't call method on "+a);return a}});var ar=f((tV,Bd)=>{"use strict";var kI=Dd(),LI=$t();Bd.exports=function(a){return kI(LI(a))}});var Ve=f((rV,Od)=>{"use strict";var RI=ee();Od.exports=function(a){return typeof a=="object"?a!==null:RI(a)}});var Cr=f((iV,_d)=>{"use strict";_d.exports={}});var pt=f((aV,Fd)=>{"use strict";var So=Cr(),yo=re(),$I=ee(),Nd=function(a){return $I(a)?a:void 0};Fd.exports=function(a,e){return arguments.length<2?Nd(So[a])||Nd(yo[a]):So[a]&&So[a][e]||yo[a]&&yo[a][e]}});var xi=f((sV,qd)=>{"use strict";var MI=ne();qd.exports=MI({}.isPrototypeOf)});var sr=f((nV,jd)=>{"use strict";var DI=re(),Ud=DI.navigator,Hd=Ud&&Ud.userAgent;jd.exports=Hd?String(Hd):""});var Io=f((oV,Kd)=>{"use strict";var zd=re(),To=sr(),Qd=zd.process,Gd=zd.Deno,Wd=Qd&&Qd.versions||Gd&&Gd.version,Yd=Wd&&Wd.v8,Ye,Is;Yd&&(Ye=Yd.split("."),Is=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!Is&&To&&(Ye=To.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=To.match(/Chrome\/(\d+)/),Ye&&(Is=+Ye[1])));Kd.exports=Is});var Eo=f((uV,Jd)=>{"use strict";var Xd=Io(),CI=ce(),VI=re(),BI=VI.String;Jd.exports=!!Object.getOwnPropertySymbols&&!CI(function(){var a=Symbol("symbol detection");return!BI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Xd&&Xd<41})});var xo=f((lV,Zd)=>{"use strict";var OI=Eo();Zd.exports=OI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Po=f((cV,ep)=>{"use strict";var _I=pt(),NI=ee(),FI=xi(),qI=xo(),UI=Object;ep.exports=qI?function(a){return typeof a=="symbol"}:function(a){var e=_I("Symbol");return NI(e)&&FI(e.prototype,UI(a))}});var Pi=f((dV,tp)=>{"use strict";var HI=String;tp.exports=function(a){try{return HI(a)}catch(e){return"Object"}}});var st=f((pV,rp)=>{"use strict";var jI=ee(),QI=Pi(),GI=TypeError;rp.exports=function(a){if(jI(a))return a;throw new GI(QI(a)+" is not a function")}});var wi=f((hV,ip)=>{"use strict";var WI=st(),YI=Dr();ip.exports=function(a,e){var t=a[e];return YI(t)?void 0:WI(t)}});var sp=f((mV,ap)=>{"use strict";var wo=Ce(),Ao=ee(),ko=Ve(),zI=TypeError;ap.exports=function(a,e){var t,r;if(e==="string"&&Ao(t=a.toString)&&!ko(r=wo(t,a))||Ao(t=a.valueOf)&&!ko(r=wo(t,a))||e!=="string"&&Ao(t=a.toString)&&!ko(r=wo(t,a)))return r;throw new zI("Can't convert object to primitive value")}});var ze=f((fV,np)=>{"use strict";np.exports=!0});var lp=f((bV,up)=>{"use strict";var op=re(),KI=Object.defineProperty;up.exports=function(a,e){try{KI(op,a,{value:e,configurable:!0,writable:!0})}catch(t){op[a]=e}return e}});var Ai=f((gV,pp)=>{"use strict";var XI=ze(),JI=re(),ZI=lp(),cp="__core-js_shared__",dp=pp.exports=JI[cp]||ZI(cp,{});(dp.versions||(dp.versions=[])).push({version:"3.38.0",mode:XI?"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 Lo=f((vV,mp)=>{"use strict";var hp=Ai();mp.exports=function(a,e){return hp[a]||(hp[a]=e||{})}});var Vr=f((SV,fp)=>{"use strict";var eE=$t(),tE=Object;fp.exports=function(a){return tE(eE(a))}});var Ke=f((yV,bp)=>{"use strict";var rE=ne(),iE=Vr(),aE=rE({}.hasOwnProperty);bp.exports=Object.hasOwn||function(e,t){return aE(iE(e),t)}});var Ro=f((TV,gp)=>{"use strict";var sE=ne(),nE=0,oE=Math.random(),uE=sE(1 .toString);gp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+uE(++nE+oE,36)}});var de=f((IV,Sp)=>{"use strict";var lE=re(),cE=Lo(),vp=Ke(),dE=Ro(),pE=Eo(),hE=xo(),Br=lE.Symbol,$o=cE("wks"),mE=hE?Br.for||Br:Br&&Br.withoutSetter||dE;Sp.exports=function(a){return vp($o,a)||($o[a]=pE&&vp(Br,a)?Br[a]:mE("Symbol."+a)),$o[a]}});var Ep=f((EV,Ip)=>{"use strict";var fE=Ce(),yp=Ve(),Tp=Po(),bE=wi(),gE=sp(),vE=de(),SE=TypeError,yE=vE("toPrimitive");Ip.exports=function(a,e){if(!yp(a)||Tp(a))return a;var t=bE(a,yE),r;if(t){if(e===void 0&&(e="default"),r=fE(t,a,e),!yp(r)||Tp(r))return r;throw new SE("Can't convert object to primitive value")}return e===void 0&&(e="number"),gE(a,e)}});var Mo=f((xV,xp)=>{"use strict";var TE=Ep(),IE=Po();xp.exports=function(a){var e=TE(a,"string");return IE(e)?e:e+""}});var Es=f((PV,wp)=>{"use strict";var EE=re(),Pp=Ve(),Do=EE.document,xE=Pp(Do)&&Pp(Do.createElement);wp.exports=function(a){return xE?Do.createElement(a):{}}});var Co=f((wV,Ap)=>{"use strict";var PE=De(),wE=ce(),AE=Es();Ap.exports=!PE&&!wE(function(){return Object.defineProperty(AE("div"),"a",{get:function(){return 7}}).a!==7})});var Rp=f(Lp=>{"use strict";var kE=De(),LE=Ce(),RE=go(),$E=Ei(),ME=ar(),DE=Mo(),CE=Ke(),VE=Co(),kp=Object.getOwnPropertyDescriptor;Lp.f=kE?kp:function(e,t){if(e=ME(e),t=DE(t),VE)try{return kp(e,t)}catch(r){}if(CE(e,t))return $E(!LE(RE.f,e,t),e[t])}});var Vo=f((kV,$p)=>{"use strict";var BE=ce(),OE=ee(),_E=/#|\.prototype\./,ki=function(a,e){var t=FE[NE(a)];return t===UE?!0:t===qE?!1:OE(e)?BE(e):!!e},NE=ki.normalize=function(a){return String(a).replace(_E,".").toLowerCase()},FE=ki.data={},qE=ki.NATIVE="N",UE=ki.POLYFILL="P";$p.exports=ki});var Or=f((LV,Dp)=>{"use strict";var Mp=fo(),HE=st(),jE=Ii(),QE=Mp(Mp.bind);Dp.exports=function(a,e){return HE(a),e===void 0?a:jE?QE(a,e):function(){return a.apply(e,arguments)}}});var Bo=f((RV,Cp)=>{"use strict";var GE=De(),WE=ce();Cp.exports=GE&&WE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=f(($V,Vp)=>{"use strict";var YE=Ve(),zE=String,KE=TypeError;Vp.exports=function(a){if(YE(a))return a;throw new KE(zE(a)+" is not an object")}});var nr=f(Op=>{"use strict";var XE=De(),JE=Co(),ZE=Bo(),xs=nt(),Bp=Mo(),ex=TypeError,Oo=Object.defineProperty,tx=Object.getOwnPropertyDescriptor,_o="enumerable",No="configurable",Fo="writable";Op.f=XE?ZE?function(e,t,r){if(xs(e),t=Bp(t),xs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Fo in r&&!r[Fo]){var i=tx(e,t);i&&i[Fo]&&(e[t]=r.value,r={configurable:No in r?r[No]:i[No],enumerable:_o in r?r[_o]:i[_o],writable:!1})}return Oo(e,t,r)}:Oo:function(e,t,r){if(xs(e),t=Bp(t),xs(r),JE)try{return Oo(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new ex("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=f((DV,_p)=>{"use strict";var rx=De(),ix=nr(),ax=Ei();_p.exports=rx?function(a,e,t){return ix.f(a,e,ax(1,t))}:function(a,e,t){return a[e]=t,a}});var se=f((CV,Fp)=>{"use strict";var Li=re(),sx=ho(),nx=fo(),ox=ee(),ux=Rp().f,lx=Vo(),Nr=Cr(),cx=Or(),Fr=_r(),Np=Ke();Ai();var dx=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return sx(a,this,arguments)};return e.prototype=a.prototype,e};Fp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Li:i?Li[t]:Li[t]&&Li[t].prototype,o=r?Nr:Nr[t]||Fr(Nr,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=lx(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Np(n,p),m=o[p],c&&(a.dontCallGetSet?(v=ux(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?g=cx(h,Li):a.wrap&&c?g=dx(h):s&&ox(h)?g=nx(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Fr(g,"sham",!0),Fr(o,p,g),s&&(d=t+"Prototype",Np(Nr,d)||Fr(Nr,d,{}),Fr(Nr[d],p,h),a.real&&u&&(l||!u[p])&&Fr(u,p,h)))}});var Up=f((VV,qp)=>{"use strict";var px=Math.ceil,hx=Math.floor;qp.exports=Math.trunc||function(e){var t=+e;return(t>0?hx:px)(t)}});var Ri=f((BV,Hp)=>{"use strict";var mx=Up();Hp.exports=function(a){var e=+a;return e!==e||e===0?0:mx(e)}});var Qp=f((OV,jp)=>{"use strict";var fx=Ri(),bx=Math.max,gx=Math.min;jp.exports=function(a,e){var t=fx(a);return t<0?bx(t+e,0):gx(t,e)}});var qo=f((_V,Gp)=>{"use strict";var vx=Ri(),Sx=Math.min;Gp.exports=function(a){var e=vx(a);return e>0?Sx(e,9007199254740991):0}});var qr=f((NV,Wp)=>{"use strict";var yx=qo();Wp.exports=function(a){return yx(a.length)}});var Uo=f((FV,zp)=>{"use strict";var Tx=ar(),Ix=Qp(),Ex=qr(),Yp=function(a){return function(e,t,r){var i=Tx(e),s=Ex(i);if(s===0)return!a&&-1;var n=Ix(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};zp.exports={includes:Yp(!0),indexOf:Yp(!1)}});var $i=f((qV,Kp)=>{"use strict";Kp.exports=function(){}});var Xp=f(()=>{"use strict";var xx=se(),Px=Uo().includes,wx=ce(),Ax=$i(),kx=wx(function(){return!Array(1).includes()});xx({target:"Array",proto:!0,forced:kx},{includes:function(e){return Px(this,e,arguments.length>1?arguments[1]:void 0)}});Ax("includes")});var Mt=f((jV,Jp)=>{"use strict";var Lx=pt();Jp.exports=Lx});var eh=f((QV,Zp)=>{"use strict";Xp();var Rx=Mt();Zp.exports=Rx("Array","includes")});var rh=f((GV,th)=>{"use strict";var $x=eh();th.exports=$x});var Xe=f((WV,ih)=>{"use strict";var Mx=rh();ih.exports=Mx});var As=f((sB,dh)=>{"use strict";var Fx=Lo(),qx=Ro(),ch=Fx("keys");dh.exports=function(a){return ch[a]||(ch[a]=qx(a))}});var hh=f((nB,ph)=>{"use strict";var Ux=ce();ph.exports=!Ux(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ks=f((oB,fh)=>{"use strict";var Hx=Ke(),jx=ee(),Qx=Vr(),Gx=As(),Wx=hh(),mh=Gx("IE_PROTO"),Qo=Object,Yx=Qo.prototype;fh.exports=Wx?Qo.getPrototypeOf:function(a){var e=Qx(a);if(Hx(e,mh))return e[mh];var t=e.constructor;return jx(t)&&e instanceof t?t.prototype:e instanceof Qo?Yx:null}});var Ls=f((uB,bh)=>{"use strict";bh.exports={}});var Sh=f((lB,vh)=>{"use strict";var zx=ne(),Go=Ke(),Kx=ar(),Xx=Uo().indexOf,Jx=Ls(),gh=zx([].push);vh.exports=function(a,e){var t=Kx(a),r=0,i=[],s;for(s in t)!Go(Jx,s)&&Go(t,s)&&gh(i,s);for(;e.length>r;)Go(t,s=e[r++])&&(~Xx(i,s)||gh(i,s));return i}});var Wo=f((cB,yh)=>{"use strict";yh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Yo=f((dB,Th)=>{"use strict";var Zx=Sh(),eP=Wo();Th.exports=Object.keys||function(e){return Zx(e,eP)}});var zo=f((pB,wh)=>{"use strict";var Eh=De(),tP=ce(),xh=ne(),rP=ks(),iP=Yo(),aP=ar(),sP=go().f,Ph=xh(sP),nP=xh([].push),oP=Eh&&tP(function(){var a=Object.create(null);return a[2]=2,!Ph(a,2)}),Ih=function(a){return function(e){for(var t=aP(e),r=iP(t),i=oP&&rP(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Eh||(i?u in t:Ph(t,u)))&&nP(o,a?[u,t[u]]:t[u]);return o}};wh.exports={entries:Ih(!0),values:Ih(!1)}});var Ah=f(()=>{"use strict";var uP=se(),lP=zo().entries;uP({target:"Object",stat:!0},{entries:function(e){return lP(e)}})});var Lh=f((fB,kh)=>{"use strict";Ah();var cP=Cr();kh.exports=cP.Object.entries});var $h=f((bB,Rh)=>{"use strict";var dP=Lh();Rh.exports=dP});var Ur=f((gB,Mh)=>{"use strict";var pP=$h();Mh.exports=pP});var or=f((vB,Dh)=>{"use strict";Dh.exports={}});var Bh=f((SB,Vh)=>{"use strict";var hP=re(),mP=ee(),Ch=hP.WeakMap;Vh.exports=mP(Ch)&&/native code/.test(String(Ch))});var Zo=f((yB,Nh)=>{"use strict";var fP=Bh(),_h=re(),bP=Ve(),gP=_r(),Ko=Ke(),Xo=Ai(),vP=As(),SP=Ls(),Oh="Object already initialized",Jo=_h.TypeError,yP=_h.WeakMap,Rs,Mi,$s,TP=function(a){return $s(a)?Mi(a):Rs(a,{})},IP=function(a){return function(e){var t;if(!bP(e)||(t=Mi(e)).type!==a)throw new Jo("Incompatible receiver, "+a+" required");return t}};fP||Xo.state?(Je=Xo.state||(Xo.state=new yP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,Rs=function(a,e){if(Je.has(a))throw new Jo(Oh);return e.facade=a,Je.set(a,e),e},Mi=function(a){return Je.get(a)||{}},$s=function(a){return Je.has(a)}):(ur=vP("state"),SP[ur]=!0,Rs=function(a,e){if(Ko(a,ur))throw new Jo(Oh);return e.facade=a,gP(a,ur,e),e},Mi=function(a){return Ko(a,ur)?a[ur]:{}},$s=function(a){return Ko(a,ur)});var Je,ur;Nh.exports={set:Rs,get:Mi,has:$s,enforce:TP,getterFor:IP}});var ru=f((TB,qh)=>{"use strict";var eu=De(),EP=Ke(),Fh=Function.prototype,xP=eu&&Object.getOwnPropertyDescriptor,tu=EP(Fh,"name"),PP=tu&&function(){}.name==="something",wP=tu&&(!eu||eu&&xP(Fh,"name").configurable);qh.exports={EXISTS:tu,PROPER:PP,CONFIGURABLE:wP}});var Hh=f(Uh=>{"use strict";var AP=De(),kP=Bo(),LP=nr(),RP=nt(),$P=ar(),MP=Yo();Uh.f=AP&&!kP?Object.defineProperties:function(e,t){RP(e);for(var r=$P(t),i=MP(t),s=i.length,n=0,o;s>n;)LP.f(e,o=i[n++],r[o]);return e}});var iu=f((EB,jh)=>{"use strict";var DP=pt();jh.exports=DP("document","documentElement")});var ou=f((xB,Xh)=>{"use strict";var CP=nt(),VP=Hh(),Qh=Wo(),BP=Ls(),OP=iu(),_P=Es(),NP=As(),Gh=">",Wh="<",su="prototype",nu="script",zh=NP("IE_PROTO"),au=function(){},Kh=function(a){return Wh+nu+Gh+a+Wh+"/"+nu+Gh},Yh=function(a){a.write(Kh("")),a.close();var e=a.parentWindow.Object;return a=null,e},FP=function(){var a=_P("iframe"),e="java"+nu+":",t;return a.style.display="none",OP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Kh("document.F=Object")),t.close(),t.F},Ms,Ds=function(){try{Ms=new ActiveXObject("htmlfile")}catch(e){}Ds=typeof document!="undefined"?document.domain&&Ms?Yh(Ms):FP():Yh(Ms);for(var a=Qh.length;a--;)delete Ds[su][Qh[a]];return Ds()};BP[zh]=!0;Xh.exports=Object.create||function(e,t){var r;return e!==null?(au[su]=CP(e),r=new au,au[su]=null,r[zh]=e):r=Ds(),t===void 0?r:VP.f(r,t)}});var Hr=f((PB,Jh)=>{"use strict";var qP=_r();Jh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:qP(a,e,t),a}});var du=f((wB,tm)=>{"use strict";var UP=ce(),HP=ee(),jP=Ve(),QP=ou(),Zh=ks(),GP=Hr(),WP=de(),YP=ze(),cu=WP("iterator"),em=!1,ht,uu,lu;[].keys&&(lu=[].keys(),"next"in lu?(uu=Zh(Zh(lu)),uu!==Object.prototype&&(ht=uu)):em=!0);var zP=!jP(ht)||UP(function(){var a={};return ht[cu].call(a)!==a});zP?ht={}:YP&&(ht=QP(ht));HP(ht[cu])||GP(ht,cu,function(){return this});tm.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:em}});var Cs=f((AB,im)=>{"use strict";var KP=de(),XP=KP("toStringTag"),rm={};rm[XP]="z";im.exports=String(rm)==="[object z]"});var Di=f((kB,am)=>{"use strict";var JP=Cs(),ZP=ee(),Vs=ir(),ew=de(),tw=ew("toStringTag"),rw=Object,iw=Vs(function(){return arguments}())==="Arguments",aw=function(a,e){try{return a[e]}catch(t){}};am.exports=JP?Vs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=aw(e=rw(a),tw))=="string"?t:iw?Vs(e):(r=Vs(e))==="Object"&&ZP(e.callee)?"Arguments":r}});var nm=f((LB,sm)=>{"use strict";var sw=Cs(),nw=Di();sm.exports=sw?{}.toString:function(){return"[object "+nw(this)+"]"}});var Ci=f((RB,um)=>{"use strict";var ow=Cs(),uw=nr().f,lw=_r(),cw=Ke(),dw=nm(),pw=de(),om=pw("toStringTag");um.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(cw(i,om)||uw(i,om,{configurable:!0,value:e}),r&&!ow&&lw(i,"toString",dw))}});var cm=f(($B,lm)=>{"use strict";var hw=du().IteratorPrototype,mw=ou(),fw=Ei(),bw=Ci(),gw=or(),vw=function(){return this};lm.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=mw(hw,{next:fw(+!r,t)}),bw(a,i,!1,!0),gw[i]=vw,a}});var pm=f((MB,dm)=>{"use strict";var Sw=ne(),yw=st();dm.exports=function(a,e,t){try{return Sw(yw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var mm=f((DB,hm)=>{"use strict";var Tw=Ve();hm.exports=function(a){return Tw(a)||a===null}});var bm=f((CB,fm)=>{"use strict";var Iw=mm(),Ew=String,xw=TypeError;fm.exports=function(a){if(Iw(a))return a;throw new xw("Can't set "+Ew(a)+" as a prototype")}});var pu=f((VB,gm)=>{"use strict";var Pw=pm(),ww=Ve(),Aw=$t(),kw=bm();gm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Pw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return Aw(i),kw(s),ww(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var km=f((BB,Am)=>{"use strict";var Lw=se(),Rw=Ce(),Bs=ze(),Pm=ru(),$w=ee(),Mw=cm(),vm=ks(),Sm=pu(),Dw=Ci(),Cw=_r(),hu=Hr(),Vw=de(),ym=or(),wm=du(),Bw=Pm.PROPER,Ow=Pm.CONFIGURABLE,Tm=wm.IteratorPrototype,Os=wm.BUGGY_SAFARI_ITERATORS,Vi=Vw("iterator"),Im="keys",Bi="values",Em="entries",xm=function(){return this};Am.exports=function(a,e,t,r,i,s,n){Mw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Os&&v&&v in c)return c[v];switch(v){case Im:return function(){return new t(this,v)};case Bi:return function(){return new t(this,v)};case Em:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Vi]||c["@@iterator"]||i&&c[i],p=!Os&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=vm(h.call(new a)),m!==Object.prototype&&m.next&&(!Bs&&vm(m)!==Tm&&(Sm?Sm(m,Tm):$w(m[Vi])||hu(m,Vi,xm)),Dw(m,u,!0,!0),Bs&&(ym[u]=xm))),Bw&&i===Bi&&d&&d.name!==Bi&&(!Bs&&Ow?Cw(c,"name",Bi):(l=!0,p=function(){return Rw(d,this)})),i)if(b={values:o(Bi),keys:s?p:o(Im),entries:o(Em)},n)for(g in b)(Os||l||!(g in c))&&hu(c,g,b[g]);else Lw({target:e,proto:!0,forced:Os||l},b);return(!Bs||n)&&c[Vi]!==p&&hu(c,Vi,p,{name:i}),ym[e]=p,b}});var Rm=f((OB,Lm)=>{"use strict";Lm.exports=function(a,e){return{value:a,done:e}}});var fu=f((_B,Vm)=>{"use strict";var _w=ar(),mu=$i(),$m=or(),Dm=Zo(),Nw=nr().f,Fw=km(),_s=Rm(),qw=ze(),Uw=De(),Cm="Array Iterator",Hw=Dm.set,jw=Dm.getterFor(Cm);Vm.exports=Fw(Array,"Array",function(a,e){Hw(this,{type:Cm,target:_w(a),index:0,kind:e})},function(){var a=jw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,_s(void 0,!0);switch(a.kind){case"keys":return _s(t,!1);case"values":return _s(e[t],!1)}return _s([t,e[t]],!1)},"values");var Mm=$m.Arguments=$m.Array;mu("keys");mu("values");mu("entries");if(!qw&&Uw&&Mm.name!=="values")try{Nw(Mm,"name",{value:"values"})}catch(a){}});var Om=f((NB,Bm)=>{"use strict";var Qw=de(),Gw=or(),Ww=Qw("iterator"),Yw=Array.prototype;Bm.exports=function(a){return a!==void 0&&(Gw.Array===a||Yw[Ww]===a)}});var bu=f((FB,Nm)=>{"use strict";var zw=Di(),_m=wi(),Kw=Dr(),Xw=or(),Jw=de(),Zw=Jw("iterator");Nm.exports=function(a){if(!Kw(a))return _m(a,Zw)||_m(a,"@@iterator")||Xw[zw(a)]}});var qm=f((qB,Fm)=>{"use strict";var eA=Ce(),tA=st(),rA=nt(),iA=Pi(),aA=bu(),sA=TypeError;Fm.exports=function(a,e){var t=arguments.length<2?aA(a):e;if(tA(t))return rA(eA(t,a));throw new sA(iA(a)+" is not iterable")}});var jm=f((UB,Hm)=>{"use strict";var nA=Ce(),Um=nt(),oA=wi();Hm.exports=function(a,e,t){var r,i;Um(a);try{if(r=oA(a,"return"),!r){if(e==="throw")throw t;return t}r=nA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Um(r),t}});var Fs=f((HB,Ym)=>{"use strict";var uA=Or(),lA=Ce(),cA=nt(),dA=Pi(),pA=Om(),hA=qr(),Qm=xi(),mA=qm(),fA=bu(),Gm=jm(),bA=TypeError,Ns=function(a,e){this.stopped=a,this.result=e},Wm=Ns.prototype;Ym.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=uA(e,r),l,c,d,p,h,m,b,g=function(S){return l&&Gm(l,"normal",S),new Ns(!0,S)},v=function(S){return i?(cA(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=fA(a),!c)throw new bA(dA(a)+" is not iterable");if(pA(c)){for(d=0,p=hA(a);p>d;d++)if(h=v(a[d]),h&&Qm(Wm,h))return h;return new Ns(!1)}l=mA(a,c)}for(m=s?a.next:l.next;!(b=lA(m,l)).done;){try{h=v(b.value)}catch(S){Gm(l,"throw",S)}if(typeof h=="object"&&h&&Qm(Wm,h))return h}return new Ns(!1)}});var Km=f((jB,zm)=>{"use strict";var gA=De(),vA=nr(),SA=Ei();zm.exports=function(a,e,t){gA?vA.f(a,e,SA(0,t)):a[e]=t}});var Xm=f(()=>{"use strict";var yA=se(),TA=Fs(),IA=Km();yA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return TA(e,function(r,i){IA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Zm=f((WB,Jm)=>{"use strict";fu();Xm();var EA=Cr();Jm.exports=EA.Object.fromEntries});var tf=f((YB,ef)=>{"use strict";ef.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 af=f(()=>{"use strict";fu();var xA=tf(),PA=re(),wA=Ci(),rf=or();for(qs in xA)wA(PA[qs],qs),rf[qs]=rf.Array;var qs});var nf=f((XB,sf)=>{"use strict";var AA=Zm();af();sf.exports=AA});var gu=f((JB,of)=>{"use strict";var kA=nf();of.exports=kA});var uf=f(()=>{"use strict"});var vu=f((tO,lf)=>{"use strict";var Oi=re(),LA=sr(),RA=ir(),Us=function(a){return LA.slice(0,a.length)===a};lf.exports=function(){return Us("Bun/")?"BUN":Us("Cloudflare-Workers")?"CLOUDFLARE":Us("Deno/")?"DENO":Us("Node.js/")?"NODE":Oi.Bun&&typeof Bun.version=="string"?"BUN":Oi.Deno&&typeof Deno.version=="object"?"DENO":RA(Oi.process)==="process"?"NODE":Oi.window&&Oi.document?"BROWSER":"REST"}()});var Hs=f((rO,cf)=>{"use strict";var $A=vu();cf.exports=$A==="NODE"});var pf=f((iO,df)=>{"use strict";var MA=nr();df.exports=function(a,e,t){return MA.f(a,e,t)}});var ff=f((aO,mf)=>{"use strict";var DA=pt(),CA=pf(),VA=de(),BA=De(),hf=VA("species");mf.exports=function(a){var e=DA(a);BA&&e&&!e[hf]&&CA(e,hf,{configurable:!0,get:function(){return this}})}});var gf=f((sO,bf)=>{"use strict";var OA=xi(),_A=TypeError;bf.exports=function(a,e){if(OA(e,a))return a;throw new _A("Incorrect invocation")}});var yu=f((nO,vf)=>{"use strict";var NA=ne(),FA=ee(),Su=Ai(),qA=NA(Function.toString);FA(Su.inspectSource)||(Su.inspectSource=function(a){return qA(a)});vf.exports=Su.inspectSource});var Iu=f((oO,Ef)=>{"use strict";var UA=ne(),HA=ce(),Sf=ee(),jA=Di(),QA=pt(),GA=yu(),yf=function(){},Tf=QA("Reflect","construct"),Tu=/^\s*(?:class|function)\b/,WA=UA(Tu.exec),YA=!Tu.test(yf),_i=function(e){if(!Sf(e))return!1;try{return Tf(yf,[],e),!0}catch(t){return!1}},If=function(e){if(!Sf(e))return!1;switch(jA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return YA||!!WA(Tu,GA(e))}catch(t){return!0}};If.sham=!0;Ef.exports=!Tf||HA(function(){var a;return _i(_i.call)||!_i(Object)||!_i(function(){a=!0})||a})?If:_i});var Pf=f((uO,xf)=>{"use strict";var zA=Iu(),KA=Pi(),XA=TypeError;xf.exports=function(a){if(zA(a))return a;throw new XA(KA(a)+" is not a constructor")}});var Eu=f((lO,Af)=>{"use strict";var wf=nt(),JA=Pf(),ZA=Dr(),ek=de(),tk=ek("species");Af.exports=function(a,e){var t=wf(a).constructor,r;return t===void 0||ZA(r=wf(t)[tk])?e:JA(r)}});var Lf=f((cO,kf)=>{"use strict";var rk=ne();kf.exports=rk([].slice)});var $f=f((dO,Rf)=>{"use strict";var ik=TypeError;Rf.exports=function(a,e){if(a<e)throw new ik("Not enough arguments");return a}});var xu=f((pO,Mf)=>{"use strict";var ak=sr();Mf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ak)});var Du=f((hO,qf)=>{"use strict";var Be=re(),sk=ho(),nk=Or(),Df=ee(),ok=Ke(),Ff=ce(),Cf=iu(),uk=Lf(),Vf=Es(),lk=$f(),ck=xu(),dk=Hs(),Ru=Be.setImmediate,$u=Be.clearImmediate,pk=Be.process,Pu=Be.Dispatch,hk=Be.Function,Bf=Be.MessageChannel,mk=Be.String,wu=0,Ni={},Of="onreadystatechange",Fi,lr,Au,ku;Ff(function(){Fi=Be.location});var Mu=function(a){if(ok(Ni,a)){var e=Ni[a];delete Ni[a],e()}},Lu=function(a){return function(){Mu(a)}},_f=function(a){Mu(a.data)},Nf=function(a){Be.postMessage(mk(a),Fi.protocol+"//"+Fi.host)};(!Ru||!$u)&&(Ru=function(e){lk(arguments.length,1);var t=Df(e)?e:hk(e),r=uk(arguments,1);return Ni[++wu]=function(){sk(t,void 0,r)},lr(wu),wu},$u=function(e){delete Ni[e]},dk?lr=function(a){pk.nextTick(Lu(a))}:Pu&&Pu.now?lr=function(a){Pu.now(Lu(a))}:Bf&&!ck?(Au=new Bf,ku=Au.port2,Au.port1.onmessage=_f,lr=nk(ku.postMessage,ku)):Be.addEventListener&&Df(Be.postMessage)&&!Be.importScripts&&Fi&&Fi.protocol!=="file:"&&!Ff(Nf)?(lr=Nf,Be.addEventListener("message",_f,!1)):Of in Vf("script")?lr=function(a){Cf.appendChild(Vf("script"))[Of]=function(){Cf.removeChild(this),Mu(a)}}:lr=function(a){setTimeout(Lu(a),0)});qf.exports={set:Ru,clear:$u}});var jf=f((mO,Hf)=>{"use strict";var Uf=re(),fk=De(),bk=Object.getOwnPropertyDescriptor;Hf.exports=function(a){if(!fk)return Uf[a];var e=bk(Uf,a);return e&&e.value}});var Cu=f((fO,Gf)=>{"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}}};Gf.exports=Qf});var Yf=f((bO,Wf)=>{"use strict";var gk=sr();Wf.exports=/ipad|iphone|ipod/i.test(gk)&&typeof Pebble!="undefined"});var Kf=f((gO,zf)=>{"use strict";var vk=sr();zf.exports=/web0s(?!.*chrome)/i.test(vk)});var ib=f((vO,rb)=>{"use strict";var Qr=re(),Sk=jf(),Xf=Or(),Vu=Du().set,yk=Cu(),Tk=xu(),Ik=Yf(),Ek=Kf(),Bu=Hs(),Jf=Qr.MutationObserver||Qr.WebKitMutationObserver,Zf=Qr.document,eb=Qr.process,js=Qr.Promise,Nu=Sk("queueMicrotask"),jr,Ou,_u,Qs,tb;Nu||(qi=new yk,Ui=function(){var a,e;for(Bu&&(a=eb.domain)&&a.exit();e=qi.get();)try{e()}catch(t){throw qi.head&&jr(),t}a&&a.enter()},!Tk&&!Bu&&!Ek&&Jf&&Zf?(Ou=!0,_u=Zf.createTextNode(""),new Jf(Ui).observe(_u,{characterData:!0}),jr=function(){_u.data=Ou=!Ou}):!Ik&&js&&js.resolve?(Qs=js.resolve(void 0),Qs.constructor=js,tb=Xf(Qs.then,Qs),jr=function(){tb(Ui)}):Bu?jr=function(){eb.nextTick(Ui)}:(Vu=Xf(Vu,Qr),jr=function(){Vu(Ui)}),Nu=function(a){qi.head||jr(),qi.add(a)});var qi,Ui;rb.exports=Nu});var sb=f((SO,ab)=>{"use strict";ab.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Gs=f((yO,nb)=>{"use strict";nb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var cr=f((TO,ob)=>{"use strict";var xk=re();ob.exports=xk.Promise});var Gr=f((IO,db)=>{"use strict";var Pk=re(),Hi=cr(),wk=ee(),Ak=Vo(),kk=yu(),Lk=de(),ub=vu(),Rk=ze(),Fu=Io(),lb=Hi&&Hi.prototype,$k=Lk("species"),qu=!1,cb=wk(Pk.PromiseRejectionEvent),Mk=Ak("Promise",function(){var a=kk(Hi),e=a!==String(Hi);if(!e&&Fu===66||Rk&&!(lb.catch&&lb.finally))return!0;if(!Fu||Fu<51||!/native code/.test(a)){var t=new Hi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[$k]=r,qu=t.then(function(){})instanceof r,!qu)return!0}return!e&&(ub==="BROWSER"||ub==="DENO")&&!cb});db.exports={CONSTRUCTOR:Mk,REJECTION_EVENT:cb,SUBCLASSING:qu}});var Wr=f((EO,hb)=>{"use strict";var pb=st(),Dk=TypeError,Ck=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Dk("Bad Promise constructor");e=r,t=i}),this.resolve=pb(e),this.reject=pb(t)};hb.exports.f=function(a){return new Ck(a)}});var Mb=f(()=>{"use strict";var Vk=se(),Bk=ze(),Ks=Hs(),Dt=re(),Xr=Ce(),mb=Hr(),fb=pu(),Ok=Ci(),_k=ff(),Nk=st(),zs=ee(),Fk=Ve(),qk=gf(),Uk=Eu(),yb=Du().set,Gu=ib(),Hk=sb(),jk=Gs(),Qk=Cu(),Tb=Zo(),Xs=cr(),Wu=Gr(),Ib=Wr(),Js="Promise",Eb=Wu.CONSTRUCTOR,Gk=Wu.REJECTION_EVENT,Wk=Wu.SUBCLASSING,Uu=Tb.getterFor(Js),Yk=Tb.set,Yr=Xs&&Xs.prototype,dr=Xs,Ws=Yr,xb=Dt.TypeError,Hu=Dt.document,Yu=Dt.process,ju=Ib.f,zk=ju,Kk=!!(Hu&&Hu.createEvent&&Dt.dispatchEvent),Pb="unhandledrejection",Xk="rejectionhandled",bb=0,wb=1,Jk=2,zu=1,Ab=2,Ys,gb,Zk,vb,kb=function(a){var e;return Fk(a)&&zs(e=a.then)?e:!1},Lb=function(a,e){var t=e.value,r=e.state===wb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Ab&&tL(e),e.rejection=zu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new xb("Promise-chain cycle")):(l=kb(u))?Xr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Rb=function(a,e){a.notified||(a.notified=!0,Gu(function(){for(var t=a.reactions,r;r=t.get();)Lb(r,a);a.notified=!1,e&&!a.rejection&&eL(a)}))},$b=function(a,e,t){var r,i;Kk?(r=Hu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Dt.dispatchEvent(r)):r={promise:e,reason:t},!Gk&&(i=Dt["on"+a])?i(r):a===Pb&&Hk("Unhandled promise rejection",t)},eL=function(a){Xr(yb,Dt,function(){var e=a.facade,t=a.value,r=Sb(a),i;if(r&&(i=jk(function(){Ks?Yu.emit("unhandledRejection",t,e):$b(Pb,e,t)}),a.rejection=Ks||Sb(a)?Ab:zu,i.error))throw i.value})},Sb=function(a){return a.rejection!==zu&&!a.parent},tL=function(a){Xr(yb,Dt,function(){var e=a.facade;Ks?Yu.emit("rejectionHandled",e):$b(Xk,e,a.value)})},zr=function(a,e,t){return function(r){a(e,r,t)}},Kr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Jk,Rb(a,!0))},Qu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new xb("Promise can't be resolved itself");var r=kb(e);r?Gu(function(){var i={done:!1};try{Xr(r,e,zr(Qu,i,a),zr(Kr,i,a))}catch(s){Kr(i,s,a)}}):(a.value=e,a.state=wb,Rb(a,!1))}catch(i){Kr({done:!1},i,a)}}};if(Eb&&(dr=function(e){qk(this,Ws),Nk(e),Xr(Ys,this);var t=Uu(this);try{e(zr(Qu,t),zr(Kr,t))}catch(r){Kr(t,r)}},Ws=dr.prototype,Ys=function(e){Yk(this,{type:Js,done:!1,notified:!1,parent:!1,reactions:new Qk,rejection:!1,state:bb,value:void 0})},Ys.prototype=mb(Ws,"then",function(e,t){var r=Uu(this),i=ju(Uk(this,dr));return r.parent=!0,i.ok=zs(e)?e:!0,i.fail=zs(t)&&t,i.domain=Ks?Yu.domain:void 0,r.state===bb?r.reactions.add(i):Gu(function(){Lb(i,r)}),i.promise}),gb=function(){var a=new Ys,e=Uu(a);this.promise=a,this.resolve=zr(Qu,e),this.reject=zr(Kr,e)},Ib.f=ju=function(a){return a===dr||a===Zk?new gb(a):zk(a)},!Bk&&zs(Xs)&&Yr!==Object.prototype)){vb=Yr.then,Wk||mb(Yr,"then",function(e,t){var r=this;return new dr(function(i,s){Xr(vb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Yr.constructor}catch(a){}fb&&fb(Yr,Ws)}Vk({global:!0,constructor:!0,wrap:!0,forced:Eb},{Promise:dr});Ok(dr,Js,!1,!0);_k(Js)});var Ob=f((wO,Bb)=>{"use strict";var rL=de(),Cb=rL("iterator"),Vb=!1;try{Db=0,Ku={next:function(){return{done:!!Db++}},return:function(){Vb=!0}},Ku[Cb]=function(){return this},Array.from(Ku,function(){throw 2})}catch(a){}var Db,Ku;Bb.exports=function(a,e){try{if(!e&&!Vb)return!1}catch(i){return!1}var t=!1;try{var r={};r[Cb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Xu=f((AO,_b)=>{"use strict";var iL=cr(),aL=Ob(),sL=Gr().CONSTRUCTOR;_b.exports=sL||!aL(function(a){iL.all(a).then(void 0,function(){})})});var Nb=f(()=>{"use strict";var nL=se(),oL=Ce(),uL=st(),lL=Wr(),cL=Gs(),dL=Fs(),pL=Xu();nL({target:"Promise",stat:!0,forced:pL},{all:function(e){var t=this,r=lL.f(t),i=r.resolve,s=r.reject,n=cL(function(){var o=uL(t.resolve),u=[],l=0,c=1;dL(e,function(d){var p=l++,h=!1;c++,oL(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var qb=f(()=>{"use strict";var hL=se(),mL=ze(),fL=Gr().CONSTRUCTOR,Zu=cr(),bL=pt(),gL=ee(),vL=Hr(),Fb=Zu&&Zu.prototype;hL({target:"Promise",proto:!0,forced:fL,real:!0},{catch:function(a){return this.then(void 0,a)}});!mL&&gL(Zu)&&(Ju=bL("Promise").prototype.catch,Fb.catch!==Ju&&vL(Fb,"catch",Ju,{unsafe:!0}));var Ju});var Ub=f(()=>{"use strict";var SL=se(),yL=Ce(),TL=st(),IL=Wr(),EL=Gs(),xL=Fs(),PL=Xu();SL({target:"Promise",stat:!0,forced:PL},{race:function(e){var t=this,r=IL.f(t),i=r.reject,s=EL(function(){var n=TL(t.resolve);xL(e,function(o){yL(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Hb=f(()=>{"use strict";var wL=se(),AL=Wr(),kL=Gr().CONSTRUCTOR;wL({target:"Promise",stat:!0,forced:kL},{reject:function(e){var t=AL.f(this),r=t.reject;return r(e),t.promise}})});var el=f((BO,jb)=>{"use strict";var LL=nt(),RL=Ve(),$L=Wr();jb.exports=function(a,e){if(LL(a),RL(e)&&e.constructor===a)return e;var t=$L.f(a),r=t.resolve;return r(e),t.promise}});var Wb=f(()=>{"use strict";var ML=se(),DL=pt(),Qb=ze(),CL=cr(),Gb=Gr().CONSTRUCTOR,VL=el(),BL=DL("Promise"),OL=Qb&&!Gb;ML({target:"Promise",stat:!0,forced:Qb||Gb},{resolve:function(e){return VL(OL&&this===BL?CL:this,e)}})});var Yb=f(()=>{"use strict";Mb();Nb();qb();Ub();Hb();Wb()});var Jb=f(()=>{"use strict";var _L=se(),NL=ze(),Zs=cr(),FL=ce(),Kb=pt(),Xb=ee(),qL=Eu(),zb=el(),UL=Hr(),rl=Zs&&Zs.prototype,HL=!!Zs&&FL(function(){rl.finally.call({then:function(){}},function(){})});_L({target:"Promise",proto:!0,real:!0,forced:HL},{finally:function(a){var e=qL(this,Kb("Promise")),t=Xb(a);return this.then(t?function(r){return zb(e,a()).then(function(){return r})}:a,t?function(r){return zb(e,a()).then(function(){throw r})}:a)}});!NL&&Xb(Zs)&&(tl=Kb("Promise").prototype.finally,rl.finally!==tl&&UL(rl,"finally",tl,{unsafe:!0}));var tl});var eg=f((HO,Zb)=>{"use strict";uf();Yb();Jb();var jL=Mt();Zb.exports=jL("Promise","finally")});var rg=f((jO,tg)=>{"use strict";var QL=eg();tg.exports=QL});var en=f((QO,ig)=>{"use strict";var GL=rg();ig.exports=GL});var bg=f(()=>{"use strict";var nR=se(),oR=zo().values;nR({target:"Object",stat:!0},{values:function(e){return oR(e)}})});var vg=f((L_,gg)=>{"use strict";bg();var uR=Cr();gg.exports=uR.Object.values});var yg=f((R_,Sg)=>{"use strict";var lR=vg();Sg.exports=lR});var Zr=f(($_,Tg)=>{"use strict";var cR=yg();Tg.exports=cR});var Cg=f(()=>{"use strict";var wR=se(),AR=Vr(),kR=qr(),LR=Ri(),RR=$i();wR({target:"Array",proto:!0},{at:function(e){var t=AR(this),r=kR(t),i=LR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});RR("at")});var Bg=f((sN,Vg)=>{"use strict";Cg();var $R=Mt();Vg.exports=$R("Array","at")});var _g=f((nN,Og)=>{"use strict";var MR=Bg();Og.exports=MR});var _t=f((oN,Ng)=>{"use strict";var DR=_g();Ng.exports=DR});var Pl=f((WF,yv)=>{"use strict";var b$=ir();yv.exports=Array.isArray||function(e){return b$(e)==="Array"}});var Iv=f((YF,Tv)=>{"use strict";var g$=TypeError,v$=9007199254740991;Tv.exports=function(a){if(a>v$)throw g$("Maximum allowed index exceeded");return a}});var Pv=f((zF,xv)=>{"use strict";var S$=Pl(),y$=qr(),T$=Iv(),I$=Or(),Ev=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?I$(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&S$(d)?(p=y$(d),u=Ev(a,e,d,p,u,s-1)-1):(T$(u+1),a[u]=d),u++),l++;return u};xv.exports=Ev});var Lv=f((KF,kv)=>{"use strict";var wv=Pl(),E$=Iu(),x$=Ve(),P$=de(),w$=P$("species"),Av=Array;kv.exports=function(a){var e;return wv(a)&&(e=a.constructor,E$(e)&&(e===Av||wv(e.prototype))?e=void 0:x$(e)&&(e=e[w$],e===null&&(e=void 0))),e===void 0?Av:e}});var $v=f((XF,Rv)=>{"use strict";var A$=Lv();Rv.exports=function(a,e){return new(A$(a))(e===0?0:e)}});var Mv=f(()=>{"use strict";var k$=se(),L$=Pv(),R$=st(),$$=Vr(),M$=qr(),D$=$v();k$({target:"Array",proto:!0},{flatMap:function(e){var t=$$(this),r=M$(t),i;return R$(e),i=D$(t,0),i.length=L$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Dv=f(()=>{"use strict";var C$=$i();C$("flatMap")});var Vv=f((rq,Cv)=>{"use strict";Mv();Dv();var V$=Mt();Cv.exports=V$("Array","flatMap")});var Ov=f((iq,Bv)=>{"use strict";var B$=Vv();Bv.exports=B$});var wl=f((aq,_v)=>{"use strict";var O$=Ov();_v.exports=O$});var sa=f((fq,aS)=>{"use strict";var Q$=Di(),G$=String;aS.exports=function(a){if(Q$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return G$(a)}});var kl=f((bq,sS)=>{"use strict";sS.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 uS=f((gq,oS)=>{"use strict";var W$=ne(),Y$=$t(),z$=sa(),Rl=kl(),nS=W$("".replace),K$=RegExp("^["+Rl+"]+"),X$=RegExp("(^|[^"+Rl+"])["+Rl+"]+$"),Ll=function(a){return function(e){var t=z$(Y$(e));return a&1&&(t=nS(t,K$,"")),a&2&&(t=nS(t,X$,"$1")),t}};oS.exports={start:Ll(1),end:Ll(2),trim:Ll(3)}});var pS=f((vq,dS)=>{"use strict";var J$=ru().PROPER,Z$=ce(),lS=kl(),cS="\u200B\x85\u180E";dS.exports=function(a){return Z$(function(){return!!lS[a]()||cS[a]()!==cS||J$&&lS[a].name!==a})}});var $l=f((Sq,hS)=>{"use strict";var eM=uS().start,tM=pS();hS.exports=tM("trimStart")?function(){return eM(this)}:"".trimStart});var fS=f(()=>{"use strict";var rM=se(),mS=$l();rM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==mS},{trimLeft:mS})});var gS=f(()=>{"use strict";fS();var iM=se(),bS=$l();iM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==bS},{trimStart:bS})});var SS=f((xq,vS)=>{"use strict";gS();var aM=Mt();vS.exports=aM("String","trimLeft")});var TS=f((Pq,yS)=>{"use strict";var sM=SS();yS.exports=sM});var ES=f((wq,IS)=>{"use strict";var nM=TS();IS.exports=nM});var NS=f(()=>{"use strict"});var FS=f(()=>{"use strict"});var US=f((uH,qS)=>{"use strict";var LM=Ve(),RM=ir(),$M=de(),MM=$M("match");qS.exports=function(a){var e;return LM(a)&&((e=a[MM])!==void 0?!!e:RM(a)==="RegExp")}});var jS=f((lH,HS)=>{"use strict";var DM=nt();HS.exports=function(){var a=DM(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 WS=f((cH,GS)=>{"use strict";var CM=Ce(),VM=Ke(),BM=xi(),OM=jS(),QS=RegExp.prototype;GS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in QS)&&!VM(a,"flags")&&BM(QS,a)?CM(OM,a):e}});var zS=f((dH,YS)=>{"use strict";var Fl=ne(),_M=Vr(),NM=Math.floor,_l=Fl("".charAt),FM=Fl("".replace),Nl=Fl("".slice),qM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,UM=/\$([$&'`]|\d{1,2})/g;YS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=UM;return i!==void 0&&(i=_M(i),u=qM),FM(s,u,function(l,c){var d;switch(_l(c,0)){case"$":return"$";case"&":return a;case"`":return Nl(e,0,t);case"'":return Nl(e,n);case"<":d=i[Nl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=NM(p/10);return h===0?l:h<=o?r[h-1]===void 0?_l(c,1):r[h-1]+_l(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var JS=f(()=>{"use strict";var HM=se(),jM=Ce(),Ul=ne(),KS=$t(),QM=ee(),GM=Dr(),WM=US(),ni=sa(),YM=wi(),zM=WS(),KM=zS(),XM=de(),JM=ze(),ZM=XM("replace"),eD=TypeError,ql=Ul("".indexOf),tD=Ul("".replace),XS=Ul("".slice),rD=Math.max;HM({target:"String",proto:!0},{replaceAll:function(e,t){var r=KS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!GM(e)){if(i=WM(e),i&&(s=ni(KS(zM(e))),!~ql(s,"g")))throw new eD("`.replaceAll` does not allow non-global regexes");if(n=YM(e,ZM),n)return jM(n,e,r,t);if(JM&&i)return tD(ni(r),e,t)}for(o=ni(r),u=ni(e),l=QM(t),l||(t=ni(t)),c=u.length,d=rD(1,c),p=ql(o,u);p!==-1;)h=l?ni(t(u,p,o)):KM(u,o,p,[],void 0,t),b+=XS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:ql(o,u,p+d);return m<o.length&&(b+=XS(o,m)),b}})});var ey=f((mH,ZS)=>{"use strict";NS();FS();JS();var iD=Mt();ZS.exports=iD("String","replaceAll")});var ry=f((fH,ty)=>{"use strict";var aD=ey();ty.exports=aD});var ay=f((bH,iy)=>{"use strict";var sD=ry();iy.exports=sD});var ny=f((gH,sy)=>{"use strict";var nD=Ri(),oD=sa(),uD=$t(),lD=RangeError;sy.exports=function(e){var t=oD(uD(this)),r="",i=nD(e);if(i<0||i===1/0)throw new lD("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var dy=f((vH,cy)=>{"use strict";var ly=ne(),cD=qo(),oy=sa(),dD=ny(),pD=$t(),hD=ly(dD),mD=ly("".slice),fD=Math.ceil,uy=function(a){return function(e,t,r){var i=oy(pD(e)),s=cD(t),n=i.length,o=r===void 0?" ":oy(r),u,l;return s<=n||o===""?i:(u=s-n,l=hD(o,fD(u/o.length)),l.length>u&&(l=mD(l,0,u)),a?i+l:l+i)}};cy.exports={start:uy(!1),end:uy(!0)}});var hy=f((SH,py)=>{"use strict";var bD=sr();py.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(bD)});var my=f(()=>{"use strict";var gD=se(),vD=dy().start,SD=hy();gD({target:"String",proto:!0,forced:SD},{padStart:function(e){return vD(this,e,arguments.length>1?arguments[1]:void 0)}})});var by=f((IH,fy)=>{"use strict";my();var yD=Mt();fy.exports=yD("String","padStart")});var vy=f((EH,gy)=>{"use strict";var TD=by();gy.exports=TD});var yy=f((xH,Sy)=>{"use strict";var ID=vy();Sy.exports=ID});var dd="2.0.124-dev.b0f19b8d.0";var Ie=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Ie||{}),Rt=(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))(Rt||{});var Ss=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ss||{}),lo=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(lo||{});var co=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(co||{}),ys=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(ys||{});var KT=V(Xe(),1);import{assertNever as lh,assertNonNullable as Dx,isNonNullable as Ps,ValueSubject as Ho,Subject as Cx,Subscription as Vx,merge as Bx,observableFrom as Ox,fromEvent as sh,map as nh,tap as oh,filterChanged as _x,isNullable as jo,ErrorCategory as uh}from"@vkontakte/videoplayer-shared/es2015";var ah=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var ws=class{constructor(e){this.connection$=new Ho(void 0);this.castState$=new Ho("NOT_AVAILABLE");this.errorEvent$=new Cx;this.realCastState$=new Ho("NOT_AVAILABLE");this.subscription=new Vx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ps((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||ah("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:uh.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ps(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();jo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();jo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(sh(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return lh(i.sessionState)}})).add(Bx(sh(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(oh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),nh(i=>i.castState)),Ox([r.getCastState()])).pipe(_x(),nh(Nx),oh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ps(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Dx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(jo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ps(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:uh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Nx=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 lh(a)}};var Tc=V(Xe(),1),$T=V(Ur(),1),MT=V(gu(),1);var hg=V(en(),1);import{assertNever as ag}from"@vkontakte/videoplayer-shared/es2015";var pe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:ag(t)}return a},tn=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:ag(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as WL,Subject as rn,merge as sg}from"@vkontakte/videoplayer-shared/es2015";var D=class{constructor(e){this.transitionStarted$=new rn;this.transitionEnded$=new rn;this.transitionUpdated$=new rn;this.forceChanged$=new rn;this.stateChangeStarted$=sg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=sg(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||WL(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as YL}from"@vkontakte/videoplayer-shared/es2015";var ng=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 YL(a)}};import{assertNever as Jr,assertNonNullable as pr,debounce as og,ErrorCategory as ug,fromEvent as hr,isNonNullable as lg,map as cg,merge as dg,observableFrom as zL,Subject as KL,Subscription as il,timeout as XL,getHighestQuality as JL}from"@vkontakte/videoplayer-shared/es2015";var ZL=5,eR=5,tR=500,pg=7e3,ji=class{constructor(e){this.subscription=new il;this.loadMediaTimeoutSubscription=new il;this.videoState=new D("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Jr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Jr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Jr(e)}break}default:Jr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ng(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 il;this.subscription.add(e),this.subscription.add(dg(this.videoState.stateChangeStarted$.pipe(cg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(cg(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new KL;e.add(i.pipe(og(tR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>ZL)&&i.next(o),s=o})),e.add(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<eR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Jr(n)}}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=dg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zL(["init"])).pipe(og(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(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"),x(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"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];pr(c);let d=JL(Object.keys(c));pr(d);let p=c[d];pr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];pr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];pr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];pr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];pr(c),r=pe(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:ug.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Jr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return lg(o)&&(n.metadata.title=o),lg(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(XL(pg).subscribe(()=>s(`timeout(${pg})`)))});(0,hg.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ug.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var El=V(Xe(),1);import{clearVideoElement as fg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as rR}from"@vkontakte/videoplayer-shared/es2015";var mg=a=>{try{a.pause(),a.playbackRate=0,rR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as iR,Subscription as aR}from"@vkontakte/videoplayer-shared/es2015";var al=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)}},sl=window.WeakMap?new WeakMap:new al,nl=window.WeakMap?new WeakMap:new Map,sR=(a,e=20)=>{let t=0;return iR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?fg(t):(t=document.createElement("video"),a.appendChild(t)),sl.set(t,r);let i=new aR;return i.add(sR(t,e)),nl.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},xe=a=>{let e=nl.get(a);e==null||e.unsubscribe(),nl.delete(a);let t=sl.get(a);sl.delete(a),t?fg(a):mg(a)};var ul=V(Zr(),1);import{assertNonNullable as Qi,isNonNullable as ut,isNullable as hR,fromEvent as ei,merge as Ig,observableFrom as Eg,filterChanged as xg,map as Gi,Subject as Pg,Subscription as mR,ValueSubject as fR,ErrorCategory as bR}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as ol,isNullable as dR,Subscription as pR}from"@vkontakte/videoplayer-shared/es2015";var an=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=dR(i),l=new pR;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>an(e,()=>a.loop,r=>{ol(r)&&(a.loop=r)},{onError:t}),Pe=(a,e,t,r)=>an(e,()=>({muted:a.muted,volume:a.volume}),i=>{ol(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Fe=(a,e,t,r)=>an(e,()=>a.playbackRate,i=>{ol(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ct=an;var gR=a=>["__",a.language,a.label].join("|"),vR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},ll=class a{constructor(e){this.available$=new Pg;this.current$=new fR(void 0);this.error$=new Pg;this.subscription=new mR;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:bR.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ct(t.internalTextTracks,()=>(0,ul.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ct(t.externalTextTracks,()=>(0,ul.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ct(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Ct(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Qi(this.video);let{textTracks:e}=this.video;this.subscription.add(ei(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Ig(ei(e,"addtrack"),ei(e,"removetrack"),Eg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),xg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Ig(ei(e,"change"),Eg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Gi(r=>r&&this.htmlTextTrackToITextTrack(r).id),xg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(ei(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(ei(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;ut(t.align)&&(i.align=t.align),ut(t.position)&&(i.position=t.position),ut(t.size)&&(i.size=t.size),ut(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Qi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:gR(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){Qi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(hR(e)||!vR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Qi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Qi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},qe=ll;var ft=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 wg=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},cl=a=>{let e=wg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Ag=a=>{let e=wg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ue,map as Vt,merge as Lg,filterChanged as yR,isNonNullable as Rg,Subject as TR,filter as $g,mapTo as Mg,combine as IR,once as ER,ErrorCategory as xR,ValueSubject as Dg,clientChecker as PR}from"@vkontakte/videoplayer-shared/es2015";var SR=3,kg=(a,e,t=SR)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var we=a=>{let e=y=>Ue(a,y).pipe(Mg(void 0)),r=Lg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Ue(a,y))).pipe(Vt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),yR()),i=Lg(Ue(a,"progress"),Ue(a,"timeupdate")).pipe(Vt(()=>kg(a.buffered,a.currentTime))),s=PR.isSafari?IR({play:e("play").pipe(ER()),playing:e("playing")}).pipe(Mg(void 0)):e("playing"),n=Ue(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=Ue(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=Ue(a,"error").pipe($g(()=>!!(a.error||a.played.length)),Vt(()=>{var P;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:xR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(P=a.error)!=null?P:void 0}})),l=Ue(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new TR,d=.3,p;l.subscribe(y=>{a.loop&&Rg(p)&&Rg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe($g(()=>!a.error&&p!==a.duration)),m=Ue(a,"enterpictureinpicture"),b=Ue(a,"leavepictureinpicture"),g=new Dg(Ag(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Dg(cl(a));return Ue(a,"fullscreenchange").pipe(Vt(()=>cl(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ue(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as Bt}from"@vkontakte/videoplayer-shared/es2015";var Ot=a=>{switch(a){case"mobile":return Bt.Q_144P;case"lowest":return Bt.Q_240P;case"low":return Bt.Q_360P;case"sd":case"medium":return Bt.Q_480P;case"hd":case"high":return Bt.Q_720P;case"fullhd":case"full":return Bt.Q_1080P;case"quadhd":case"quad":return Bt.Q_1440P;case"ultrahd":case"ultra":return Bt.Q_2160P}};var Nt=V(_t(),1),zg=V(Xe(),1),on=V(Ur(),1);import{isNonNullable as Oe,isNullable as Qg,now as Kg,isHigher as Gg,isHigherOrEqual as ml,isInvariantQuality as Wg,isLowerOrEqual as fl,videoSizeToQuality as BR,assertNotEmptyArray as Xg,assertNonNullable as OR}from"@vkontakte/videoplayer-shared/es2015";var dl=!1,bt={},Fg=a=>{dl=a},qg=()=>{bt={}},Ug=a=>{a(bt)},Wi=(a,e)=>{var t;dl&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var r,i;if(!dl)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};import{isHigher as CR,isHigherOrEqual as hN,isLower as Hg,isLowerOrEqual as mN,isNonNullable as sn,isNullable as VR,videoHeightToQuality as nn}from"@vkontakte/videoplayer-shared/es2015";function pl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function hl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&pl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Yi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return VR(a)||sn(a.min)&&sn(a.max)&&Hg(a.max,a.min)||sn(a.min)&&e&&CR(a.min,e)||sn(a.max)&&t&&Hg(a.max,t)}function jg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Yi({limits:{max:a!=null&&a.max?nn(a.max):void 0,min:a!=null&&a.min?nn(a.min):void 0},highestAvailableQuality:e?nn(e):void 0,lowestAvailableQuality:t?nn(t):void 0})}var _R=new ve("best_bitrate"),Jg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var bl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),zi=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',un=(a,e,t,r)=>{var u;let i=[...e].sort(bl(1)),s=[...t].sort(bl(1)),n=s.filter(l=>Oe(l.bitrate)&&Oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,zg.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},Yg=a=>"quality"in a,ev=(a,e,t,r)=>{var n;let i=Oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&Oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Kg()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Yg(o)?"video":"audio",l=Yg(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return r==null||r.recordSwitch(t),t},k$=(a,e)=>Math.log(e)/Math.log(a),Ft=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{var q,R,U,_,Y,k;Hg(a,Gg);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let D=r.pixelRatioLogBase,[W=0,j=0,Oe=0]=r.pixelRatioLogCoefficients,It=k$(D,W*T+j)+Oe;Number.isFinite(It)&&(b*=It)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,v=r.considerPlaybackRate&&oe(o)?o:1,S=a.filter(T=>!_g(T.quality)).sort((T,D)=>ll(T.quality,D.quality)?-1:1),y=(q=(0,Nt.default)(S,-1))==null?void 0:q.quality,x=(R=(0,Nt.default)(S,0))==null?void 0:R.quality,E=ul(i)||oe(i.min)&&oe(i.max)&&Ng(i.max,i.min)||oe(i.min)&&x&&ll(i.min,x)||oe(i.max)&&y&&Ng(i.max,y),L=v*jg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),B={},M=S.filter(T=>{let D=!0;if(g)if(T.size)D=T.size.width<=g.width&&T.size.height<=g.height;else{let de=g&&P$(g);D=de?dl(T.quality,de):!0}if(!D)return B[T.quality]="FitsContainer",!1;let W=h||t;if(!(oe(W)&&isFinite(W)&&oe(T.bitrate)?W-s>=T.bitrate*L:!0))return B[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&oe(r.minBufferToSwitchUp)&&u&&!_g(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&ll(T.quality,u.quality))return B[T.quality]="Buffer",!1;if(!!d&&cl(T.quality,d))return B[T.quality]="DroppedFramesLimit",!1;if(!!p&&cl(T.quality,p))return B[T.quality]="StallsLimit",!1;let G=E||(ul(i.max)||dl(T.quality,i.max))&&(ul(i.min)||cl(T.quality,i.min)),ce=oe(c)&&!c?dl(T.quality,r.backgroundVideoQualityLimit):!0;return!G||!ce?(B[T.quality]="FitsQualityLimits",!1):!0})[0];M&&M.bitrate&&A$.next(M.bitrate);let F=(U=M!=null?M:(0,Nt.default)(S,-1))!=null?U:a[0];return F.quality!==((_=l==null?void 0:l.last)==null?void 0:_.quality)&&f({message:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},NR=(a,e)=>Math.log(e)/Math.log(a),FR=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&window.devicePixelRatio){let i=window.devicePixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=NR(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return hl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Ft=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{var q,L,U,_,Y,k;Xg(a,Zg);let{containerSizeFactor:b,containerSizeLimit:g}=FR({container:e,tuning:r,limits:i}),v=r.considerPlaybackRate&&Oe(o)?o:1,S=a.filter(T=>!Wg(T.quality)).sort((T,O)=>Gg(T.quality,O.quality)?-1:1),y=(q=(0,Nt.default)(S,-1))==null?void 0:q.quality,P=(L=(0,Nt.default)(S,0))==null?void 0:L.quality,E=Yi({limits:i,lowestAvailableQuality:y,highestAvailableQuality:P}),$=v*Jg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),C={},M=S.filter(T=>{let O=!0;if(g)if(T.size)O=T.size.width<=g.width&&T.size.height<=g.height;else{let be=g&&BR(g);O=be?fl(T.quality,be):!0}if(!O)return C[T.quality]="FitsContainer",!1;let W=h||t,j=Oe(W)&&isFinite(W)&&Oe(T.bitrate)?W-s>=T.bitrate*$:!0,Me=hl({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===T.quality;if(!j&&!Me)return C[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Oe(r.minBufferToSwitchUp)&&u&&!Wg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Gg(T.quality,u.quality))return C[T.quality]="Buffer",!1;if(!!d&&ml(T.quality,d)&&!Me)return C[T.quality]="DroppedFramesLimit",!1;if(!!p&&ml(T.quality,p)&&!Me)return C[T.quality]="StallsLimit",!1;let le=E||(Qg(i==null?void 0:i.max)||fl(T.quality,i.max))&&(Qg(i==null?void 0:i.min)||ml(T.quality,i.min)),fe=Oe(c)&&!c?fl(T.quality,r.backgroundVideoQualityLimit):!0;return!le||!fe?(C[T.quality]="FitsQualityLimits",!1):!0})[0];M&&M.bitrate&&_R.next(M.bitrate);let F=(U=M!=null?M:(0,Nt.default)(S,-1))!=null?U:a[0];return F.quality!==((_=l==null?void 0:l.last)==null?void 0:_.quality)&&m({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(T=>{var D,W;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${(D=T.size)==null?void 0:D.width}:${(W=T.size)==null?void 0:W.height} }`}).join(`
12
+ ${a.map(T=>{var O,W;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${(O=T.size)==null?void 0:O.width}:${(W=T.size)==null?void 0:W.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,an.default)(r!=null?r:{}).map(([T,D])=>`${T}: ${D}`).join(`
16
+ ${(0,on.default)(r!=null?r:{}).map(([T,O])=>`${T}: ${O}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
@@ -25,7 +25,7 @@ var zT=Object.create;var io=Object.defineProperty,KT=Object.defineProperties,XT=
25
25
  playbackRate: ${o},
26
26
  playbackRateFactor: ${v},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${L},
28
+ bitrateFactor: ${$},
29
29
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
30
30
  droppedVideoMaxQualityLimit: ${d},
31
31
  stallsVideoMaxQualityLimit: ${p},
@@ -34,19 +34,19 @@ var zT=Object.create;var io=Object.defineProperty,KT=Object.defineProperties,XT=
34
34
  minQualityLimit: ${i==null?void 0:i.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,an.default)(B).map(([T,D])=>`${T}: ${D}`).join(`
37
+ ${(0,on.default)(C).map(([T,O])=>`${T}: ${O}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
40
  [best video track] ${M==null?void 0:M.quality}
41
41
  [selected video track] ${F==null?void 0:F.quality}
42
- `}),Qg(r,f,F,l)},Wg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Hg(t,Gg);let c=i.considerPlaybackRate&&oe(s)?s:1,d=[...t].sort(pl(-1)),p=a.bitrate;w$(p);let h=c*jg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=sn(a,e,t,i.minVideoAudioRatio),g=l||r;return oe(g)&&isFinite(g)&&(f=d.find(S=>oe(S.bitrate)&&oe(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),f||(f=b),(f==null?void 0:f.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
42
+ `}),ev(r,m,F,l)},tv=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Xg(t,Zg);let c=i.considerPlaybackRate&&Oe(s)?s:1,d=[...t].sort(bl(-1)),p=a.bitrate;OR(p);let h=c*Jg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,b=un(a,e,t,i.minVideoAudioRatio),g=l||r;return Oe(g)&&isFinite(g)&&(m=d.find(S=>Oe(S.bitrate)&&Oe(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),m||(m=b),(m==null?void 0:m.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
43
43
  [AUDIO TRACKS ABR]
44
44
  [available audio tracks]
45
45
  ${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,an.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
49
+ ${(0,on.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
@@ -59,15 +59,15 @@ var zT=Object.create;var io=Object.defineProperty,KT=Object.defineProperties,XT=
59
59
  bitrateFactor: ${h},
60
60
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
61
61
 
62
- [selected audio track] ${f==null?void 0:f.id}
63
- `}),f&&Qg(i,u,f,o)};var ue=a=>new URL(a).hostname;import{assertNever as iv,assertNonNullable as av,combine as z$,debounce as K$,ErrorCategory as sv,filter as nv,filterChanged as X$,isNonNullable as gl,map as cn,merge as ov,observableFrom as J$,once as Z$,Subscription as eL,ValueSubject as vl,videoQualityToHeight as tL,videoSizeToQuality as rL}from"@vkontakte/videoplayer-shared/es2015";var zg=O(Xe(),1);var Yg=a=>{if(a instanceof DOMException&&(0,zg.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"))},Ae=(a,e)=>w(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Yg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Yg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as on,isNullable as L$,assertNonNullable as Xi}from"@vkontakte/videoplayer-shared/es2015";var Xg=O(Zr(),1);import{isNonNullable as Kg,assertNonNullable as nn,now as R$}from"@vkontakte/videoplayer-shared/es2015";function le(){return R$()}function hl(a){return le()-a}function fl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Jg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ri(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;nn(c);let R=hl(c),U;if(R<b){U=b-R,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,L()},v=R=>(s=R,q),S=R=>(d=R,q),y=()=>(h="json",q),x=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=R=>(p=R,q),L=()=>{c=le(),n=new i,n.open("get",a);let R=0,U,_=0,Y=()=>(nn(c),Math.max(c,Math.max(U||0,_||0)));if(s&&n.addEventListener("progress",k=>{let T=le();s.updateChunk&&k.loaded>R&&(s.updateChunk(Y(),k.loaded-R),R=k.loaded,U=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(u)return;nn(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let T=n.response.byteLength-R;T&&s.updateChunk&&s.updateChunk(Y(),T)}n.responseType==="json"&&!(0,Xg.default)(n.response).length?x():(d&&d(),e(n.response))}else x()}),n.addEventListener("error",()=>{x()}),p){let k=()=>{nn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(_=le(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),q},q={withBitrateReporting:v,withParallel:E,withJSONResponse:y,withRetryCount:R=>(l=R,q),withRetryInterval:(R,U)=>(Kg(R)&&(b=R),Kg(U)&&(f=U),q),withTimeout:R=>(o=R,q),withFinally:S,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var zi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Zg=O(Zr(),1);var Ki=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=le(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=le()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ri(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=le()}_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=le();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Zg.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as M$}from"@vkontakte/videoplayer-shared/es2015";var un=1e4,ml=3;var D$=6e4,C$=10,B$=1,V$=500,Ji=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new M$,this.chunkRateEstimator=new zi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=fl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=fl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||on(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Jg(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ki(ml,un,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let x=s&&(!c||c===this.rep);return x||t("Not running!"),x},p=(x,E,L)=>{u&&u.abort(),u=ri(this.urlResolver.resolve(x,!1),E,L,()=>this._retryCallback()).withTimeout(un).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ml).withFinally(()=>{u=null}).send()},h=(x,E,L)=>{Xi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),E,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=x=>{let E=r.playbackRate;r.playbackRate!==x&&(t(`Playback rate switch: ${E}=>${x}`),r.playbackRate=x)},b=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let L=le()-1e4,B=0;for(let M=0;M<this.bufferStates.length;M++){let F=this.bufferStates[M];x=Math.min(x,F.buf),F.ts<L&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${x} drop=${B} jitter=${this.sourceJitter}`);let Z=x-B$;this.sourceJitter>=0?Z-=this.sourceJitter/2:this.sourceJitter-=1,Z>3?f(1.15):Z>1?f(1.1):Z>.3?f(1.05):f(1)}},v=x=>{let E,L=()=>E&&E.start?E.start.length:0,B=k=>E.start[k]/1e3,Z=k=>E.dur[k]/1e3,M=k=>E.fragIndex+k,F=(k,T)=>({chunkIdx:M(k),startTS:B(k),dur:Z(k),discontinuity:T}),q=()=>{let k=0;if(E&&E.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,D=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=T;this.sourceJitter>1&&(W+=this.sourceJitter-1);let j=E.dur.length-1;for(;j>=0&&(W-=E.dur[j],!(W<=0));--j);k=Math.min(j,E.dur.length-1-D),k=Math.max(k,0)}return F(k,!0)},R=k=>{let T=L();if(!(T<=0)){if(on(k)){for(let D=0;D<T;D++)if(B(D)>k)return F(D)}return q()}},U=k=>{let T=L(),D=k?k.chunkIdx+1:0,W=D-E.fragIndex;if(!(T<=0)){if(!k||W<0||W-T>C$)return t(`Resync: offset=${W} bChunks=${T} chunk=`+JSON.stringify(k)),q();if(!(W>=T))return F(D-E.fragIndex,!1)}},_=(k,T,D)=>{l&&l.abort(),l=ri(this.urlResolver.resolve(k,!0,this.lowLatency),T,D,()=>this._retryCallback()).withTimeout(un).withRetryCount(ml).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,T)=>{_(x,D=>{if(!d())return;E=D;let W=!!E.lowLatency;W!==this.lowLatency&&b(W);let j=0;for(let Oe=0;Oe<E.dur.length;++Oe)j+=E.dur[Oe];j>0&&(Xi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(j/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,k(R(T))},()=>this._handleNetworkError())},nextChunk:U}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Xi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:x=>{let{videoElement:E,logger:L}=this.params,B=v(e.jidxUrl),Z,M,F,q,R=0,U,_,Y,k=()=>{U&&(clearTimeout(U),U=void 0);let G=Math.max(V$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=R+G,de=le(),_e=Math.min(1e4,ce-de);R=de;let Et=()=>{l||d()&&B.seek(()=>{d()&&(R=le(),T(),k())})};_e>0?U=window.setTimeout(()=>{this.paused?k():Et()},_e):Et()},T=()=>{let G;for(;G=B.nextChunk(q);)q=G,It(G);let ce=B.nextChunk(F);if(ce){if(F&&ce.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}Oe(ce)}else k()},D=(G,ce)=>{if(!d()||!this.sourceBuffer)return;let de,_e,Et,Pr=xt=>{window.setTimeout(()=>{d()&&D(G,ce)},xt)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Pr(100);else{let xt=le(),Kt=E.currentTime;!this.paused&&E.buffered.length>1&&_===Kt&&xt-Y>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),_!==Kt&&(_=Kt,Y=xt);let wr=this._getBufferSizeSec();if(wr>30)L(`Buffered ${wr} seconds; delaying appendBuffer`),Pr(2e3);else try{this.sourceBuffer.appendBuffer(G),this.videoPlayStarted?(this.bufferStates.push({ts:xt,buf:wr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(fi){if(fi.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(de=this.sourceBuffer.buffered.start(0),_e=Kt,_e-de>4&&this.sourceBuffer.remove(de,_e-3)),Pr(1e3);else throw fi}}},W=()=>{M&&Z&&(L([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(F)]),D(M,function(){M=null,T()}))},j=G=>e.fragUrlTemplate.replace("%%id%%",G.chunkIdx),Oe=G=>{d()&&h(j(G),(ce,de)=>{if(d()){if(de/=1e3,M=ce,F=G,n=G.startTS,de){let _e=Math.min(10,G.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*_e:_e}W()}},()=>this._handleNetworkError())},It=G=>{d()&&(Xi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(j(G),!1)))},xr=G=>{d()&&(e.cachedHeader=G,D(G,()=>{Z=!0,W()}))};s=!0,B.seek(G=>{if(d()){if(R=le(),!G){k();return}q=G,!L$(x)||G.startTS>x?Oe(G):(F=G,T())}},x),e.cachedHeader?xr(e.cachedHeader):p(e.headerUrl,xr,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),on(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Xi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return on(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=le();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&hl(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=le();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ri(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(un).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ae(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},D$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var rv=O(Ur(),1);import{debounce as O$,filter as ev,fromEvent as _$,interval as N$,isHigher as F$,isInvariantQuality as q$,isLower as U$,merge as H$,Subject as tv,Subscription as j$}from"@vkontakte/videoplayer-shared/es2015";var bl=class{constructor(){this.onDroopedVideoFramesLimit$=new tv;this.subscription=new j$;this.playing=!1;this.tracks=[];this.forceChecker$=new tv;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&&!q$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&F$(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(_$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=N$(this.droppedFramesChecker.checkTime).pipe(ev(()=>this.playing),ev(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(O$(this.droppedFramesChecker.checkTime)),r=H$(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,rv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>U$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ln=bl;import{map as G$,Observable as Q$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as W$}from"@vkontakte/videoplayer-shared/es2015";var Zi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Y$=(a,e)=>new Q$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Zi()))},I(I({},r),e));i.observe(a);let s=W$(document,"visibilitychange").pipe(G$(n=>!document.hidden||Zi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),He=Y$;var iL=["paused","playing","ready"],aL=["paused","playing","ready"],ea=class{constructor(e){this.subscription=new eL;this.videoState=new C("stopped");this.representations$=new vl([]);this.droppedFramesManager=new ln;this.maxSeekBackTime$=new vl(1/0);this.zeroTime$=new vl(void 0);this.liveOffset=new mt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:sv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=_t(u.name))!=null?r:rL(u.video),d=u.bitrate/1e3,p=I({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),gl(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Sl.default)(aL,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Sl.default)(iL,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(fe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(fe(this.params.source.url,u))}return;default:return iv(e)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:sv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};ov(this.videoState.stateChangeStarted$.pipe(cn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(cn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=we(this.video);this.subscription.add(this.representations$.pipe(cn(i=>i.map(({track:s})=>s)),nv(i=>!!i.length),Z$()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(X$(),cn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(z$({zeroTime:this.zeroTime$.pipe(nv(gl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Fe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(He(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&tL(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return iv(i.to)}},t)).add(ov(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,J$(["init"])).pipe(K$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),xe(this.video)}createLiveDashPlayer(){let e=new Ji({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&gl(t)?t:Ft(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;av(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;av(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(fe(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var uv=ea;var Gy=O(Xe(),1);var lt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as QD,assertNonNullable as WD,debounce as YD,ErrorCategory as sc,filter as Uy,filterChanged as ja,fromEvent as zD,isNonNullable as Hy,map as nc,merge as On,observableFrom as oc,once as jy,Subscription as KD}from"@vkontakte/videoplayer-shared/es2015";var dn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ii=class extends dn{constructor(){super(),this.listeners||dn.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)}},ta=class{constructor(){Object.defineProperty(this,"signal",{value:new ii,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ta.prototype[Symbol.toStringTag]="AbortController",ii.prototype[Symbol.toStringTag]="AbortSignal");function pn(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 yl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!pn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ra=pn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),lv=ra?yl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=ra?lv.fetch:window.fetch,EF=ra?lv.Request:window.Request,me=ra?ta:window.AbortController,xF=ra?ii:window.AbortSignal;var tc=O(Il(),1);var Tn=O(ti(),1);var gt=()=>window.ManagedMediaSource||window.MediaSource,hn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Rv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},$v=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as En,clientChecker as In}from"@vkontakte/videoplayer-shared/es2015";var je=document.createElement("video"),RL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',$L='video/mp4; codecs="hev1.1.6.L93.B0"',qv='video/webm; codecs="vp09.00.10.08"',Uv='video/webm; codecs="av01.0.00M.08"',LL='audio/mp4; codecs="mp4a.40.2"',ML='audio/webm; codecs="opus"',Lv,Mv,ia={mms:hn(),mse:Rv(),hls:!!((Lv=je.canPlayType)!=null&&Lv.call(je,"application/x-mpegurl")||(Mv=je.canPlayType)!=null&&Mv.call(je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Dv,Cv,ke={mp4:!!((Dv=je.canPlayType)!=null&&Dv.call(je,"video/mp4")),webm:!!((Cv=je.canPlayType)!=null&&Cv.call(je,"video/webm")),cmaf:!0},mn,Bv,bn,Vv,gn,Ov,vn,_v,Sn,Nv,yn,Fv,Re={h264:!!((Bv=(mn=gt())==null?void 0:mn.isTypeSupported)!=null&&Bv.call(mn,RL)),h265:!!((Vv=(bn=gt())==null?void 0:bn.isTypeSupported)!=null&&Vv.call(bn,$L)),vp9:!!((Ov=(gn=gt())==null?void 0:gn.isTypeSupported)!=null&&Ov.call(gn,qv)),av1:!!((_v=(vn=gt())==null?void 0:vn.isTypeSupported)!=null&&_v.call(vn,Uv)),aac:!!((Nv=(Sn=gt())==null?void 0:Sn.isTypeSupported)!=null&&Nv.call(Sn,LL)),opus:!!((Fv=(yn=gt())==null?void 0:yn.isTypeSupported)!=null&&Fv.call(yn,ML))},ai=(Re.h264||Re.h265)&&Re.aac,fr,DL=()=>w(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo($(I({},a),{video:$(I({},a.video),{contentType:Uv})})),window.navigator.mediaCapabilities.decodingInfo($(I({},a),{video:$(I({},a.video),{contentType:qv})}))]);fr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{DL()}catch(a){console.error(a)}var si=ia.hls&&ke.mp4,Hv=()=>Object.keys(Re).filter(a=>Re[a]),jv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ia.mse&&(!r||!!window.MediaStreamTrack)||ia.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&ke.mp4&&ai;case"DASH_WEBM":return i&&ke.webm&&Re.vp9&&Re.opus;case"DASH_WEBM_AV1":return i&&ke.webm&&Re.av1&&Re.opus;case"DASH_STREAMS":return i&&(ke.mp4&&ai||ke.webm&&(Re.vp9||Re.av1)&&(Re.opus||Re.aac));case"DASH_LIVE":return i&&ke.mp4&&ai;case"DASH_LIVE_CMAF":return i&&ke.mp4&&ai&&ke.cmaf;case"DASH_ONDEMAND":return i&&ke.mp4&&ai;case"HLS":case"HLS_ONDEMAND":return si||e&&i&&ke.mp4&&ai;case"HLS_LIVE":case"HLS_LIVE_CMAF":return si;case"MPEG":return ke.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ia.webrtc&&ia.ws&&Re.h264&&(ke.mp4||ke.webm);default:return En(s)}})},fn=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return fr?fr[t].smooth?[t,e]:fr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return fr?fr[t].powerEfficient?[t,e]:fr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:En(a)}return[e,t]},Gv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...fn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(In.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...fn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...fn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...fn(a),...i,"HLS","HLS_ONDEMAND"];default:En(e)}return si?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Qv=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=In.isMac&&In.isSafari;if(In.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:En(a)}else si&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},El=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Wv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Tn.default)(t.value.split("."),0)}for(let t of a){let r=(0,Tn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,Tn.default)(e.value.split("."),0)};var fS=O(hS(),1);import{ErrorCategory as sa}from"@vkontakte/videoplayer-shared/es2015";var mS=a=>{if(!a)return{id:"EmptyResponse",category:sa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:sa.NETWORK,message:`UV Error ${a}`};let e=(0,fS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:sa.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:sa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:sa.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as Zl,assertNonNullable as yr,clientChecker as wD,combine as di,ErrorCategory as Qt,filter as Fa,filterChanged as Ln,flattenObject as qa,fromEvent as Tr,getTraceSubscriptionMethod as AD,interval as ec,isNonNullable as Cy,map as Ua,merge as Ir,now as kD,Subject as By,Subscription as Vy,tap as RD,throttle as $D,ValueSubject as ie}from"@vkontakte/videoplayer-shared/es2015";var Pn=O(Xe(),1),li=O(ti(),1),wn=O(Il(),1);var KL=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},XL=a=>window.clearTimeout(a),bS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),gS=!bS(window.requestIdleCallback)||!bS(window.cancelIdleCallback),kl=gS?KL:window.requestIdleCallback,na=gS?XL:window.cancelIdleCallback;var wy=O(Zs(),1);import{assertNever as JL,ErrorCategory as vS,clientChecker as Rl,Subject as SS}from"@vkontakte/videoplayer-shared/es2015";var ZL=18,yS=!1;try{yS=Rl.isSafari&&!!Rl.macVersion&&Rl.macVersion<=ZL}catch(a){console.error(a)}var $l=class{constructor(e){this.bufferFull$=new SS;this.error$=new SS;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:vS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return w(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return w(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return w(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};yS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:vS.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:JL(t)}}},TS=$l;var Ll=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Ht,assertNonNullable as $e,clientChecker as mD,ErrorCategory as jt,fromEvent as Yl,getExponentialDelay as zl,isNonNullable as ui,isNullable as be,now as xn,once as bD,Subject as gD,Subscription as vD,ValueSubject as gr}from"@vkontakte/videoplayer-shared/es2015";var N=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ni=class extends N{};var oa=class extends N{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ua=class extends N{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var la=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends N{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ca=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 da=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends N{constructor(e,t){super(e,t),this.data=this.content}};var mr=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ha=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ma=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 ba=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ga=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 va=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=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 ya=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ea=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xa=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 Pa=class extends J{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var wa=class extends J{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Aa=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=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 Ra=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var tM={ftyp:ua,moov:la,mvhd:ca,moof:da,mdat:pa,sidx:mr,trak:ha,mdia:va,mfhd:Ia,tkhd:Sa,traf:Ea,tfhd:xa,tfdt:Pa,trun:wa,minf:ya,sv3d:fa,st3d:ma,prhd:ba,proj:Ta,equi:ga,uuid:oa,stbl:Aa,stsd:ka,avc1:Ra,unknown:ni},vt=class a{constructor(e={}){this.options=I({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=tM[e];return r?new r(t,new a):new ni(t,new a)}};var Ut=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var iM=new TextDecoder("ascii"),aM=a=>iM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",sM=a=>{let e=new mr(a,new vt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},nM=(a,e)=>{let r=new vt().parse(a),i=new Ut(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},oM=a=>{let t=new vt().parse(a),r=new Ut(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},uM=a=>{var i;let t=new vt().parse(a);return(i=new Ut(t).find("sidx"))==null?void 0:i.timescale},lM=(a,e)=>{let r=new vt().parse(a),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},cM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new vt().parse(a),i=new Ut(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},IS={validateData:aM,parseInit:cM,getIndexRange:()=>{},parseSegments:sM,parseFeedableSegmentChunk:nM,getChunkEndTime:lM,getServerLatencyTimestamps:oM,getTimescaleFromIndex:uM};var La=O(Xe(),1);import{assertNonNullable as Dl,isNonNullable as wS,isNullable as pM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as dM}from"@vkontakte/videoplayer-shared/es2015";var ES={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"}},xS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=$a(a,t),i=r in ES,s=i?ES[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=$a(u),d=l*at(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},$a=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*at(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*at(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*at(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},et=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return $a(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:dM(e)}},br=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=xS(r);if(!e(i))return;i.type==="master"&&br(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},PS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=xS(a);return br(i.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var AS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],hM=[231,22612,22743,167,171,163,160,175],fM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return br(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=et(f,h);l=$a(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=et(f,h):p===17545?i=et(f,h):p===21420&&l===475249515?u=et(f,h):p===374648427?br(f,({tag:g,type:v,value:S})=>g===30321?(c=et(S,v)===1,!1):!0):s&&n&&(0,La.default)(AS,p)&&(o=!0),!o}),Dl(e,"Failed to parse webm Segment start"),Dl(t,"Failed to parse webm Segment end"),Dl(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},mM=a=>{if(pM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},bM=(a,e)=>{let t=!1,r=!1,i=o=>wS(o.time)&&wS(o.position),s=[],n;return br(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=et(l,u));break;case 183:break;case 241:n&&(n.position=et(l,u));break;default:t&&(0,La.default)(AS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},gM=a=>{let e=0,t=!1;try{br(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,La.default)(hM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,La.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},kS={validateData:PS,parseInit:fM,getIndexRange:mM,parseSegments:bM,parseFeedableSegmentChunk:gM};var Ma=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return kS;case"mp4":return IS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Gl=O(YS(),1),yy=O(Ur(),1),Ty=O(cy(),1),Iy=O(ti(),1),Ql=O(Zr(),1);var dy=O(Xe(),1),Nl=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,dy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as fD,isNullable as vy}from"@vkontakte/videoplayer-shared/es2015";var py=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var hy=a=>{var e;try{let t=pD(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function pD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
62
+ [selected audio track] ${m==null?void 0:m.id}
63
+ `}),m&&ev(i,u,m,o)};var oe=a=>new URL(a).hostname;import{assertNever as pv,assertNonNullable as hv,combine as o$,debounce as u$,ErrorCategory as mv,filter as fv,filterChanged as l$,isNonNullable as Tl,map as hn,merge as bv,observableFrom as c$,once as d$,Subscription as p$,ValueSubject as Il,videoQualityToHeight as gv,videoSizeToQuality as h$}from"@vkontakte/videoplayer-shared/es2015";var uv=V(_t(),1);var iv=V(Xe(),1);var rv=a=>{if(a instanceof DOMException&&(0,iv.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"))},Ae=(a,e)=>A(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!rv(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return rv(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as cn,isNullable as HR,assertNonNullable as Ji}from"@vkontakte/videoplayer-shared/es2015";var sv=V(Zr(),1);import{isNonNullable as av,assertNonNullable as ln,now as qR}from"@vkontakte/videoplayer-shared/es2015";function ue(){return qR()}function gl(a){return ue()-a}function vl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function nv(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ti(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;ln(c);let L=gl(c),U;if(L<b){U=b-L,setTimeout(g,U);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,$()},v=L=>(s=L,q),S=L=>(d=L,q),y=()=>(h="json",q),P=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=L=>(p=L,q),$=()=>{c=ue(),n=new i,n.open("get",a);let L=0,U,_=0,Y=()=>(ln(c),Math.max(c,Math.max(U||0,_||0)));if(s&&n.addEventListener("progress",k=>{let T=ue();s.updateChunk&&k.loaded>L&&(s.updateChunk(Y(),k.loaded-L),L=k.loaded,U=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>P())),n.addEventListener("load",()=>{if(u)return;ln(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let T=n.response.byteLength-L;T&&s.updateChunk&&s.updateChunk(Y(),T)}n.responseType==="json"&&!(0,sv.default)(n.response).length?P():(d&&d(),e(n.response))}else P()}),n.addEventListener("error",()=>{P()}),p){let k=()=>{ln(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(_=ue(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),q},q={withBitrateReporting:v,withParallel:E,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:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var Ki=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var ov=V(Zr(),1);var Xi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ue(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ue()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ti(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ue()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ue();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,ov.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as jR}from"@vkontakte/videoplayer-shared/es2015";var dn=1e4,Sl=3;var QR=6e4,GR=10,WR=1,YR=500,Zi=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 jR,this.chunkRateEstimator=new Ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=vl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=vl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!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)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s))}return console.log("entered",i||r),i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||cn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{nv(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Xi(Sl,dn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let P=s&&(!c||c===this.rep);return P||t("Not running!"),P},p=(P,E,$)=>{u&&u.abort(),u=ti(this.urlResolver.resolve(P,!1),E,$,()=>this._retryCallback()).withTimeout(dn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Sl).withFinally(()=>{u=null}).send()},h=(P,E,$)=>{Ji(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(P,!1),E,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=P=>{let E=r.playbackRate;r.playbackRate!==P&&(t(`Playback rate switch: ${E}=>${P}`),r.playbackRate=P)},b=P=>{this.lowLatency=P,t(`lowLatency changed to ${P}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let P=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let $=ue()-1e4,C=0;for(let M=0;M<this.bufferStates.length;M++){let F=this.bufferStates[M];P=Math.min(P,F.buf),F.ts<$&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${P} drop=${C} jitter=${this.sourceJitter}`);let Z=P-WR;this.sourceJitter>=0?Z-=this.sourceJitter/2:this.sourceJitter-=1,Z>3?m(1.15):Z>1?m(1.1):Z>.3?m(1.05):m(1)}},v=P=>{let E,$=()=>E&&E.start?E.start.length:0,C=k=>E.start[k]/1e3,Z=k=>E.dur[k]/1e3,M=k=>E.fragIndex+k,F=(k,T)=>({chunkIdx:M(k),startTS:C(k),dur:Z(k),discontinuity:T}),q=()=>{let k=0;if(E&&E.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,O=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,W=T;this.sourceJitter>1&&(W+=this.sourceJitter-1);let j=E.dur.length-1;for(;j>=0&&(W-=E.dur[j],!(W<=0));--j);k=Math.min(j,E.dur.length-1-O),k=Math.max(k,0)}return F(k,!0)},L=k=>{let T=$();if(!(T<=0)){if(cn(k)){for(let O=0;O<T;O++)if(C(O)>k)return F(O)}return q()}},U=k=>{let T=$(),O=k?k.chunkIdx+1:0,W=O-E.fragIndex;if(!(T<=0)){if(!k||W<0||W-T>GR)return t(`Resync: offset=${W} bChunks=${T} chunk=`+JSON.stringify(k)),q();if(!(W>=T))return F(O-E.fragIndex,!1)}},_=(k,T,O)=>{l&&l.abort(),l=ti(this.urlResolver.resolve(k,!0,this.lowLatency),T,O,()=>this._retryCallback()).withTimeout(dn).withRetryCount(Sl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,T)=>{_(P,O=>{if(!d())return;E=O;let W=!!E.lowLatency;W!==this.lowLatency&&b(W);let j=0;for(let Me=0;Me<E.dur.length;++Me)j+=E.dur[Me];j>0&&(Ji(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(j/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,k(L(T))},()=>this._handleNetworkError())},nextChunk:U}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ji(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:P=>{let{videoElement:E,logger:$}=this.params,C=v(e.jidxUrl),Z,M,F,q,L=0,U,_,Y,k=()=>{U&&(clearTimeout(U),U=void 0);let Q=Math.max(YR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=L+Q,fe=ue(),be=Math.min(1e4,le-fe);L=fe;let It=()=>{l||d()&&C.seek(()=>{d()&&(L=ue(),T(),k())})};be>0?U=window.setTimeout(()=>{this.paused?k():It()},be):It()},T=()=>{let Q;for(;Q=C.nextChunk(q);)q=Q,hi(Q);let le=C.nextChunk(F);if(le){if(F&&le.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}Me(le)}else k()},O=(Q,le)=>{if(!d()||!this.sourceBuffer)return;let fe,be,It,Pr=Et=>{window.setTimeout(()=>{d()&&O(Q,le)},Et)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),Pr(100);else{let Et=ue(),Kt=E.currentTime;!this.paused&&E.buffered.length>1&&_===Kt&&Et-Y>500&&($("Stall suspected; trying to fix"),this._fixupStall()),_!==Kt&&(_=Kt,Y=Et);let wr=this._getBufferSizeSec();if(wr>30)$(`Buffered ${wr} seconds; delaying appendBuffer`),Pr(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:Et,buf:wr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(mi){if(mi.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),It=this.sourceBuffer.buffered.length,It!==0&&(fe=this.sourceBuffer.buffered.start(0),be=Kt,be-fe>4&&this.sourceBuffer.remove(fe,be-3)),Pr(1e3);else throw mi}}},W=()=>{M&&Z&&($([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(F)]),O(M,function(){M=null,T()}))},j=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),Me=Q=>{d()&&h(j(Q),(le,fe)=>{if(d()){if(fe/=1e3,M=le,F=Q,n=Q.startTS,fe){let be=Math.min(10,Q.dur/fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*be:be}W()}},()=>this._handleNetworkError())},hi=Q=>{d()&&(Ji(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(j(Q),!1)))},xr=Q=>{d()&&(e.cachedHeader=Q,O(Q,()=>{Z=!0,W()}))};s=!0,C.seek(Q=>{if(d()){if(L=ue(),!Q){k();return}q=Q,!HR(P)||Q.startTS>P?Me(Q):(F=Q,T())}},P),e.cachedHeader?xr(e.cachedHeader):p(e.headerUrl,xr,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),cn(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ji(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return cn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=ue();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&gl(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ue();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ti(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(dn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ae(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},QR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var dv=V(Ur(),1);import{debounce as zR,filter as lv,fromEvent as KR,interval as XR,isHigher as JR,isInvariantQuality as ZR,isLower as e$,merge as t$,Subject as cv,Subscription as r$}from"@vkontakte/videoplayer-shared/es2015";var yl=class{constructor(){this.onDroopedVideoFramesLimit$=new cv;this.subscription=new r$;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&&!ZR(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&JR(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(KR(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=XR(this.droppedFramesChecker.checkTime).pipe(lv(()=>this.playing),lv(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(zR(this.droppedFramesChecker.checkTime)),r=t$(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,dv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>e$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},pn=yl;import{map as i$,Observable as a$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as s$}from"@vkontakte/videoplayer-shared/es2015";var ea=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var n$=(a,e)=>new a$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||ea()))},I(I({},r),e));i.observe(a);let s=s$(document,"visibilitychange").pipe(i$(n=>!document.hidden||ea())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),He=n$;var m$=["paused","playing","ready"],f$=["paused","playing","ready"],ta=class{constructor(e){this.subscription=new p$;this.videoState=new D("stopped");this.representations$=new Il([]);this.droppedFramesManager=new pn;this.maxSeekBackTime$=new Il(1/0);this.zeroTime$=new Il(void 0);this.liveOffset=new ft;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category: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=(r=Ot(u.name))!=null?r:h$(u.video),d=u.bitrate/1e3,p=I({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Tl(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,El.default)(f$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,El.default)(m$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(pe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(pe(this.params.source.url,u))}return;default:return pv(e)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:mv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};bv(this.videoState.stateChangeStarted$.pipe(hn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(hn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),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 r=we(this.video);this.subscription.add(this.representations$.pipe(hn(i=>i.map(({track:s})=>s)),fv(i=>!!i.length),d$()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(l$(),hn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(o$({zeroTime:this.zeroTime$.pipe(fv(Tl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Fe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(He(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&gv(i),min:s&&gv(s)}),this.params.output.autoVideoTrackLimits$.next({max:i,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return pv(i.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$,c$(["init"])).pipe(u$(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 Zi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Tl(t)?t:Ft(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;hv(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;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(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(pe(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var vv=ta;var tT=V(Xe(),1);var lt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as i0,assertNonNullable as a0,debounce as s0,ErrorCategory as lc,filter as Jy,filterChanged as Qa,fromEvent as n0,isNonNullable as Zy,map as cc,merge as Fn,observableFrom as dc,once as eT,Subscription as o0}from"@vkontakte/videoplayer-shared/es2015";var mn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ri=class extends mn{constructor(){super(),this.listeners||mn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},ra=class{constructor(){Object.defineProperty(this,"signal",{value:new ri,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ra.prototype[Symbol.toStringTag]="AbortController",ri.prototype[Symbol.toStringTag]="AbortSignal");function fn(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 xl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!fn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ia=fn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Sv=ia?xl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=ia?Sv.fetch:window.fetch,jF=ia?Sv.Request:window.Request,he=ia?ra:window.AbortController,QF=ia?ri:window.AbortSignal;var sc=V(wl(),1);var xn=V(_t(),1);var gt=()=>window.ManagedMediaSource||window.MediaSource,bn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Nv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Fv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as wn,clientChecker as Pn}from"@vkontakte/videoplayer-shared/es2015";var je=document.createElement("video"),F$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',q$='video/mp4; codecs="hev1.1.6.L93.B0"',Xv='video/webm; codecs="vp09.00.10.08"',Jv='video/webm; codecs="av01.0.00M.08"',U$='audio/mp4; codecs="mp4a.40.2"',H$='audio/webm; codecs="opus"',qv,Uv,aa={mms:bn(),mse:Nv(),hls:!!((qv=je.canPlayType)!=null&&qv.call(je,"application/x-mpegurl")||(Uv=je.canPlayType)!=null&&Uv.call(je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Hv,jv,ke={mp4:!!((Hv=je.canPlayType)!=null&&Hv.call(je,"video/mp4")),webm:!!((jv=je.canPlayType)!=null&&jv.call(je,"video/webm")),cmaf:!0},vn,Qv,Sn,Gv,yn,Wv,Tn,Yv,In,zv,En,Kv,Le={h264:!!((Qv=(vn=gt())==null?void 0:vn.isTypeSupported)!=null&&Qv.call(vn,F$)),h265:!!((Gv=(Sn=gt())==null?void 0:Sn.isTypeSupported)!=null&&Gv.call(Sn,q$)),vp9:!!((Wv=(yn=gt())==null?void 0:yn.isTypeSupported)!=null&&Wv.call(yn,Xv)),av1:!!((Yv=(Tn=gt())==null?void 0:Tn.isTypeSupported)!=null&&Yv.call(Tn,Jv)),aac:!!((zv=(In=gt())==null?void 0:In.isTypeSupported)!=null&&zv.call(In,U$)),opus:!!((Kv=(En=gt())==null?void 0:En.isTypeSupported)!=null&&Kv.call(En,H$))},ii=(Le.h264||Le.h265)&&Le.aac,mr,j$=()=>A(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(R(I({},a),{video:R(I({},a.video),{contentType:Jv})})),window.navigator.mediaCapabilities.decodingInfo(R(I({},a),{video:R(I({},a.video),{contentType:Xv})}))]);mr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{j$()}catch(a){console.error(a)}var ai=aa.hls&&ke.mp4,Zv=()=>Object.keys(Le).filter(a=>Le[a]),eS=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=aa.mse&&(!r||!!window.MediaStreamTrack)||aa.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&ke.mp4&&ii;case"DASH_WEBM":return i&&ke.webm&&Le.vp9&&Le.opus;case"DASH_WEBM_AV1":return i&&ke.webm&&Le.av1&&Le.opus;case"DASH_STREAMS":return i&&(ke.mp4&&ii||ke.webm&&(Le.vp9||Le.av1)&&(Le.opus||Le.aac));case"DASH_LIVE":return i&&ke.mp4&&ii;case"DASH_LIVE_CMAF":return i&&ke.mp4&&ii&&ke.cmaf;case"DASH_ONDEMAND":return i&&ke.mp4&&ii;case"HLS":case"HLS_ONDEMAND":return ai||e&&i&&ke.mp4&&ii;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ai;case"MPEG":return ke.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return aa.webrtc&&aa.ws&&Le.h264&&(ke.mp4||ke.webm);default:return wn(s)}})},gn=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return mr?mr[t].smooth?[t,e]:mr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return mr?mr[t].powerEfficient?[t,e]:mr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:wn(a)}return[e,t]},tS=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...gn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Pn.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...gn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...gn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...gn(a),...i,"HLS","HLS_ONDEMAND"];default:wn(e)}return ai?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},rS=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=Pn.isMac&&Pn.isSafari;if(Pn.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:wn(a)}else ai&&!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"]},Al=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],iS=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,xn.default)(t.value.split("."),0)}for(let t of a){let r=(0,xn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,xn.default)(e.value.split("."),0)};var xS=V(ES(),1);import{ErrorCategory as na}from"@vkontakte/videoplayer-shared/es2015";var PS=a=>{if(!a)return{id:"EmptyResponse",category:na.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:na.NETWORK,message:`UV Error ${a}`};let e=(0,xS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:na.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:na.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:na.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as ic,assertNonNullable as yr,clientChecker as OD,combine as ci,ErrorCategory as Gt,filter as qa,filterChanged as Cn,flattenObject as Ua,fromEvent as Tr,getTraceSubscriptionMethod as _D,interval as ac,isNonNullable as jy,map as Ha,merge as Ir,now as ND,Subject as Qy,Subscription as Gy,tap as FD,throttle as qD,ValueSubject as ie}from"@vkontakte/videoplayer-shared/es2015";var kn=V(Xe(),1),ui=V(_t(),1),Ln=V(wl(),1);var oM=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},uM=a=>window.clearTimeout(a),wS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),AS=!wS(window.requestIdleCallback)||!wS(window.cancelIdleCallback),Ml=AS?oM:window.requestIdleCallback,oa=AS?uM:window.cancelIdleCallback;var By=V(en(),1);import{assertNever as lM,ErrorCategory as kS,clientChecker as Dl,Subject as LS}from"@vkontakte/videoplayer-shared/es2015";var cM=18,RS=!1;try{RS=Dl.isSafari&&!!Dl.macVersion&&Dl.macVersion<=cM}catch(a){console.error(a)}var Cl=class{constructor(e){this.bufferFull$=new LS;this.error$=new LS;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:kS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return A(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return A(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return A(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};RS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:kS.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:lM(t)}}},$S=Cl;var Vl=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Ht,assertNonNullable as Re,clientChecker as wD,ErrorCategory as jt,fromEvent as Jl,getExponentialDelay as Zl,isNonNullable as oi,isNullable as me,now as An,once as AD,Subject as kD,Subscription as LD,ValueSubject as gr}from"@vkontakte/videoplayer-shared/es2015";var N=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var si=class extends N{};var ua=class extends N{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var la=class extends N{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ca=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends N{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var da=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 pa=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends N{constructor(e,t){super(e,t),this.data=this.content}};var fr=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ma=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=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 ga=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var va=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 Sa=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=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 Ta=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var xa=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=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 wa=class extends J{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Aa=class extends J{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ka=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var La=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 Ra=class extends N{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var pM={ftyp:la,moov:ca,mvhd:da,moof:pa,mdat:ha,sidx:fr,trak:ma,mdia:Sa,mfhd:Ea,tkhd:ya,traf:xa,tfhd:Pa,tfdt:wa,trun:Aa,minf:Ta,sv3d:fa,st3d:ba,prhd:ga,proj:Ia,equi:va,uuid:ua,stbl:ka,stsd:La,avc1:Ra,unknown:si},vt=class a{constructor(e={}){this.options=I({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=pM[e];return r?new r(t,new a):new si(t,new a)}};var Ut=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var mM=new TextDecoder("ascii"),fM=a=>mM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",bM=a=>{let e=new fr(a,new vt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},gM=(a,e)=>{let r=new vt().parse(a),i=new Ut(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},vM=a=>{let t=new vt().parse(a),r=new Ut(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},SM=a=>{var i;let t=new vt().parse(a);return(i=new Ut(t).find("sidx"))==null?void 0:i.timescale},yM=(a,e)=>{let r=new vt().parse(a),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},TM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new vt().parse(a),i=new Ut(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},MS={validateData:fM,parseInit:TM,getIndexRange:()=>{},parseSegments:bM,parseFeedableSegmentChunk:gM,getChunkEndTime:yM,getServerLatencyTimestamps:vM,getTimescaleFromIndex:SM};var Ma=V(Xe(),1);import{assertNonNullable as Ol,isNonNullable as BS,isNullable as EM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as IM}from"@vkontakte/videoplayer-shared/es2015";var DS={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"}},CS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=$a(a,t),i=r in DS,s=i?DS[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=$a(u),d=l*at(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},$a=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*at(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*at(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*at(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},et=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return $a(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:IM(e)}},br=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=CS(r);if(!e(i))return;i.type==="master"&&br(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},VS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=CS(a);return br(i.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var OS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],xM=[231,22612,22743,167,171,163,160,175],PM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return br(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=et(m,h);l=$a(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=et(m,h):p===17545?i=et(m,h):p===21420&&l===475249515?u=et(m,h):p===374648427?br(m,({tag:g,type:v,value:S})=>g===30321?(c=et(S,v)===1,!1):!0):s&&n&&(0,Ma.default)(OS,p)&&(o=!0),!o}),Ol(e,"Failed to parse webm Segment start"),Ol(t,"Failed to parse webm Segment end"),Ol(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},wM=a=>{if(EM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},AM=(a,e)=>{let t=!1,r=!1,i=o=>BS(o.time)&&BS(o.position),s=[],n;return br(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=et(l,u));break;case 183:break;case 241:n&&(n.position=et(l,u));break;default:t&&(0,Ma.default)(OS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},kM=a=>{let e=0,t=!1;try{br(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Ma.default)(xM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Ma.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},_S={validateData:VS,parseInit:PM,getIndexRange:wM,parseSegments:AM,parseFeedableSegmentChunk:kM};var Da=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return _S;case"mp4":return MS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var zl=V(ay(),1),Ry=V(Ur(),1),$y=V(yy(),1),My=V(_t(),1),Kl=V(Zr(),1);var Ty=V(Xe(),1),Hl=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,Ty.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as PD,isNullable as ky}from"@vkontakte/videoplayer-shared/es2015";var Iy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Ey=a=>{var e;try{let t=ED(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function ED(){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 ql=O(ti(),1);import{videoSizeToQuality as hD}from"@vkontakte/videoplayer-shared/es2015";var fy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?_t(s):void 0)!=null?u:hD({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},my=({id:a,bitrate:e})=>({id:a,bitrate:e}),by=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),gy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Ul=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,ql.default)(r.split("."),0),isDefault:i}),Hl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,ql.default)(i.split("."),0)}),jl=a=>"url"in a,Se=a=>a.type==="template",Da=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Sy=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},St=(a,e)=>{let t=a;t=(0,Gl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,yy.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Gl.default)(t,n,(o,u)=>vy(s)?o:vy(u)?s:(0,Ty.default)(s,parseInt(u,10),"0"))}return t},Ey=(a,e)=>{var E,L,B,Z,M,F,q,R,U,_,Y,k,T,D,W,j,Oe,It,xr,G,ce,de,_e,Et,Pr,xt,Kt,wr,fi,Ec,xc,Pc,wc,Ac,kc,Rc,$c,Lc,Mc,Dc,Cc,Bc,Vc,Oc,_c,Nc,Fc,qc,Uc,Hc,jc,Gc,Qc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Ge=>{var K,Xt;return(Xt=(K=Ge.textContent)==null?void 0:K.trim())!=null?Xt:""}),o=(E=(0,Iy.default)(n,0))!=null?E:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],f=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((Ge,K)=>$(I({},Ge),{[K.id]:K.children}),{}),v=b.reduce((Ge,K)=>$(I({},Ge),{[K.id]:K.getAttribute("duration")}),{});p?d=Sy(p):(0,Ql.default)(v).filter(Ge=>Ge).length&&!u?d=(0,Ql.default)(v).reduce((Ge,K)=>{var Xt;return Ge+((Xt=Sy(K))!=null?Xt:0)},0):f&&(d=parseInt(f,10));let S=0,y=(B=(L=s.getAttribute("profiles"))==null?void 0:L.split(","))!=null?B:[];for(let Ge of b.map(K=>K.id))for(let K of g[Ge]){let Xt=(Z=K.getAttribute("id"))!=null?Z:"id"+(S++).toString(10),mi=(M=K.getAttribute("mimeType"))!=null?M:"",Jn=(F=K.getAttribute("codecs"))!=null?F:"",Zn=(q=K.getAttribute("contentType"))!=null?q:mi==null?void 0:mi.split("/")[0],UT=(U=(R=K.getAttribute("profiles"))==null?void 0:R.split(","))!=null?U:[],td=(Y=hy((_=K.getAttribute("lang"))!=null?_:""))!=null?Y:{},as=(D=(T=(k=K.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:T.trim())!=null?D:void 0,HT=K.querySelectorAll("Representation"),jT=K.querySelector("SegmentTemplate"),GT=(j=(W=K.querySelector("Role"))==null?void 0:W.getAttribute("value"))!=null?j:void 0,Ar=Zn,te={id:Xt,language:td.language,isDefault:GT==="main",label:as,codecs:Jn,hdr:Ar==="video"&&Nl(Jn),mime:mi,representations:[]};for(let z of HT){let Pt=(Oe=z.getAttribute("lang"))!=null?Oe:void 0,bi=(xr=(It=as!=null?as:K.getAttribute("label"))!=null?It:z.getAttribute("label"))!=null?xr:void 0,ss=(de=(ce=(G=z.querySelector("BaseURL"))==null?void 0:G.textContent)==null?void 0:ce.trim())!=null?de:"",Jt=new URL(ss||o,e).toString(),wt=(_e=z.getAttribute("mimeType"))!=null?_e:mi,ns=(Pr=(Et=z.getAttribute("codecs"))!=null?Et:Jn)!=null?Pr:"",os;if(Zn==="text"){let At=z.getAttribute("id")||"",us=((xt=td.privateuse)==null?void 0:xt.includes("x-auto"))||At.includes("_auto"),Zt=z.querySelector("SegmentTemplate");if(Zt){let gi={representationId:(Kt=z.getAttribute("id"))!=null?Kt:void 0,bandwidth:(wr=z.getAttribute("bandwidth"))!=null?wr:void 0},ls=parseInt((fi=z.getAttribute("bandwidth"))!=null?fi:"",10)/1e3,cs=(xc=parseInt((Ec=Zt.getAttribute("startNumber"))!=null?Ec:"",10))!=null?xc:1,kr=parseInt((Pc=Zt.getAttribute("timescale"))!=null?Pc:"",10),eo=(wc=Zt.querySelectorAll("SegmentTimeline S"))!=null?wc:[],Rr=Zt.getAttribute("media");if(!Rr)continue;let ds=[],ps=0,hs="",$r=0,vi=cs,ge=0;for(let Qe of eo){let er=parseInt((Ac=Qe.getAttribute("d"))!=null?Ac:"",10),Ne=parseInt((kc=Qe.getAttribute("r"))!=null?kc:"",10)||0,kt=parseInt((Rc=Qe.getAttribute("t"))!=null?Rc:"",10);ge=Number.isFinite(kt)?kt:ge;let tr=er/kr*1e3,Rt=ge/kr*1e3;for(let rt=0;rt<Ne+1;rt++){let $t=St(Rr,$(I({},gi),{segmentNumber:vi.toString(10),segmentTime:(ge+rt*er).toString(10)})),Lr=(Rt!=null?Rt:0)+rt*tr,yi=Lr+tr;vi++,ds.push({time:{from:Lr,to:yi},url:$t})}ge+=(Ne+1)*er,ps+=(Ne+1)*tr}$r=ge/kr*1e3,hs=St(Rr,$(I({},gi),{segmentNumber:vi.toString(10),segmentTime:ge.toString(10)}));let Si={time:{from:$r,to:1/0},url:hs},dt={type:"template",baseUrl:Jt,segmentTemplateUrl:Rr,initUrl:"",totalSegmentsDurationMs:ps,segments:ds,nextSegmentBeyondManifest:Si,timescale:kr};os={id:At,kind:"text",segmentReference:dt,profiles:[],duration:d,bitrate:ls,mime:"",codecs:"",width:0,height:0,isAuto:us}}else os={id:At,isAuto:us,kind:"text",url:Jt}}else{let At=(Lc=($c=z.getAttribute("contentType"))!=null?$c:wt==null?void 0:wt.split("/")[0])!=null?Lc:Zn,us=(Dc=(Mc=K.getAttribute("profiles"))==null?void 0:Mc.split(","))!=null?Dc:[],Zt=parseInt((Cc=z.getAttribute("width"))!=null?Cc:"",10),gi=parseInt((Bc=z.getAttribute("height"))!=null?Bc:"",10),ls=parseInt((Vc=z.getAttribute("bandwidth"))!=null?Vc:"",10)/1e3,cs=(Oc=z.getAttribute("frameRate"))!=null?Oc:"",kr=(_c=z.getAttribute("quality"))!=null?_c:void 0,eo=cs?py(cs):void 0,Rr=(Nc=z.getAttribute("id"))!=null?Nc:"id"+(S++).toString(10),ds=At==="video"?`${gi}p`:At==="audio"?`${ls}Kbps`:ns,ps=`${Rr}@${ds}`,hs=[...y,...UT,...us],$r,vi=z.querySelector("SegmentBase"),ge=(Fc=z.querySelector("SegmentTemplate"))!=null?Fc:jT;if(vi){let dt=(Uc=(qc=z.querySelector("SegmentBase Initialization"))==null?void 0:qc.getAttribute("range"))!=null?Uc:"",[Qe,er]=dt.split("-").map($t=>parseInt($t,10)),Ne={from:Qe,to:er},kt=(Hc=z.querySelector("SegmentBase"))==null?void 0:Hc.getAttribute("indexRange"),[tr,Rt]=kt?kt.split("-").map($t=>parseInt($t,10)):[],rt=kt?{from:tr,to:Rt}:void 0;$r={type:"byteRange",url:Jt,initRange:Ne,indexRange:rt}}else if(ge){let dt={representationId:(jc=z.getAttribute("id"))!=null?jc:void 0,bandwidth:(Gc=z.getAttribute("bandwidth"))!=null?Gc:void 0},Qe=parseInt((Qc=ge.getAttribute("timescale"))!=null?Qc:"",10),er=(Wc=ge.getAttribute("initialization"))!=null?Wc:"",Ne=ge.getAttribute("media"),kt=(zc=parseInt((Yc=ge.getAttribute("startNumber"))!=null?Yc:"",10))!=null?zc:1,tr=St(er,dt);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Rt=(Kc=ge.querySelectorAll("SegmentTimeline S"))!=null?Kc:[],rt=[],$t=0,Lr="",yi=0;if(Rt.length){let fs=kt,We=0;for(let Mr of Rt){let it=parseInt((Xc=Mr.getAttribute("d"))!=null?Xc:"",10),rr=parseInt((Jc=Mr.getAttribute("r"))!=null?Jc:"",10)||0,ms=parseInt((Zc=Mr.getAttribute("t"))!=null?Zc:"",10);We=Number.isFinite(ms)?ms:We;let to=it/Qe*1e3,ro=We/Qe*1e3;for(let bs=0;bs<rr+1;bs++){let WT=St(Ne,$(I({},dt),{segmentNumber:fs.toString(10),segmentTime:(We+bs*it).toString(10)})),rd=(ro!=null?ro:0)+bs*to,YT=rd+to;fs++,rt.push({time:{from:rd,to:YT},url:WT})}We+=(rr+1)*it,$t+=(rr+1)*to}yi=We/Qe*1e3,Lr=St(Ne,$(I({},dt),{segmentNumber:fs.toString(10),segmentTime:We.toString(10)}))}else if(fD(d)){let We=parseInt((ed=ge.getAttribute("duration"))!=null?ed:"",10)/Qe*1e3,Mr=Math.ceil(d/We),it=0;for(let rr=1;rr<Mr;rr++){let ms=St(Ne,$(I({},dt),{segmentNumber:rr.toString(10),segmentTime:it.toString(10)}));rt.push({time:{from:it,to:it+We},url:ms}),it+=We}yi=it,Lr=St(Ne,$(I({},dt),{segmentNumber:Mr.toString(10),segmentTime:it.toString(10)}))}let QT={time:{from:yi,to:1/0},url:Lr};$r={type:"template",baseUrl:Jt,segmentTemplateUrl:Ne,initUrl:tr,totalSegmentsDurationMs:$t,segments:rt,nextSegmentBeyondManifest:QT,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!At||!wt)continue;let Si={video:"video",audio:"audio",text:"text"}[At];if(!Si)continue;Ar||(Ar=Si),os={id:ps,kind:Si,segmentReference:$r,profiles:hs,duration:d,bitrate:ls,mime:wt,codecs:ns,width:Zt,height:gi,fps:eo,quality:kr}}te.language||(te.language=Pt),te.label||(te.label=bi),te.mime||(te.mime=wt),te.codecs||(te.codecs=ns),te.hdr||(te.hdr=Ar==="video"&&Nl(ns)),te.representations.push(os)}if(Ar){let z=i[Ar].find(Pt=>Pt.id===te.id);if(z&&te.representations.every(Pt=>Se(Pt.segmentReference)))for(let Pt of z.representations){let bi=te.representations.find(wt=>wt.id===Pt.id),ss=bi==null?void 0:bi.segmentReference,Jt=Pt.segmentReference;Jt.segments.push(...ss.segments),Jt.nextSegmentBeyondManifest=ss.nextSegmentBeyondManifest}else i[Ar].push(te)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var Py=O(Xe(),1);import{isNonNullable as xy}from"@vkontakte/videoplayer-shared/es2015";var ye=(a,e)=>xy(a)&&xy(e)&&a.readyState==="open"&&(0,Py.default)([...a.activeSourceBuffers],e);var Ca=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gr(0);this.currentLowLatencySegmentLength$=new gr(0);this.currentSegmentLength$=new gr(0);this.onLastSegment$=new gr(!1);this.fullyBuffered$=new gr(!1);this.playingRepresentation$=new gr(void 0);this.playingRepresentationInit$=new gr(void 0);this.error$=new gD;this.gaps=[];this.subscription=new vD;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=Ht(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){let t=this.representations.get(e);$e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new TS(this.sourceBuffer),this.subscription.add(Yl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:jt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:jt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Yl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:jt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ye(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ll(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=lt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);$e(r,"No init buffer for starting representation"),$e(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=Ht(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(be(s)||be(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ui(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new vs(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Ht(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(be(s)||be(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ui(n)&&(this.isLive||(this.bufferLimit=1/0,yield new vs(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Ht(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){var u,l;let t=(u=(0,wn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Se(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);$e(i);let s=this.segments.get(r);$e(s,"No segments for starting representation");let n=this.initData.get(r);if($e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new me,Ht(this.switchAbortController.signal,function(r,i=!1){return ae(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);$e(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(be(o)||be(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),$e(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();ui(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!be(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return w(this,null,function*(){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(be(e)||be(this.downloadingRepresentationId)||be(this.playingRepresentationId)||be(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer)||ui(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if($e(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);ui(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=lt(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Ll(this.sourceBuffer.buffered)>=this.bufferLimit){let l=lt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,Pn.default)(o,i))l="high";else{let c=(0,li.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&lt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,li.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;ui(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,wn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,wn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Se(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>$(I({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,li.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;$e(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Se(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=St(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&na&&na(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&na&&na(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&ye(this.mediaSource,this.sourceBuffer)&&!(qt(this.sourceBuffer.buffered,p)&&qt(this.sourceBuffer.buffered,h)))&&g&&S});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return w(this,null,function*(){Se(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return w(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ht(o,function(){return ae(this,null,function*(){let c=zl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=xn(),!c)return;let d=new DataView(c),p=Ma(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Da(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())Se(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return w(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Ht(n,function(){return ae(this,null,function*(){let u=zl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Yl(window,"online").pipe(bD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=xn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Da(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Se(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,li.default)(e,0).byte.from,to:(0,li.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>w(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=xn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:jt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!Se(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=xn();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:jt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Pn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return w(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ma(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return w(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(!f)continue;let g=Ma(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(be(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer))){!this.isLive&&mD.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:jt.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",jl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=kl(()=>(0,wy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return w(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ht(this.destroyAbortController.signal,function(){return ae(this,null,function*(){let o=zl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ma(e.mime),i)).then(o=>w(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Se(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:jt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return w(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return w(this,null,function*(){if(!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||be(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(I({},u.time)),i=n(i);let l=jl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Pn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return w(this,null,function*(){if(!this.sourceBuffer||!ye(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||!ye(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||be(e)?0:lt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=kl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:jt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(be(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer)||be(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Ba=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ay=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Va,assertNever as Ry,fromEvent as $y,merge as SD,now as Oa,Subscription as yD,ValueSubject as Kl,flattenObject as ci}from"@vkontakte/videoplayer-shared/es2015";var ky=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var An=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Kl(void 0);this.lastConnectionReused$=new Kl(void 0);this.lastRequestFirstBytes$=new Kl(void 0);this.abortAllController=new me;this.subscription=new yD;this.fetchManifest=Va(this.abortAllController.signal,function(e){return ae(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ba(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=ky(r));let i=yield Ze(r,{signal:this.abortAllController.signal}).catch(_a);return i?(t.log("success",ci({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ci({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Va(this.abortAllController.signal,function(l){return ae(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,U;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(c,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),c=_.toString();break}default:Ry(t)}this.requestQuic&&(c=Ba(c));let h=this.abortAllController.signal,f;if(n){let _=new me;if(f=SD($y(this.abortAllController.signal,"abort"),$y(n,"abort")).subscribe(()=>{try{_.abort()}catch(Y){_a(Y)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(Y){_a(Y)}h=_.signal}let b=Oa();p.log("startRequest",ci({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield Ze(c,{priority:s,headers:d,signal:h}).catch(_a),v=Oa();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(v-b),!g.ok||!g.body){f==null||f.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:_}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let _=Oa(),Y={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",ci(Y)),p.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),x=S.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(y,u));let E=0,L=new Uint8Array(0),B=!1,Z=_=>{f==null||f.unsubscribe(),B=!0,_a(_)},M=Va(h,function(k){return ae(this,arguments,function*({done:_,value:Y}){if(E===0&&this.lastRequestFirstBytes$.next(Oa()-b),h.aborted){f==null||f.unsubscribe();return}if(!_&&Y){let T=new Uint8Array(L.length+Y.length);T.set(L),T.set(Y,L.length),L=T,E+=Y.byteLength,i==null||i(new DataView(L.buffer),E),yield x==null?void 0:x.read().then(M,Z)}})}.bind(this));yield x==null?void 0:x.read().then(M,Z),f==null||f.unsubscribe();let F=Oa(),q={failed:B,requestStartedAt:b,requestEndedAt:F,duration:F-b};return B?(p.error("endRequest",ci(q)),p.end(),null):(p.log("endRequest",ci(q)),p.end(),L.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Va(this.abortAllController.signal,function(e,t,r){return ae(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Va(this.abortAllController.signal,function(e,t){return ae(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>$(I({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=Ay(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return w(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Ry(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},_a=a=>{if(!Da(a))throw a};var vr=(a,e,t)=>t*e+(1-t)*a,Xl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Ly=(a,e,t,r)=>{let i=0,s=t,n=Xl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as TD,ValueSubject as My}from"@vkontakte/videoplayer-shared/es2015";var Gt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new My(e.initial),this.debounced$=new My(e.initial);let t=(r=e.label)!=null?r:"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,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=at(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(TD(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 kn=class extends Gt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vr(this.slow,e,this.params.emaAlphaSlow),this.fast=vr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Rn=class extends Gt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Xl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vr(this.emaSmoothed,e,this.params.emaAlpha);let r=Ly(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var $n=class extends Gt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?vr(this.smoothed,t,this.params.emaAlpha):t}};var Sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new kn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Rn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new $n(I({initial:e,label:"liveEdgeDelay"},t))}};var Jl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as ID,ValueSubject as ED}from"@vkontakte/videoplayer-shared/es2015";var Na=class a{constructor(e,t){this.currentRepresentation$=new ED(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(!ID(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next($(I({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Se(t.segmentReference))}};var LD=["timeupdate","progress","play","seeked","stalled","waiting"],MD=["timeupdate","progress","loadeddata","playing","seeked"];var Mn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Vy;this.representationSubscription=new Vy;this.state$=new C("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new By;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.currentLiveTextRepresentation$=new ie(null);this.isLive$=new ie(!1);this.liveDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLatency$=new ie(void 0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.isLowLatency$=new ie(!1);this.isActiveLowLatency$=new ie(!1);this.currentStallDuration$=new ie(0);this.videoLastDataObtainedTimestamp$=new ie(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new By;this.gapWatchdogActive=!1;this.destroyController=new me;this.initManifest=Zl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=fe(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Qt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Zl(this.destroyController.signal,function(){return ae(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Qt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Ey(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=mS(e))!=null?n:{id:"ManifestParsing",category:Qt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=gt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=Wv(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);wD.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=$(I({},t),{streams:i});return this.tracer.log("updateManifestEnd",qa(s)),s})}.bind(this));this.initRepresentations=Zl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",qa({initialVideo:e,initialAudio:t,sourceHls:r})),yr(this.manifest),yr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Tr(p,"error").pipe(Fa(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?$v():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&hn())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ca("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Cy(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Ca("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Na.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Na(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ec(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=en(this.manifestUrlString,2);this.manifestUrlString=fe(this.manifestUrlString,f+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ir(...MD.map(p=>Tr(this.element,p))).pipe(Ua(p=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),Ln(),RD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ir(Tr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ln()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Jl(this.element,1)})),this.representationSubscription.add(di({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Fa(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(di({isActiveLowLatency:this.isActiveLowLatency$.pipe(Ln()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Fa(({isActiveLowLatency:h,currentLowLatencySegmentLength:f})=>h&&!!f)).subscribe(({currentLowLatencySegmentLength:h})=>{let f=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(f,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(di({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Fa(({isLive:h})=>h),Ua(h=>I({},h)),Ln((h,f)=>f.bufferLength<h.bufferLength),Ua(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=en(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(di({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=h-b;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(S)>g&&(y=1+Math.sign(S)*v),Jl(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(y=>{var x,E;return(E=(x=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:x.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(di({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe($D(1e3)).subscribe(b=>w(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(yr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=en(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,L=isFinite(h)?h:f,B=this.isActiveLowLatency$.getValue(),Z=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(B&&Z);let M="none";if(B?M="active_low_latency":this.isLowLatency$.getValue()&&Z?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),M="active_low_latency"):v!==0&&L<y?M="live_forward_buffering":L<y+E&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let F=p-(y+x),q=this.normolizeLiveOffset(Math.trunc(v+F/g)),R=Math.abs(q-v),U;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?U=v:q>0&&R>this.tuning.dashCmafLive.offsetCalculationError?U=q:U=0,this.manifestUrlString=fe(this.manifestUrlString,U,2)}M!=="none"&&M!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=Ir(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ua(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Ir(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ua(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(Ir(this.forceEnded$,di({allBuffersFull:l,someBufferEnded:c}).pipe(Fa(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:Qt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ir(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,tc.default)((0,tc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Se(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Cy(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ec(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Qt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new An({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Sr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,I({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return w(this,null,function*(){var r,i,s;yr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=fe(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){yr(this.element),this.state$.setState("running"),this.subscription.add(Ir(...LD.map(e=>Tr(this.element,e)),Tr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Qt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Tr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Tr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,v,S,y,x,E,L;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=kD(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(x=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?x:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let B=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(B),(L=this.audioBufferManager)==null||L.maintain(B),i.position=B}this.tracer.log("stallIntervalCallback",qa(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=ec(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Qt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return w(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)})}seek(e,t){return w(this,null,function*(){var i,s,n,o,u;yr(this.element),yr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),qt(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",qa({requestedPosition:e,forcePrecise:t,position:r}))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=AD(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return w(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=$(I({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",qa(t)))}}};var Dn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Cn=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/at(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=I({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*at(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Oy=`attribute vec2 a_vertex;
70
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Ql=V(_t(),1);import{videoSizeToQuality as xD}from"@vkontakte/videoplayer-shared/es2015";var xy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ot(s):void 0)!=null?u:xD({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Py=({id:a,bitrate:e})=>({id:a,bitrate:e}),wy=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Ay=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Gl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ql.default)(r.split("."),0),isDefault:i}),Wl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ql.default)(i.split("."),0)}),Yl=a=>"url"in a,Se=a=>a.type==="template",Ca=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Ly=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},St=(a,e)=>{let t=a;t=(0,zl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Ry.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,zl.default)(t,n,(o,u)=>ky(s)?o:ky(u)?s:(0,$y.default)(s,parseInt(u,10),"0"))}return t},Dy=(a,e)=>{var E,$,C,Z,M,F,q,L,U,_,Y,k,T,O,W,j,Me,hi,xr,Q,le,fe,be,It,Pr,Et,Kt,wr,mi,kc,Lc,Rc,$c,Mc,Dc,Cc,Vc,Bc,Oc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,rd,id,ad,sd;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Qe=>{var K,Xt;return(Xt=(K=Qe.textContent)==null?void 0:K.trim())!=null?Xt:""}),o=(E=(0,My.default)(n,0))!=null?E:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],m=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((Qe,K)=>R(I({},Qe),{[K.id]:K.children}),{}),v=b.reduce((Qe,K)=>R(I({},Qe),{[K.id]:K.getAttribute("duration")}),{});p?d=Ly(p):(0,Kl.default)(v).filter(Qe=>Qe).length&&!u?d=(0,Kl.default)(v).reduce((Qe,K)=>{var Xt;return Qe+((Xt=Ly(K))!=null?Xt:0)},0):m&&(d=parseInt(m,10));let S=0,y=(C=($=s.getAttribute("profiles"))==null?void 0:$.split(","))!=null?C:[];for(let Qe of b.map(K=>K.id))for(let K of g[Qe]){let Xt=(Z=K.getAttribute("id"))!=null?Z:"id"+(S++).toString(10),fi=(M=K.getAttribute("mimeType"))!=null?M:"",ro=(F=K.getAttribute("codecs"))!=null?F:"",io=(q=K.getAttribute("contentType"))!=null?q:fi==null?void 0:fi.split("/")[0],XT=(U=(L=K.getAttribute("profiles"))==null?void 0:L.split(","))!=null?U:[],nd=(Y=Ey((_=K.getAttribute("lang"))!=null?_:""))!=null?Y:{},as=(O=(T=(k=K.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:T.trim())!=null?O:void 0,JT=K.querySelectorAll("Representation"),ZT=K.querySelector("SegmentTemplate"),eI=(j=(W=K.querySelector("Role"))==null?void 0:W.getAttribute("value"))!=null?j:void 0,Ar=io,te={id:Xt,language:nd.language,isDefault:eI==="main",label:as,codecs:ro,hdr:Ar==="video"&&Hl(ro),mime:fi,representations:[]};for(let z of JT){let xt=(Me=z.getAttribute("lang"))!=null?Me:void 0,bi=(xr=(hi=as!=null?as:K.getAttribute("label"))!=null?hi:z.getAttribute("label"))!=null?xr:void 0,ss=(fe=(le=(Q=z.querySelector("BaseURL"))==null?void 0:Q.textContent)==null?void 0:le.trim())!=null?fe:"",Jt=new URL(ss||o,e).toString(),Pt=(be=z.getAttribute("mimeType"))!=null?be:fi,ns=(Pr=(It=z.getAttribute("codecs"))!=null?It:ro)!=null?Pr:"",os;if(io==="text"){let wt=z.getAttribute("id")||"",us=((Et=nd.privateuse)==null?void 0:Et.includes("x-auto"))||wt.includes("_auto"),Zt=z.querySelector("SegmentTemplate");if(Zt){let gi={representationId:(Kt=z.getAttribute("id"))!=null?Kt:void 0,bandwidth:(wr=z.getAttribute("bandwidth"))!=null?wr:void 0},ls=parseInt((mi=z.getAttribute("bandwidth"))!=null?mi:"",10)/1e3,cs=(Lc=parseInt((kc=Zt.getAttribute("startNumber"))!=null?kc:"",10))!=null?Lc:1,kr=parseInt((Rc=Zt.getAttribute("timescale"))!=null?Rc:"",10),ao=($c=Zt.querySelectorAll("SegmentTimeline S"))!=null?$c:[],Lr=Zt.getAttribute("media");if(!Lr)continue;let ds=[],ps=0,hs="",Rr=0,vi=cs,ge=0;for(let Ge of ao){let er=parseInt((Mc=Ge.getAttribute("d"))!=null?Mc:"",10),Ne=parseInt((Dc=Ge.getAttribute("r"))!=null?Dc:"",10)||0,At=parseInt((Cc=Ge.getAttribute("t"))!=null?Cc:"",10);ge=Number.isFinite(At)?At:ge;let tr=er/kr*1e3,kt=ge/kr*1e3;for(let rt=0;rt<Ne+1;rt++){let Lt=St(Lr,R(I({},gi),{segmentNumber:vi.toString(10),segmentTime:(ge+rt*er).toString(10)})),$r=(kt!=null?kt:0)+rt*tr,yi=$r+tr;vi++,ds.push({time:{from:$r,to:yi},url:Lt})}ge+=(Ne+1)*er,ps+=(Ne+1)*tr}Rr=ge/kr*1e3,hs=St(Lr,R(I({},gi),{segmentNumber:vi.toString(10),segmentTime:ge.toString(10)}));let Si={time:{from:Rr,to:1/0},url:hs},dt={type:"template",baseUrl:Jt,segmentTemplateUrl:Lr,initUrl:"",totalSegmentsDurationMs:ps,segments:ds,nextSegmentBeyondManifest:Si,timescale:kr};os={id:wt,kind:"text",segmentReference:dt,profiles:[],duration:d,bitrate:ls,mime:"",codecs:"",width:0,height:0,isAuto:us}}else os={id:wt,isAuto:us,kind:"text",url:Jt}}else{let wt=(Bc=(Vc=z.getAttribute("contentType"))!=null?Vc:Pt==null?void 0:Pt.split("/")[0])!=null?Bc:io,us=(_c=(Oc=K.getAttribute("profiles"))==null?void 0:Oc.split(","))!=null?_c:[],Zt=parseInt((Nc=z.getAttribute("width"))!=null?Nc:"",10),gi=parseInt((Fc=z.getAttribute("height"))!=null?Fc:"",10),ls=parseInt((qc=z.getAttribute("bandwidth"))!=null?qc:"",10)/1e3,cs=(Uc=z.getAttribute("frameRate"))!=null?Uc:"",kr=(Hc=z.getAttribute("quality"))!=null?Hc:void 0,ao=cs?Iy(cs):void 0,Lr=(jc=z.getAttribute("id"))!=null?jc:"id"+(S++).toString(10),ds=wt==="video"?`${gi}p`:wt==="audio"?`${ls}Kbps`:ns,ps=`${Lr}@${ds}`,hs=[...y,...XT,...us],Rr,vi=z.querySelector("SegmentBase"),ge=(Qc=z.querySelector("SegmentTemplate"))!=null?Qc:ZT;if(vi){let dt=(Wc=(Gc=z.querySelector("SegmentBase Initialization"))==null?void 0:Gc.getAttribute("range"))!=null?Wc:"",[Ge,er]=dt.split("-").map(Lt=>parseInt(Lt,10)),Ne={from:Ge,to:er},At=(Yc=z.querySelector("SegmentBase"))==null?void 0:Yc.getAttribute("indexRange"),[tr,kt]=At?At.split("-").map(Lt=>parseInt(Lt,10)):[],rt=At?{from:tr,to:kt}:void 0;Rr={type:"byteRange",url:Jt,initRange:Ne,indexRange:rt}}else if(ge){let dt={representationId:(zc=z.getAttribute("id"))!=null?zc:void 0,bandwidth:(Kc=z.getAttribute("bandwidth"))!=null?Kc:void 0},Ge=parseInt((Xc=ge.getAttribute("timescale"))!=null?Xc:"",10),er=(Jc=ge.getAttribute("initialization"))!=null?Jc:"",Ne=ge.getAttribute("media"),At=(ed=parseInt((Zc=ge.getAttribute("startNumber"))!=null?Zc:"",10))!=null?ed:1,tr=St(er,dt);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let kt=(td=ge.querySelectorAll("SegmentTimeline S"))!=null?td:[],rt=[],Lt=0,$r="",yi=0;if(kt.length){let ms=At,We=0;for(let Mr of kt){let it=parseInt((rd=Mr.getAttribute("d"))!=null?rd:"",10),rr=parseInt((id=Mr.getAttribute("r"))!=null?id:"",10)||0,fs=parseInt((ad=Mr.getAttribute("t"))!=null?ad:"",10);We=Number.isFinite(fs)?fs:We;let so=it/Ge*1e3,no=We/Ge*1e3;for(let bs=0;bs<rr+1;bs++){let rI=St(Ne,R(I({},dt),{segmentNumber:ms.toString(10),segmentTime:(We+bs*it).toString(10)})),od=(no!=null?no:0)+bs*so,iI=od+so;ms++,rt.push({time:{from:od,to:iI},url:rI})}We+=(rr+1)*it,Lt+=(rr+1)*so}yi=We/Ge*1e3,$r=St(Ne,R(I({},dt),{segmentNumber:ms.toString(10),segmentTime:We.toString(10)}))}else if(PD(d)){let We=parseInt((sd=ge.getAttribute("duration"))!=null?sd:"",10)/Ge*1e3,Mr=Math.ceil(d/We),it=0;for(let rr=1;rr<Mr;rr++){let fs=St(Ne,R(I({},dt),{segmentNumber:rr.toString(10),segmentTime:it.toString(10)}));rt.push({time:{from:it,to:it+We},url:fs}),it+=We}yi=it,$r=St(Ne,R(I({},dt),{segmentNumber:Mr.toString(10),segmentTime:it.toString(10)}))}let tI={time:{from:yi,to:1/0},url:$r};Rr={type:"template",baseUrl:Jt,segmentTemplateUrl:Ne,initUrl:tr,totalSegmentsDurationMs:Lt,segments:rt,nextSegmentBeyondManifest:tI,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!wt||!Pt)continue;let Si={video:"video",audio:"audio",text:"text"}[wt];if(!Si)continue;Ar||(Ar=Si),os={id:ps,kind:Si,segmentReference:Rr,profiles:hs,duration:d,bitrate:ls,mime:Pt,codecs:ns,width:Zt,height:gi,fps:ao,quality:kr}}te.language||(te.language=xt),te.label||(te.label=bi),te.mime||(te.mime=Pt),te.codecs||(te.codecs=ns),te.hdr||(te.hdr=Ar==="video"&&Hl(ns)),te.representations.push(os)}if(Ar){let z=i[Ar].find(xt=>xt.id===te.id);if(z&&te.representations.every(xt=>Se(xt.segmentReference)))for(let xt of z.representations){let bi=te.representations.find(Pt=>Pt.id===xt.id),ss=bi==null?void 0:bi.segmentReference,Jt=xt.segmentReference;Jt.segments.push(...ss.segments),Jt.nextSegmentBeyondManifest=ss.nextSegmentBeyondManifest}else i[Ar].push(te)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var Vy=V(Xe(),1);import{isNonNullable as Cy}from"@vkontakte/videoplayer-shared/es2015";var ye=(a,e)=>Cy(a)&&Cy(e)&&a.readyState==="open"&&(0,Vy.default)([...a.activeSourceBuffers],e);var Va=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gr(0);this.currentLowLatencySegmentLength$=new gr(0);this.currentSegmentLength$=new gr(0);this.onLastSegment$=new gr(!1);this.fullyBuffered$=new gr(!1);this.playingRepresentation$=new gr(void 0);this.playingRepresentationInit$=new gr(void 0);this.error$=new kD;this.gaps=[];this.subscription=new LD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new he;this.switchAbortController=new he;this.destroyAbortController=new he;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ht(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){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 $S(this.sourceBuffer),this.subscription.add(Jl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:jt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:jt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Jl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:jt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ye(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Vl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=lt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Re(r,"No init buffer for starting representation"),Re(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=Ht(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Re(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(me(s)||me(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Re(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ye(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();oi(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new vs(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Ht(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Re(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(me(s)||me(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Re(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ye(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();oi(n)&&(this.isLive||(this.bufferLimit=1/0,yield new vs(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Ht(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){var u,l;let t=(u=(0,Ln.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Se(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);Re(i);let s=this.segments.get(r);Re(s,"No segments for starting representation");let n=this.initData.get(r);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,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new he,Ht(this.switchAbortController.signal,function(r,i=!1){return ae(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);Re(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(me(o)||me(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),Re(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();oi(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!me(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return A(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new he,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(me(e)||me(this.downloadingRepresentationId)||me(this.playingRepresentationId)||me(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer)||oi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);oi(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=lt(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Vl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=lt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,kn.default)(o,i))l="high";else{let c=(0,ui.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&lt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ui.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;oi(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,Ln.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,Ln.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Se(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>R(I({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ui.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Se(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=St(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&oa&&oa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&oa&&oa(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&ye(this.mediaSource,this.sourceBuffer)&&!(qt(this.sourceBuffer.buffered,p)&&qt(this.sourceBuffer.buffered,h)))&&g&&S});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return A(this,null,function*(){Se(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return A(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ht(o,function(){return ae(this,null,function*(){let c=Zl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=An(),!c)return;let d=new DataView(c),p=Da(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ca(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())Se(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return A(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Ht(n,function(){return ae(this,null,function*(){let u=Zl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Jl(window,"online").pipe(AD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=An(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ca(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Se(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ui.default)(e,0).byte.from,to:(0,ui.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>A(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=An(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:jt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!Se(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=An();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:jt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,kn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return A(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Da(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return A(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<i,b=p<=i;if(!m)continue;let g=Da(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(me(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer))){!this.isLive&&wD.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:jt.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",Yl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Ml(()=>(0,By.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return A(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ht(this.destroyAbortController.signal,function(){return ae(this,null,function*(){let o=Zl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Da(e.mime),i)).then(o=>A(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Se(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:jt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return A(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return A(this,null,function*(){if(!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||me(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(I({},u.time)),i=n(i);let l=Yl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,kn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return A(this,null,function*(){if(!this.sourceBuffer||!ye(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||!ye(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||me(e)?0:lt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Ml(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:jt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(me(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer)||me(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Ba=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Oy=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Oa,assertNever as Ny,fromEvent as Fy,merge as RD,now as _a,Subscription as $D,ValueSubject as ec,flattenObject as li}from"@vkontakte/videoplayer-shared/es2015";var _y=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Rn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new ec(void 0);this.lastConnectionReused$=new ec(void 0);this.lastRequestFirstBytes$=new ec(void 0);this.abortAllController=new he;this.subscription=new $D;this.fetchManifest=Oa(this.abortAllController.signal,function(e){return ae(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ba(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=_y(r));let i=yield Ze(r,{signal:this.abortAllController.signal}).catch(Na);return i?(t.log("success",li({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",li({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Oa(this.abortAllController.signal,function(l){return ae(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,U;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(c,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),c=_.toString();break}default:Ny(t)}this.requestQuic&&(c=Ba(c));let h=this.abortAllController.signal,m;if(n){let _=new he;if(m=RD(Fy(this.abortAllController.signal,"abort"),Fy(n,"abort")).subscribe(()=>{try{_.abort()}catch(Y){Na(Y)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(Y){Na(Y)}h=_.signal}let b=_a();p.log("startRequest",li({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield Ze(c,{priority:s,headers:d,signal:h}).catch(Na),v=_a();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:_}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){m==null||m.unsubscribe();let _=_a(),Y={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",li(Y)),p.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),P=S.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(y,u));let E=0,$=new Uint8Array(0),C=!1,Z=_=>{m==null||m.unsubscribe(),C=!0,Na(_)},M=Oa(h,function(k){return ae(this,arguments,function*({done:_,value:Y}){if(E===0&&this.lastRequestFirstBytes$.next(_a()-b),h.aborted){m==null||m.unsubscribe();return}if(!_&&Y){let T=new Uint8Array($.length+Y.length);T.set($),T.set(Y,$.length),$=T,E+=Y.byteLength,i==null||i(new DataView($.buffer),E),yield P==null?void 0:P.read().then(M,Z)}})}.bind(this));yield P==null?void 0:P.read().then(M,Z),m==null||m.unsubscribe();let F=_a(),q={failed:C,requestStartedAt:b,requestEndedAt:F,duration:F-b};return C?(p.error("endRequest",li(q)),p.end(),null):(p.log("endRequest",li(q)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Oa(this.abortAllController.signal,function(e,t,r){return ae(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Oa(this.abortAllController.signal,function(e,t){return ae(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>R(I({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=Oy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return A(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Ny(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Na=a=>{if(!Ca(a))throw a};var vr=(a,e,t)=>t*e+(1-t)*a,tc=(a,e)=>a.reduce((t,r)=>t+r,0)/e,qy=(a,e,t,r)=>{let i=0,s=t,n=tc(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as MD,ValueSubject as Uy}from"@vkontakte/videoplayer-shared/es2015";var Qt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Uy(e.initial),this.debounced$=new Uy(e.initial);let t=(r=e.label)!=null?r:"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,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=at(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(MD(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 $n=class extends Qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vr(this.slow,e,this.params.emaAlphaSlow),this.fast=vr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Mn=class extends Qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=tc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vr(this.emaSmoothed,e,this.params.emaAlpha);let r=qy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Dn=class extends Qt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?vr(this.smoothed,t,this.params.emaAlpha):t}};var Sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new $n({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Mn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Dn(I({initial:e,label:"liveEdgeDelay"},t))}};var rc=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as DD,ValueSubject as CD}from"@vkontakte/videoplayer-shared/es2015";var Fa=class a{constructor(e,t){this.currentRepresentation$=new CD(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(!DD(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(R(I({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Se(t.segmentReference))}};var UD=["timeupdate","progress","play","seeked","stalled","waiting"],HD=["timeupdate","progress","loadeddata","playing","seeked"];var Vn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Gy;this.representationSubscription=new Gy;this.state$=new D("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new Qy;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.currentLiveTextRepresentation$=new ie(null);this.isLive$=new ie(!1);this.liveDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLatency$=new ie(void 0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.isLowLatency$=new ie(!1);this.isActiveLowLatency$=new ie(!1);this.currentStallDuration$=new ie(0);this.videoLastDataObtainedTimestamp$=new ie(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Qy;this.gapWatchdogActive=!1;this.destroyController=new he;this.initManifest=ic(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=pe(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Gt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ic(this.destroyController.signal,function(){return ae(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Gt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Dy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=PS(e))!=null?n:{id:"ManifestParsing",category:Gt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=gt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=iS(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);OD.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=R(I({},t),{streams:i});return this.tracer.log("updateManifestEnd",Ua(s)),s})}.bind(this));this.initRepresentations=ic(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",Ua({initialVideo:e,initialAudio:t,sourceHls:r})),yr(this.manifest),yr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Tr(p,"error").pipe(qa(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Gt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Fv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&bn())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Va("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],jy(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Va("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Fa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Fa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ac(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=tn(this.manifestUrlString,2);this.manifestUrlString=pe(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ir(...HD.map(p=>Tr(this.element,p))).pipe(Ha(p=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),Cn(),FD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ir(Tr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Cn()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||rc(this.element,1)})),this.representationSubscription.add(ci({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(qa(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(ci({isActiveLowLatency:this.isActiveLowLatency$.pipe(Cn()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(qa(({isActiveLowLatency:h,currentLowLatencySegmentLength:m})=>h&&!!m)).subscribe(({currentLowLatencySegmentLength:h})=>{let m=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(ci({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(qa(({isLive:h})=>h),Ha(h=>I({},h)),Cn((h,m)=>m.bufferLength<h.bufferLength),Ha(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let g=tn(this.manifestUrlString,2);return(h/2+m+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ci({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:m})=>{if(!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=h-b;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(S)>g&&(y=1+Math.sign(S)*v),rc(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let m=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var P,E;return(E=(P=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:P.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(ci({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(qD(1e3)).subscribe(b=>A(this,[b],function*({liveLoadBufferLength:h,bufferLength:m}){if(yr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=tn(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),P=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(h)?h:m,C=this.isActiveLowLatency$.getValue(),Z=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(C&&Z);let M="none";if(C?M="active_low_latency":this.isLowLatency$.getValue()&&Z?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),M="active_low_latency"):v!==0&&$<y?M="live_forward_buffering":$<y+E&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let F=p-(y+P),q=this.normolizeLiveOffset(Math.trunc(v+F/g)),L=Math.abs(q-v),U;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?U=v:q>0&&L>this.tuning.dashCmafLive.offsetCalculationError?U=q:U=0,this.manifestUrlString=pe(this.manifestUrlString,U,2)}M!=="none"&&M!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=Ir(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ha(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Ir(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ha(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(Ir(this.forceEnded$,ci({allBuffersFull:l,someBufferEnded:c}).pipe(qa(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:Gt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ir(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,sc.default)((0,sc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Se(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&jy(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ac(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Gt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Rn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Sr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,I({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return A(this,null,function*(){var r,i,s;yr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=pe(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){yr(this.element),this.state$.setState("running"),this.subscription.add(Ir(...UD.map(e=>Tr(this.element,e)),Tr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Gt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Tr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Tr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,S,y,P,E,$;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=ND(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(P=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?P:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let C=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(C),($=this.audioBufferManager)==null||$.maintain(C),i.position=C}this.tracer.log("stallIntervalCallback",Ua(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=ac(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Gt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return A(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)})}seek(e,t){return A(this,null,function*(){var i,s,n,o,u;yr(this.element),yr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),qt(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Ua({requestedPosition:e,forcePrecise:t,position:r}))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=_D(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return A(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=R(I({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Ua(t)))}}};var Bn=class{constructor(e,t){this.fov=e,this.orientation=t}};var On=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/at(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=I({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*at(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Wy=`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 _y=`#ifdef GL_ES
81
+ `;var Yy=`#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 Bn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Dn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Cn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Oy,this.gl.VERTEX_SHADER),r=this.createShader(_y,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as BD,now as Ny,Subscription as VD,filter as OD,combine as Fy,ValueSubject as rc,isNonNullable as _D}from"@vkontakte/videoplayer-shared/es2015";var ic=class{constructor(){this.isSeeked$=new rc(!1);this.isBuffering$=new rc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new VD;this.severeStallOccurred$=new rc(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(Fy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(OD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Fy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(BD(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=Ny(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,_D(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Ny(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},qy=ic;import{combine as ND,map as FD,observeElementSize as qD,Subscription as UD,ValueSubject as ac,noop as HD}from"@vkontakte/videoplayer-shared/es2015";var Vn=class{constructor(){this.subscription=new UD;this.pipSize$=new ac(void 0);this.videoSize$=new ac(void 0);this.elementSize$=new ac(void 0);this.pictureInPictureWindowRemoveEventListener=HD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(qD(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(ND({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(FD(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Er=class{constructor(e){this.subscription=new KD;this.videoState=new C("stopped");this.droppedFramesManager=new ln;this.stallsManager=new qy;this.elementSizeManager=new Vn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Yi;this.audioTrackSwitchHistory=new Yi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return QD(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Bn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Mn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=we(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:sc.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Uy(c=>!!c.length),jy()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(nc(c=>c.to.state!=="none"),ja());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ja()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Uy(Hy),jy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(nc(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Fe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(WD(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Ul(f));let b=[];for(let g of f.representations){let v=my(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Hl(h));let f=[];for(let b of h.representations){let g=fy($(I({},b),{streamId:h.id}));g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let f of h.representations){let b=by(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:sc.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(On(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,zD(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Gy.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(v=>{var S;return((S=this.videoTracksMap.get(v))==null?void 0:S.representation.id)===h.id});Hy(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,v).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ja()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Hl(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ja()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Ul(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(nc(({to:c})=>c==="ready"),ja());this.subscription.add(On(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,oc(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(On(u,this.player.state$.stateChangeEnded$,oc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=On(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,oc(["init"])).pipe(YD(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var B,Z,M,F,q,R,U,_,Y,k,T,D,W;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(B=e.videoTrack.getState())==null?void 0:B.id,n=[...this.videoTracksMap.keys()].find(({id:j})=>j===i),o=t.currentVideoTrack$.getValue(),u=((F=(M=e.videoStream.getState())!=null?M:n&&((Z=this.videoTracksMap.get(n))==null?void 0:Z.stream))!=null?F:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:j})=>j===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(p,h||1/0),1),b=(q=e.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(R=[...this.audioStreamsMap.keys()].find(({id:j})=>j===(b==null?void 0:b.id)))!=null?R:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let j=sn(n,c,(U=this.audioStreamsMap.get(g))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(_=j==null?void 0:j.bitrate)!=null?_:-1/0)}if(o){let j=sn(o,c,(Y=this.audioStreamsMap.get(g))!=null?Y:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=j==null?void 0:j.bitrate)!=null?k:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=r?S!=null?S:n:n!=null?n:S,x=g&&Wg(y,c,(T=this.audioStreamsMap.get(g))!=null?T:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(D=this.videoTracksMap.get(y))==null?void 0:D.representation,L=x&&((W=this.audioTracksMap.get(x))==null?void 0:W.representation);if(E&&L)return[E,L];if(E&&!L&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sc.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),xe(this.video),this.tracer.end()}};var Ga=class extends Er{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Qy,interval as XD,map as Wy}from"@vkontakte/videoplayer-shared/es2015";var Qa=class extends Er{constructor(e){super(e),this.liveOffset=new mt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(Wy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Qy({interval:XD(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(Qy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Wy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=gy(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var zy=O(Zs(),1);import{assertNever as Wa,assertNonNullable as Yy,debounce as JD,ErrorCategory as _n,filter as ZD,isNonNullable as e0,isNullable as t0,map as Nn,merge as r0,Observable as i0,observableFrom as a0,Subscription as s0,videoSizeToQuality as n0}from"@vkontakte/videoplayer-shared/es2015";var tt={};var pi=(a,e)=>new i0(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ya=class{constructor(e){this.subscription=new s0;this.videoState=new C("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Wa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Wa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Wa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Wa(e)}break;default:Wa(t)}};this.textTracksManager=new qe(e.source.url),this.video=Ee(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:_n.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,zy.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Yy(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Yy(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:_n.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=we(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,r)),this.subscription.add(Pe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Fe(this.video,e.playbackRate,i.playbackRateState$,r)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Nn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(pi(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:_n.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(pi(this.hls,tt.Events.MANIFEST_PARSED).pipe(Nn(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(y=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?y:n0({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(pi(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(pi(this.hls,tt.Events.LEVEL_LOADING).pipe(Nn(({url:l})=>ue(l))),t.hostname$),s(pi(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Bt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=pi(this.hls,tt.Events.LEVEL_SWITCHED).pipe(Nn(({level:l})=>n(this.hls.levels[l])));o.pipe(ZD(e0)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Bt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(t0(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=r0(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a0(["init"])).pipe(JD(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return w(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_n.DOM,thrown:t})))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0)}};var Ky="X-Playback-Duration",uc=a=>w(void 0,null,function*(){var i;let e=yield Ze(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Ky)?parseInt(e.headers.get(Ky),10):void 0});import{assertNever as g0,combine as v0,debounce as S0,ErrorCategory as Un,filter as y0,filterChanged as T0,isNonNullable as Zy,isNullable as Hn,map as eT,merge as I0,observableFrom as E0,Subscription as x0,ValueSubject as dc,VideoQuality as P0}from"@vkontakte/videoplayer-shared/es2015";var cc=O(hu(),1);import{videoSizeToQuality as o0,getExponentialDelay as u0}from"@vkontakte/videoplayer-shared/es2015";var l0=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=o0({width:t,height:r})}return e!=null?e:null},c0=(a,e)=>{var s,n;let t=a.split(`
125
- `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,cc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=l0(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[S,y]=d.RESOLUTION.split("x").map(x=>parseInt(x,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(c){let d=(0,cc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},d0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),lc=0,Xy=(i,...s)=>w(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield Ze(a,r)).text();lc+=1;try{let{qualityManifests:u,textTracks:l}=c0(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(lc<=t.manifestRetryMaxCount)return yield d0(u0(lc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Xy(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Fn=Xy;import{isNonNullable as p0,Subscription as h0,throttle as f0,ValueSubject as Jy,Subject as m0,ErrorCategory as b0}from"@vkontakte/videoplayer-shared/es2015";var qn=class{constructor(e,t,r,i,s){this.subscription=new h0;this.abortControllers={destroy:new me,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Jy(null);this.getCurrentTime$=new Jy(null);this.error$=new m0;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(f0(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return w(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return w(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return w(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield Ze(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
126
- `),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(p0(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([$(I({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return w(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return w(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:b0.WTF,thrown:t,message:e})}};var za=class{constructor(e){this.subscription=new x0;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new dc([]);this.liveOffset=new mt;this.manifestStartTime$=new dc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return g0(t)}};var r;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:P0.INVARIANT,url:this.params.source.url};let t=(i,s)=>Fn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new qn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new qe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Un.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Un.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new dc((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(T0(),eT(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Zy(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(v0({startTime:this.manifestStartTime$.pipe(y0(Zy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(eT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=I0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,E0(["init"])).pipe(S0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Hn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=fe(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),uc(n).then(c=>{var d;if(!Hn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Hn(p)||!isFinite(p))&&Ze(n).then(h=>h.text()).then(h=>{var b;let f=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(f){let g=new URL(f,n).toString();uc(g).then(v=>{Hn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Un.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=fe(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as w0,debounce as A0,ErrorCategory as pc,fromEvent as hc,isNonNullable as k0,isNullable as R0,map as tT,merge as rT,observableFrom as iT,Subscription as $0,ValueSubject as L0,VideoQuality as M0,clientChecker as D0}from"@vkontakte/videoplayer-shared/es2015";var Ka=class{constructor(e){this.subscription=new $0;this.videoState=new C("stopped");this.manifests$=new L0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return w0(t)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:M0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Fn(fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:pc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:pc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(tT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&k0(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===f);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(ue(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(tT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!D0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(rT(hc(o,"addtrack"),hc(o,"removetrack"),hc(o,"change"),iT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=rT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,iT(["init"])).pipe(A0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(R0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var oT=O(Ur(),1),Xa=O(Zr(),1);import{assertNever as C0,assertNonNullable as aT,debounce as B0,ErrorCategory as sT,isHigher as V0,isHigherOrEqual as O0,isInvariantQuality as nT,isLowerOrEqual as _0,isNonNullable as N0,merge as F0,observableFrom as q0,Subscription as U0,map as H0}from"@vkontakte/videoplayer-shared/es2015";var Ja=class{constructor(e){this.subscription=new U0;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new qe;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return C0(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,oT.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Xa.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:sT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(H0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&N0(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=F0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,q0(["init"])).pipe(B0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),xe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;aT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];aT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ba(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Xa.default)(this.trackUrls).find(d=>!nT(d.track.quality)&&_0(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&O0(c.quality,u.quality)&&(t=u),!t){let d=(0,Xa.default)(this.trackUrls).filter(h=>!nT(h.track.quality)&&V0(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Xa.default)(this.trackUrls).map(l=>l.track);t=Ft(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as lT,debounce as W0,merge as cT,observableFrom as Y0,Subscription as z0,map as dT,ValueSubject as K0,ErrorCategory as mc,VideoQuality as X0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as j0}from"@vkontakte/videoplayer-shared/es2015";var uT=["stun:videostun.mycdn.me:80"],G0=1e3,Q0=3,fc=()=>null,jn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=fc;this.externalStopCallback=fc;this.externalErrorCallback=fc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return w(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return w(this,null,function*(){try{let e={iceServers:[{urls:uT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return w(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return w(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:j0.WTF,message:e.message})}onPeerConnectionStream(e){return w(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return w(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),G0)}normalizeOptions(e={}){let t={stunServerList:uT,maxRetryNumber:Q0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Za=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new K0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return lT(e)}};this.subscription=new z0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new jn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:mc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};cT(this.videoState.stateChangeStarted$.pipe(dT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(dT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=we(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(He(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Pe(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return lT(n.to)}},r)).add(cT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Y0(["init"])).pipe(W0(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:X0.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:mc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var es=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as rs,assertNonNullable as Wt,ErrorCategory as Gn,filter as gT,isNonNullable as vT,isNullable as sC,map as nC,merge as oC,once as uC,Subject as Le,Subscription as ST,ValueSubject as V,flattenObject as yT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as J0,map as pT,Subscription as Z0,Subject as eC}from"@vkontakte/videoplayer-shared/es2015";var hT=a=>new J0(e=>{let t=new Z0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(pT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(pT(({type:l})=>l!==void 0)),n=new eC,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as tC,Subscription as rC,combine as iC,filter as mT,once as bT}from"@vkontakte/videoplayer-shared/es2015";function fT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as aC}from"@vkontakte/videoplayer-shared/es2015";var ts=class ts{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new me;this.subscriptions=new rC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(mT(s=>!!s.type),bT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){aC.isSafari&&e!=="MPEG"||this.subscriptions.add(iC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(mT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),bT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return w(this,null,function*(){let{volumeMultiplier:t}=this,r=fT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:ts.errorId,category:tC.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${ts.errorId} exception`,thrown:e})}};ts.errorId="VolumeMultiplierManager";var hi=ts;var lC={chunkDuration:5e3,maxParallelRequests:5},is=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new Le;this.noAvailableProvidersError$=new Le;this.volumeMultiplierError$=new Le;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new Le,warning$:new Le,willSeekEvent$:new Le,soundProhibitedEvent$:new Le,seekedEvent$:new Le,loopedEvent$:new Le,endedEvent$:new Le,firstBytesEvent$:new Le,loadedMetadataEvent$:new Le,firstFrameEvent$:new Le,canplay$:new Le,isLive$:new V(void 0),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new ST;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=jv([...Qv(this.params.tuning),...Gv(this.params.tuning)],this.params.tuning).filter(l=>vT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,bc.default)(i,l)),...t.filter(l=>(0,bc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",yT(s)),this.screenFormatsIterator=new es(s);let n=[...El(!0),...El(!1)];this.chromecastFormatsIterator=new es(n.filter(l=>vT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&hi.isSupported()&&(this.volumeMultiplierManager=new hi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(sC(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Gn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return rs(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Wt(o),new Ga($(I({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Qa($(I({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Wt(o),si||!this.params.tuning.useHlsJs?new Ka($(I({},n),{source:o})):new Ya($(I({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new za($(I({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Ja($(I({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new uv($(I({},n),{source:o,config:$(I({},lC),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Za({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return rs(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Wt(o),new ji({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return rs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return rs(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return rs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return $(I({},e),{url:r(e.url)})}return(0,IT.default)((0,TT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new ST,t=!1,r=0;return e.add(oC(this.providerOutput.error$.pipe(gT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),hT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(nC(i=>({id:`ProviderHangup:${i}`,category:Gn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(gT(({to:s})=>s==="playing"),uC()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Gn.NETWORK,u=i.category===Gn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=$(I({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",yT(n))})),e}};import{fromEvent as Qn,once as cC,combine as dC,Subscription as ET,ValueSubject as gc,map as pC,filter as hC,isNonNullable as Wn,now as Ve,safeStorage as vc}from"@vkontakte/videoplayer-shared/es2015";var fC=5e3,xT="one_video_throughput",PT="one_video_rtt",yt=window.navigator.connection,wT=()=>{let a=yt==null?void 0:yt.downlink;if(Wn(a)&&a!==10)return a*1e3},AT=()=>{let a=yt==null?void 0:yt.rtt;if(Wn(a)&&a!==3e3)return a},kT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Sc=class a{constructor(e){this.subscription=new ET;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(xT)||(e.useBrowserEstimation?wT():void 0)||fC,r=(s=(i=a.load(PT))!=null?i:e.useBrowserEstimation?AT():void 0)!=null?s:0;if(this.throughput$=new gc(t),this.rtt$=new gc(r),this.rttAdjustedThroughput$=new gc(kT(t,r,e.rttPenaltyRequestSize)),this.throughput=Sr.getSmoothedValue(t,-1,e),this.rtt=Sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=wT();u&&this.throughput.next(u);let l=AT();Wn(l)&&this.rtt.next(l)};yt&&"onchange"in yt&&this.subscription.add(Qn(yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{vc.set(xT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{vc.set(PT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dC({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(pC(({throughput:n,rtt:o})=>kT(n,o,e.rttPenaltyRequestSize)),hC(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Ve(),i=new ET;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Qn(e,"progress").pipe(cC()).subscribe(s=>{t=s.loaded,r=Ve()}));break;case 1:case 0:i.add(Qn(e,"loadstart").subscribe(()=>{t=0,r=Ve()}));break}i.add(Qn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ve(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Ve(),n=0,o=Ve(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>w(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Ve();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Ve()}else n+=d.byteLength;o=Ve()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ve()-o,this.concurrentDownloads.size),n=0,o=Ve());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=vc.get(e);if(Wn(t))return(r=parseInt(t,10))!=null?r:void 0}},RT=Sc;import{fillWithDefault as mC,VideoQuality as $T}from"@vkontakte/videoplayer-shared/es2015";var LT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:$T.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:$T.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},MT=a=>{var e;return $(I({},mC(a,LT)),{configName:[...(e=a.configName)!=null?e:[],...LT.configName]})};import{assertNonNullable as Yn,combine as Tt,ErrorCategory as zn,filter as Te,filterChanged as Q,fromEvent as Tc,isNonNullable as IC,isNullable as EC,Logger as xC,map as H,mapTo as VT,merge as Yt,now as Kn,once as ct,Subject as X,Subscription as OT,tap as _T,ValueSubject as A,isHigher as PC,isInvariantQuality as NT,flattenObject as zt,throttle as Ic,getTraceSubscriptionMethod as FT,Tracer as wC,InternalsExposure as AC}from"@vkontakte/videoplayer-shared/es2015";import{merge as bC,map as gC,filter as DT,isNonNullable as vC}from"@vkontakte/videoplayer-shared/es2015";var yc=({seekState:a,position$:e})=>bC(a.stateChangeEnded$.pipe(gC(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),DT(vC)),e.pipe(DT(()=>a.getState().state==="none")));import{assertNonNullable as SC}from"@vkontakte/videoplayer-shared/es2015";var CT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return SC(e,`Wrong container or containerId {${a.container}}`),e};import{filter as yC,once as TC}from"@vkontakte/videoplayer-shared/es2015";var BT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(yC(i=>i.length>0),TC()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Xn=class{constructor(e={configName:[]},t=wC.createRootTracer(!1)){this.subscription=new OT;this.logger=new xC;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new A("stopped"),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new X,ready$:new X,started$:new X,playing$:new X,paused$:new X,stopped$:new X,willStart$:new X,willResume$:new X,willPause$:new X,willStop$:new X,willDestruct$:new X,watchCoverageRecord$:new X,watchCoverageLive$:new X,managedError$:new X,fatalError$:new X,ended$:new X,looped$:new X,seeked$:new X,willSeek$:new X,autoplaySoundProhibited$:new X,firstBytes$:new X,loadedMetadata$:new X,firstFrame$:new X,canplay$:new X,log$:new X};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Og,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=MT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ps({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new RT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new AC("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,qT.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:zn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=sd(i,["container"]);return this.tracer.log("initVideo",zt(r)),this.domContainer=CT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new is({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Zi()?(this.tracer.log("request play from hidden tab"),Tc(document,"visibilitychange").pipe(ct()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Yn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Te(r=>r.length>0),ct()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",zt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Yn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",zt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>I({type:"external"},t))),this}selectTextTrack(e){var t;return BT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",I({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(EC(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return IC(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Te(({from:e})=>e==="stopped"),ct()).subscribe(()=>{this.initedAt=Kn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",zt(n)),n.state==="requested"?this.desiredState.seekState.setState($(I({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:zn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ct()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",zt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(H(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(H(n=>n.destination),Q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Tt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(H(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>NT(u)?1:NT(l)?-1:PC(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(Q()).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(Q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Q()).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(H(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Tt({hasLiveOffsetByPaused:Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(n=>n.to),Q(),H(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Tt({atLiveEdge:Tt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:yc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(H(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Q(),_T(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(H(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Tt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(H(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Q(),_T(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(H(n=>n.muted),Q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(H(n=>n.volume),Q()).subscribe(this.info.volume$)).add(yc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Yt(e.providerOutput.endedEvent$.pipe(VT(!0)),e.providerOutput.seekedEvent$.pipe(VT(!1))).pipe(Q()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(H(n=>({id:n?`No${n}`:"NoProviders",category:zn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(ct(),H(n=>n!=null?n:Kn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ct(),H(()=>Kn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ct(),H(()=>Kn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new A(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Te(({to:n})=>n==="playing"),ct()).subscribe(()=>r.next(!1)));let i=0,s=Yt(e.providerOutput.isBuffering$,t,r).pipe(H(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),Q());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Yt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Yt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(H(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new OT;this.subscription.add(t),this.subscription.add(e.current$.pipe(Q((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Te(r=>r.length>0),ct()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Yt(this.desiredState.videoTrack.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(H(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Yn(this.providerContainer),Yn(e),Vg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Bg(r)),this.providerContainer.current$.subscribe(({type:r})=>Wi("provider",r)),e.duration$.subscribe(r=>Wi("duration",r)),e.availableVideoTracks$.pipe(Te(r=>!!r.length),ct()).subscribe(r=>Wi("tracks",r)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(H(r=>r==null?void 0:r.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(r=>this.subscription.add(r)),Wi("codecs",Hv())}initTracerSubscription(){let e=FT(this.tracer.log.bind(this.tracer)),t=FT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(Q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Tt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Te(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),Q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Te(r=>r>0),Q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Te(r=>r>0),Q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Tt({currentBuffer:this.info.currentBuffer$.pipe(Te(r=>r.end>0),Q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(Q())}).pipe(Ic(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Q()).subscribe(e("canChangePlaybackSpeed"))).add(Tt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Te(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Ic(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Q(),Te(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Q(),Te(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Q()).subscribe(e("muted"))).add(this.info.volume$.pipe(Q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Q(),Te(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Tt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Te(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Ic(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Q(),Te(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>w(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:zn.DOM,message:String(i)})})});this.subscription.add(Yt(Tc(document,"visibilitychange"),Tc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",zt({quality:t,availableTracks:zt(e),track:zt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as U4,Observable as H4,Subject as j4,ValueSubject as G4,VideoQuality as Q4}from"@vkontakte/videoplayer-shared/es2015";var W4=`@vkontakte/videoplayer-core@${nd}`;export{Ss as ChromecastState,so as HttpConnectionType,H4 as Observable,Ie as PlaybackState,Xn as Player,W4 as SDK_VERSION,j4 as Subject,U4 as Subscription,no as Surface,nd as VERSION,G4 as ValueSubject,Lt as VideoFormat,Q4 as VideoQuality};
124
+ `;var _n=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Bn(this.params.fov,this.params.orientation),this.cameraRotationManager=new On(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Wy,this.gl.VERTEX_SHADER),r=this.createShader(Yy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as GD,now as zy,Subscription as WD,filter as YD,combine as Ky,ValueSubject as nc,isNonNullable as zD}from"@vkontakte/videoplayer-shared/es2015";var oc=class{constructor(){this.isSeeked$=new nc(!1);this.isBuffering$=new nc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new WD;this.severeStallOccurred$=new nc(!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(Ky({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(YD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Ky({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(GD(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=zy(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,zD(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=zy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Xy=oc;import{combine as KD,map as XD,observeElementSize as JD,Subscription as ZD,ValueSubject as uc,noop as e0}from"@vkontakte/videoplayer-shared/es2015";var Nn=class{constructor(){this.subscription=new ZD;this.pipSize$=new uc(void 0);this.videoSize$=new uc(void 0);this.elementSize$=new uc(void 0);this.pictureInPictureWindowRemoveEventListener=e0}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(JD(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(KD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(XD(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Er=class{constructor(e){this.subscription=new o0;this.videoState=new D("stopped");this.droppedFramesManager=new pn;this.stallsManager=new Xy;this.elementSizeManager=new Nn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new zi;this.audioTrackSwitchHistory=new zi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return i0(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new _n(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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 Vn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=we(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:lc.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Jy(c=>!!c.length),eT()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(cc(c=>c.to.state!=="none"),Qa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Qa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Jy(Zy),eT()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(cc(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Fe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(a0(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of d.audio){h.push(Gl(m));let b=[];for(let g of m.representations){let v=Py(g);b.push(v),this.audioTracksMap.set(v,{stream:m,representation:g})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Wl(h));let m=[];for(let b of h.representations){let g=xy(R(I({},b),{streamId:h.id}));g&&(m.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let m of h.representations){let b=wy(h,m);this.textTracksMap.set(b,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:lc.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Fn(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$,n0(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,tT.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,b=[...this.videoTracksMap.keys()].find(v=>{var S;return((S=this.videoTracksMap.get(v))==null?void 0:S.representation.id)===h.id});Zy(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,v).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Qa()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Wl(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qa()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Gl(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(cc(({to:c})=>c==="ready"),Qa());this.subscription.add(Fn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Fn(u,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Fn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dc(["init"])).pipe(s0(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var C,Z,M,F,q,L,U,_,Y,k,T,O,W;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(C=e.videoTrack.getState())==null?void 0:C.id,n=[...this.videoTracksMap.keys()].find(({id:j})=>j===i),o=t.currentVideoTrack$.getValue(),u=((F=(M=e.videoStream.getState())!=null?M:n&&((Z=this.videoTracksMap.get(n))==null?void 0:Z.stream))!=null?F:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:j})=>j===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),b=(q=e.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(L=[...this.audioStreamsMap.keys()].find(({id:j})=>j===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let j=un(n,c,(U=this.audioStreamsMap.get(g))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(_=j==null?void 0:j.bitrate)!=null?_:-1/0)}if(o){let j=un(o,c,(Y=this.audioStreamsMap.get(g))!=null?Y:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=j==null?void 0:j.bitrate)!=null?k:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=r?S!=null?S:n:n!=null?n:S,P=g&&tv(y,c,(T=this.audioStreamsMap.get(g))!=null?T:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(O=this.videoTracksMap.get(y))==null?void 0:O.representation,$=P&&((W=this.audioTracksMap.get(P))==null?void 0:W.representation);if(E&&$)return[E,$];if(E&&!$&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(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}))}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 Ga=class extends Er{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as rT,interval as u0,map as iT}from"@vkontakte/videoplayer-shared/es2015";var Wa=class extends Er{constructor(e){super(e),this.liveOffset=new ft,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(iT(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(rT({interval:u0(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(rT({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(iT(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Ay(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var sT=V(en(),1);import{assertNever as Ya,assertNonNullable as aT,debounce as l0,ErrorCategory as qn,filter as c0,isNonNullable as d0,isNullable as p0,map as Un,merge as h0,Observable as m0,observableFrom as f0,Subscription as b0,videoSizeToQuality as g0}from"@vkontakte/videoplayer-shared/es2015";var tt={};var di=(a,e)=>new m0(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),za=class{constructor(e){this.subscription=new b0;this.videoState=new D("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ya(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ya(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ya(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ya(e)}break;default:Ya(t)}};this.textTracksManager=new qe(e.source.url),this.video=Ee(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:qn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,sT.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){aT(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){aT(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:qn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=we(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,r)),this.subscription.add(Pe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Fe(this.video,e.playbackRate,i.playbackRateState$,r)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Un(l=>l.to)),this.params.output.playbackState$),this.subscription.add(di(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:qn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(di(this.hls,tt.Events.MANIFEST_PARSED).pipe(Un(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(y=Ot((S=d.attrs.QUALITY)!=null?S:""))!=null?y:g0({width:h,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(di(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(di(this.hls,tt.Events.LEVEL_LOADING).pipe(Un(({url:l})=>oe(l))),t.hostname$),s(di(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Ct(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=di(this.hls,tt.Events.LEVEL_SWITCHED).pipe(Un(({level:l})=>n(this.hls.levels[l])));o.pipe(c0(d0)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ct(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(p0(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=h0(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,f0(["init"])).pipe(l0(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return A(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:qn.DOM,thrown:t})))||(this.videoState.setState("paused"),x(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"),x(this.params.desiredState.playbackState,"stopped",!0)}};var nT="X-Playback-Duration",pc=a=>A(void 0,null,function*(){var i;let e=yield Ze(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(nT)?parseInt(e.headers.get(nT),10):void 0});import{assertNever as k0,combine as L0,debounce as R0,ErrorCategory as Qn,filter as $0,filterChanged as M0,isNonNullable as lT,isNullable as Gn,map as cT,merge as D0,observableFrom as C0,Subscription as V0,ValueSubject as fc,VideoQuality as B0}from"@vkontakte/videoplayer-shared/es2015";var mc=V(gu(),1);import{videoSizeToQuality as v0,getExponentialDelay as S0}from"@vkontakte/videoplayer-shared/es2015";var y0=a=>{let e=null;if(a.QUALITY&&(e=Ot(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=v0({width:t,height:r})}return e!=null?e:null},T0=(a,e)=>{var s,n;let t=a.split(`
125
+ `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,mc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=y0(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(P=>parseInt(P,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,mc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},I0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),hc=0,oT=(i,...s)=>A(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield Ze(a,r)).text();hc+=1;try{let{qualityManifests:u,textTracks:l}=T0(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(hc<=t.manifestRetryMaxCount)return yield I0(S0(hc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),oT(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Hn=oT;import{isNonNullable as E0,Subscription as x0,throttle as P0,ValueSubject as uT,Subject as w0,ErrorCategory as A0}from"@vkontakte/videoplayer-shared/es2015";var jn=class{constructor(e,t,r,i,s){this.subscription=new x0;this.abortControllers={destroy:new he,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new uT(null);this.getCurrentTime$=new uT(null);this.error$=new w0;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(P0(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return A(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return A(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return A(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield Ze(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
126
+ `),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(E0(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([R(I({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return A(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new he;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return A(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:A0.WTF,thrown:t,message:e})}};var Ka=class{constructor(e){this.subscription=new V0;this.videoState=new D("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new fc([]);this.liveOffset=new ft;this.manifestStartTime$=new fc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return k0(t)}};var r;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:B0.INVARIANT,url:this.params.source.url};let t=(i,s)=>Hn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new jn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new qe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Qn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Qn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new fc((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Qn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(M0(),cT(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&lT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(oe(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(L0({startTime:this.manifestStartTime$.pipe($0(lT)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(cT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=D0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,C0(["init"])).pipe(R0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Gn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=pe(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),pc(n).then(c=>{var d;if(!Gn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Gn(p)||!isFinite(p))&&Ze(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();pc(g).then(v=>{Gn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=pe(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 O0,debounce as _0,ErrorCategory as bc,fromEvent as gc,isNonNullable as N0,isNullable as F0,map as dT,merge as pT,observableFrom as hT,Subscription as q0,ValueSubject as U0,VideoQuality as H0,clientChecker as j0}from"@vkontakte/videoplayer-shared/es2015";var Xa=class{constructor(e){this.subscription=new q0;this.videoState=new D("stopped");this.manifests$=new U0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return O0(t)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:H0.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),Hn(pe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:bc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&(!i||!i.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:bc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(dT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&N0(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(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(dT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!j0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(pT(gc(o,"addtrack"),gc(o,"removetrack"),gc(o,"change"),hT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=pT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,hT(["init"])).pipe(_0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(F0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var bT=V(Ur(),1),vc=V(Zr(),1),gT=V(_t(),1);import{assertNever as Q0,assertNonNullable as mT,debounce as G0,ErrorCategory as fT,isHigherOrEqual as W0,isLowerOrEqual as Y0,isNonNullable as z0,merge as K0,observableFrom as X0,Subscription as J0,map as Z0}from"@vkontakte/videoplayer-shared/es2015";var Ja=class{constructor(e){this.subscription=new J0;this.videoState=new D("stopped");this.trackUrls={};this.textTracksManager=new qe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Q0(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,bT.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,vc.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:fT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=we(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Z0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&z0(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=K0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,X0(["init"])).pipe(G0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),xe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;mT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];mT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ba(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let p=Ft(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,vc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Yi({limits:e,lowestAvailableQuality:(c=(0,gT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?Y0(i,e.max):!0,u=e.min?W0(i,e.min):!0;o&&u||r(e)}};import{assertNever as ST,debounce as iC,merge as yT,observableFrom as aC,Subscription as sC,map as TT,ValueSubject as nC,ErrorCategory as yc,VideoQuality as oC}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as eC}from"@vkontakte/videoplayer-shared/es2015";var vT=["stun:videostun.mycdn.me:80"],tC=1e3,rC=3,Sc=()=>null,Wn=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=Sc;this.externalStopCallback=Sc;this.externalErrorCallback=Sc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return A(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return A(this,null,function*(){try{let e={iceServers:[{urls:vT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return A(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return A(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:eC.WTF,message:e.message})}onPeerConnectionStream(e){return A(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return A(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),tC)}normalizeOptions(e={}){let t={stunServerList:vT,maxRetryNumber:rC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Za=class{constructor(e){this.videoState=new D("stopped");this.maxSeekBackTime$=new nC(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return ST(e)}};this.subscription=new sC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new Wn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:yc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};yT(this.videoState.stateChangeStarted$.pipe(TT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(TT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=we(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(He(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Pe(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return ST(n.to)}},r)).add(yT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,aC(["init"])).pipe(iC(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:oC.INVARIANT}),this.video.srcObject=e,x(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:yc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:yc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var es=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as rs,assertNonNullable as Wt,ErrorCategory as Yn,filter as AT,isNonNullable as kT,isNullable as fC,map as bC,merge as gC,once as vC,Subject as $e,Subscription as LT,ValueSubject as B,flattenObject as RT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as uC,map as IT,Subscription as lC,Subject as cC}from"@vkontakte/videoplayer-shared/es2015";var ET=a=>new uC(e=>{let t=new lC,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(IT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(IT(({type:l})=>l!==void 0)),n=new cC,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as dC,Subscription as pC,combine as hC,filter as PT,once as wT}from"@vkontakte/videoplayer-shared/es2015";function xT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as mC}from"@vkontakte/videoplayer-shared/es2015";var ts=class ts{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new he;this.subscriptions=new pC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(PT(s=>!!s.type),wT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){mC.isSafari&&e!=="MPEG"||this.subscriptions.add(hC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(PT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),wT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return A(this,null,function*(){let{volumeMultiplier:t}=this,r=xT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:ts.errorId,category:dC.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${ts.errorId} exception`,thrown:e})}};ts.errorId="VolumeMultiplierManager";var pi=ts;var SC={chunkDuration:5e3,maxParallelRequests:5},is=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new $e;this.noAvailableProvidersError$=new $e;this.volumeMultiplierError$=new $e;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new $e,warning$:new $e,willSeekEvent$:new $e,soundProhibitedEvent$:new $e,seekedEvent$:new $e,loopedEvent$:new $e,endedEvent$:new $e,firstBytesEvent$:new $e,loadedMetadataEvent$:new $e,firstFrameEvent$:new $e,canplay$:new $e,isLive$:new B(void 0),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B(""),getCurrentTime$:new B(null)};this.subscription=new LT;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=eS([...rS(this.params.tuning),...tS(this.params.tuning)],this.params.tuning).filter(l=>kT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Tc.default)(i,l)),...t.filter(l=>(0,Tc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",RT(s)),this.screenFormatsIterator=new es(s);let n=[...Al(!0),...Al(!1)];this.chromecastFormatsIterator=new es(n.filter(l=>kT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&pi.isSupported()&&(this.volumeMultiplierManager=new pi(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(fC(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Yn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return rs(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Wt(o),new Ga(R(I({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Wa(R(I({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Wt(o),ai||!this.params.tuning.useHlsJs?new Xa(R(I({},n),{source:o})):new za(R(I({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Ka(R(I({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Ja(R(I({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new vv(R(I({},n),{source:o,config:R(I({},SC),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Za({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return rs(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Wt(o),new ji({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return rs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return rs(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return rs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return R(I({},e),{url:r(e.url)})}return(0,MT.default)((0,$T.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new LT,t=!1,r=0;return e.add(gC(this.providerOutput.error$.pipe(AT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),ET({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(bC(i=>({id:`ProviderHangup:${i}`,category:Yn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(AT(({to:s})=>s==="playing"),vC()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Yn.NETWORK,u=i.category===Yn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=R(I({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",RT(n))})),e}};import{fromEvent as zn,once as yC,combine as TC,Subscription as DT,ValueSubject as Ic,map as IC,filter as EC,isNonNullable as Kn,now as _e,safeStorage as Ec}from"@vkontakte/videoplayer-shared/es2015";var xC=5e3,CT="one_video_throughput",VT="one_video_rtt",yt=window.navigator.connection,BT=()=>{let a=yt==null?void 0:yt.downlink;if(Kn(a)&&a!==10)return a*1e3},OT=()=>{let a=yt==null?void 0:yt.rtt;if(Kn(a)&&a!==3e3)return a},_T=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},xc=class a{constructor(e){this.subscription=new DT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(CT)||(e.useBrowserEstimation?BT():void 0)||xC,r=(s=(i=a.load(VT))!=null?i:e.useBrowserEstimation?OT():void 0)!=null?s:0;if(this.throughput$=new Ic(t),this.rtt$=new Ic(r),this.rttAdjustedThroughput$=new Ic(_T(t,r,e.rttPenaltyRequestSize)),this.throughput=Sr.getSmoothedValue(t,-1,e),this.rtt=Sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=BT();u&&this.throughput.next(u);let l=OT();Kn(l)&&this.rtt.next(l)};yt&&"onchange"in yt&&this.subscription.add(zn(yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Ec.set(CT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Ec.set(VT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(TC({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(IC(({throughput:n,rtt:o})=>_T(n,o,e.rttPenaltyRequestSize)),EC(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=_e(),i=new DT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(zn(e,"progress").pipe(yC()).subscribe(s=>{t=s.loaded,r=_e()}));break;case 1:case 0:i.add(zn(e,"loadstart").subscribe(()=>{t=0,r=_e()}));break}i.add(zn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=_e(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=_e(),n=0,o=_e(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>A(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,_e()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=_e();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=_e()}else n+=d.byteLength;o=_e()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&_e()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,_e()-o,this.concurrentDownloads.size),n=0,o=_e());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Ec.get(e);if(Kn(t))return(r=parseInt(t,10))!=null?r:void 0}},NT=xc;import{fillWithDefault as PC,VideoQuality as Xn}from"@vkontakte/videoplayer-shared/es2015";var FT={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:Xn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Xn.Q_720P,trafficSavingLimit:Xn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Xn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},qT=a=>{var e;return R(I({},PC(a,FT)),{configName:[...(e=a.configName)!=null?e:[],...FT.configName]})};import{assertNonNullable as Jn,combine as Tt,ErrorCategory as Zn,filter as Te,filterChanged as G,fromEvent as wc,isNonNullable as MC,isNullable as DC,Logger as CC,map as H,mapTo as QT,merge as Yt,now as eo,once as ct,Subject as X,Subscription as GT,tap as WT,ValueSubject as w,isHigher as VC,isInvariantQuality as YT,flattenObject as zt,throttle as Ac,getTraceSubscriptionMethod as zT,Tracer as BC,InternalsExposure as OC}from"@vkontakte/videoplayer-shared/es2015";import{merge as wC,map as AC,filter as UT,isNonNullable as kC}from"@vkontakte/videoplayer-shared/es2015";var Pc=({seekState:a,position$:e})=>wC(a.stateChangeEnded$.pipe(AC(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),UT(kC)),e.pipe(UT(()=>a.getState().state==="none")));import{assertNonNullable as LC}from"@vkontakte/videoplayer-shared/es2015";var HT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return LC(e,`Wrong container or containerId {${a.container}}`),e};import{filter as RC,once as $C}from"@vkontakte/videoplayer-shared/es2015";var jT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(RC(i=>i.length>0),$C()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var to=class{constructor(e={configName:[]},t=BC.createRootTracer(!1)){this.subscription=new GT;this.logger=new CC;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new w(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new D("stopped"),seekState:new D({state:"none"}),volume:new D({volume:1,muted:!1}),videoTrack:new D(void 0),videoStream:new D(void 0),audioStream:new D(void 0),autoVideoTrackSwitching:new D(!0),autoVideoTrackLimits:new D({}),isLooped:new D(!1),isLowLatency:new D(!1),playbackRate:new D(1),externalTextTracks:new D([]),internalTextTracks:new D([]),currentTextTrack:new D(void 0),textTrackCuesSettings:new D({}),cameraOrientation:new D({x:0,y:0})};this.info={playbackState$:new w("stopped"),position$:new w(0),duration$:new w(1/0),muted$:new w(!1),volume$:new w(1),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableQualities$:new w([]),availableQualitiesFps$:new w({}),currentQuality$:new w(void 0),isAutoQualityEnabled$:new w(!0),autoQualityLimitingAvailable$:new w(!1),autoQualityLimits$:new w({}),predefinedQualityLimitType$:new w("unknown"),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),isAudioAvailable$:new w(!0),currentPlaybackRate$:new w(1),currentBuffer$:new w({start:0,end:0}),isBuffering$:new w(!0),isStalled$:new w(!1),isEnded$:new w(!1),isLooped$:new w(!1),isLive$:new w(void 0),canChangePlaybackSpeed$:new w(void 0),atLiveEdge$:new w(void 0),atLiveDurationEdge$:new w(void 0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),currentFormat$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),throughputEstimation$:new w(void 0),rttEstimation$:new w(void 0),videoBitrate$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),surface$:new w("none"),chromecastState$:new w("NOT_AVAILABLE"),chromecastDeviceName$:new w(void 0),intrinsicVideoSize$:new w(void 0),availableSources$:new w(void 0),is3DVideo$:new w(!1),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(0)};this.events={inited$:new X,ready$:new X,started$:new X,playing$:new X,paused$:new X,stopped$:new X,willStart$:new X,willResume$:new X,willPause$:new X,willStop$:new X,willDestruct$:new X,watchCoverageRecord$:new X,watchCoverageLive$:new X,managedError$:new X,fatalError$:new X,ended$:new X,looped$:new X,seeked$:new X,willSeek$:new X,autoplaySoundProhibited$:new X,firstBytes$:new X,loadedMetadata$:new X,firstFrame$:new X,canplay$:new X,log$:new X};this.experimental={element$:new w(void 0),tuningConfigName$:new w([]),enableDebugTelemetry$:new w(!1),dumpTelemetry:Ug,getCurrentTime$:new w(null)};if(this.initLogs(),this.tuning=qT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ws({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new NT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new OC("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return(0,KT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Zn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=cd(i,["container"]);return this.tracer.log("initVideo",zt(r)),this.domContainer=HT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new is({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ea()?(this.tracer.log("request play from hidden tab"),wc(document,"visibilitychange").pipe(ct()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Jn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Te(r=>r.length>0),ct()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",zt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.setAutoQualityLimits(i),this}setPlaybackRate(e){var r;Jn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",zt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>I({type:"external"},t))),this}selectTextTrack(e){var t;return jT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",I({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(DC(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return MC(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(pl({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Te(({from:e})=>e==="stopped"),ct()).subscribe(()=>{this.initedAt=eo(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",zt(n)),n.state==="requested"?this.desiredState.seekState.setState(R(I({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Zn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ct()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",zt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(H(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(H(n=>n.destination),G()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Tt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(H(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>YT(u)?1:YT(l)?-1:VC(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(G()).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(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(G()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(G()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(G()).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(H(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Tt({hasLiveOffsetByPaused:Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(n=>n.to),G(),H(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Tt({atLiveEdge:Tt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Pc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(H(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),G(),WT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(H(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Tt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(H(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),G(),WT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(H(n=>n.muted),G()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(H(n=>n.volume),G()).subscribe(this.info.volume$)).add(Pc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Yt(e.providerOutput.endedEvent$.pipe(QT(!0)),e.providerOutput.seekedEvent$.pipe(QT(!1))).pipe(G()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(H(n=>({id:n?`No${n}`:"NoProviders",category:Zn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(ct(),H(n=>n!=null?n:eo()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ct(),H(()=>eo()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ct(),H(()=>eo()-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 w(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new w(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Te(({to:n})=>n==="playing"),ct()).subscribe(()=>r.next(!1)));let i=0,s=Yt(e.providerOutput.isBuffering$,t,r).pipe(H(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),G());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Yt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Yt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(H(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 GT;this.subscription.add(t),this.subscription.add(e.current$.pipe(G((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Te(r=>r.length>0),ct()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Yt(this.desiredState.videoTrack.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(H(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;Jn(this.providerContainer),Jn(e),qg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Fg(r)),this.providerContainer.current$.subscribe(({type:r})=>Wi("provider",r)),e.duration$.subscribe(r=>Wi("duration",r)),e.availableVideoTracks$.pipe(Te(r=>!!r.length),ct()).subscribe(r=>Wi("tracks",r)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(H(r=>r==null?void 0:r.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(r=>this.subscription.add(r)),Wi("codecs",Zv())}initTracerSubscription(){let e=zT(this.tracer.log.bind(this.tracer)),t=zT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(G()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Tt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Te(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),G((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Te(r=>r>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Te(r=>r>0),G()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Tt({currentBuffer:this.info.currentBuffer$.pipe(Te(r=>r.end>0),G((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(G())}).pipe(Ac(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(G()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(G()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(G()).subscribe(e("canChangePlaybackSpeed"))).add(Tt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Te(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Ac(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),Te(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),Te(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(G()).subscribe(e("muted"))).add(this.info.volume$.pipe(G()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(G(),Te(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Tt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Te(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Ac(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),Te(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>A(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Zn.DOM,message:String(i)})})});this.subscription.add(Yt(wc(document,"visibilitychange"),wc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",zt({quality:t,availableTracks:zt(e),track:zt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as pK,Observable as hK,Subject as mK,ValueSubject as fK,VideoQuality as bK}from"@vkontakte/videoplayer-shared/es2015";var gK=`@vkontakte/videoplayer-core@${dd}`;export{Ss as ChromecastState,lo as HttpConnectionType,hK as Observable,Ie as PlaybackState,to as Player,ys as PredefinedQualityLimits,gK as SDK_VERSION,mK as Subject,pK as Subscription,co as Surface,dd as VERSION,fK as ValueSubject,Rt as VideoFormat,bK as VideoQuality};