@vkontakte/videoplayer-core 2.0.123-dev.8ba72ee5.0 → 2.0.123-dev.92e9449d.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2018.esm.js CHANGED
@@ -1,72 +1,73 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.123-dev.8ba72ee5.0
3
- * Wed, 18 Dec 2024 15:16:11 GMT
2
+ * @vkontakte/videoplayer-core v2.0.123-dev.92e9449d.0
3
+ * Thu, 26 Dec 2024 14:15:53 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-123/doc/
5
5
  */
6
- var wT=Object.create;var Dc=Object.defineProperty;var kT=Object.getOwnPropertyDescriptor;var RT=Object.getOwnPropertyNames;var $T=Object.getPrototypeOf,LT=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var MT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of RT(e))!LT.call(a,i)&&i!==t&&Dc(a,i,{get:()=>e[i],enumerable:!(r=kT(e,i))||r.enumerable});return a};var V=(a,e,t)=>(t=a!=null?wT($T(a)):{},MT(e||!a||!a.__esModule?Dc(t,"default",{value:a,enumerable:!0}):t,a));var z=m((qn,Vc)=>{"use strict";var oi=function(a){return a&&a.Math===Math&&a};Vc.exports=oi(typeof globalThis=="object"&&globalThis)||oi(typeof window=="object"&&window)||oi(typeof self=="object"&&self)||oi(typeof global=="object"&&global)||oi(typeof qn=="object"&&qn)||function(){return this}()||Function("return this")()});var ue=m((tD,Bc)=>{"use strict";Bc.exports=function(a){try{return!!a()}catch(e){return!0}}});var ui=m((rD,_c)=>{"use strict";var CT=ue();_c.exports=!CT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Un=m((iD,Uc)=>{"use strict";var DT=ui(),qc=Function.prototype,Nc=qc.apply,Fc=qc.call;Uc.exports=typeof Reflect=="object"&&Reflect.apply||(DT?Fc.bind(Nc):function(){return Fc.apply(Nc,arguments)})});var te=m((aD,Gc)=>{"use strict";var Hc=ui(),jc=Function.prototype,Hn=jc.call,OT=Hc&&jc.bind.bind(Hn,Hn);Gc.exports=Hc?OT:function(a){return function(){return Hn.apply(a,arguments)}}});var Qt=m((sD,Wc)=>{"use strict";var Qc=te(),VT=Qc({}.toString),BT=Qc("".slice);Wc.exports=function(a){return BT(VT(a),8,-1)}});var jn=m((nD,Yc)=>{"use strict";var _T=Qt(),NT=te();Yc.exports=function(a){if(_T(a)==="Function")return NT(a)}});var Y=m((oD,zc)=>{"use strict";var Gn=typeof document=="object"&&document.all;zc.exports=typeof Gn=="undefined"&&Gn!==void 0?function(a){return typeof a=="function"||a===Gn}:function(a){return typeof a=="function"}});var xe=m((uD,Kc)=>{"use strict";var FT=ue();Kc.exports=!FT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Pe=m((lD,Jc)=>{"use strict";var qT=ui(),rs=Function.prototype.call;Jc.exports=qT?rs.bind(rs):function(){return rs.apply(rs,arguments)}});var Qn=m(ed=>{"use strict";var Xc={}.propertyIsEnumerable,Zc=Object.getOwnPropertyDescriptor,UT=Zc&&!Xc.call({1:2},1);ed.f=UT?function(e){var t=Zc(this,e);return!!t&&t.enumerable}:Xc});var li=m((dD,td)=>{"use strict";td.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var id=m((pD,rd)=>{"use strict";var HT=te(),jT=ue(),GT=Qt(),Wn=Object,QT=HT("".split);rd.exports=jT(function(){return!Wn("z").propertyIsEnumerable(0)})?function(a){return GT(a)==="String"?QT(a,""):Wn(a)}:Wn});var Ir=m((hD,ad)=>{"use strict";ad.exports=function(a){return a==null}});var xt=m((fD,sd)=>{"use strict";var WT=Ir(),YT=TypeError;sd.exports=function(a){if(WT(a))throw new YT("Can't call method on "+a);return a}});var Wt=m((mD,nd)=>{"use strict";var zT=id(),KT=xt();nd.exports=function(a){return zT(KT(a))}});var Ae=m((bD,od)=>{"use strict";var JT=Y();od.exports=function(a){return typeof a=="object"?a!==null:JT(a)}});var Er=m((gD,ud)=>{"use strict";ud.exports={}});var at=m((vD,cd)=>{"use strict";var Yn=Er(),zn=z(),XT=Y(),ld=function(a){return XT(a)?a:void 0};cd.exports=function(a,e){return arguments.length<2?ld(Yn[a])||ld(zn[a]):Yn[a]&&Yn[a][e]||zn[a]&&zn[a][e]}});var ci=m((SD,dd)=>{"use strict";var ZT=te();dd.exports=ZT({}.isPrototypeOf)});var Yt=m((yD,fd)=>{"use strict";var eI=z(),pd=eI.navigator,hd=pd&&pd.userAgent;fd.exports=hd?String(hd):""});var Jn=m((TD,yd)=>{"use strict";var Sd=z(),Kn=Yt(),md=Sd.process,bd=Sd.Deno,gd=md&&md.versions||bd&&bd.version,vd=gd&&gd.v8,Ue,is;vd&&(Ue=vd.split("."),is=Ue[0]>0&&Ue[0]<4?1:+(Ue[0]+Ue[1]));!is&&Kn&&(Ue=Kn.match(/Edge\/(\d+)/),(!Ue||Ue[1]>=74)&&(Ue=Kn.match(/Chrome\/(\d+)/),Ue&&(is=+Ue[1])));yd.exports=is});var Xn=m((ID,Id)=>{"use strict";var Td=Jn(),tI=ue(),rI=z(),iI=rI.String;Id.exports=!!Object.getOwnPropertySymbols&&!tI(function(){var a=Symbol("symbol detection");return!iI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Td&&Td<41})});var Zn=m((ED,Ed)=>{"use strict";var aI=Xn();Ed.exports=aI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var eo=m((xD,xd)=>{"use strict";var sI=at(),nI=Y(),oI=ci(),uI=Zn(),lI=Object;xd.exports=uI?function(a){return typeof a=="symbol"}:function(a){var e=sI("Symbol");return nI(e)&&oI(e.prototype,lI(a))}});var di=m((PD,Pd)=>{"use strict";var cI=String;Pd.exports=function(a){try{return cI(a)}catch(e){return"Object"}}});var Ke=m((AD,Ad)=>{"use strict";var dI=Y(),pI=di(),hI=TypeError;Ad.exports=function(a){if(dI(a))return a;throw new hI(pI(a)+" is not a function")}});var pi=m((wD,wd)=>{"use strict";var fI=Ke(),mI=Ir();wd.exports=function(a,e){var t=a[e];return mI(t)?void 0:fI(t)}});var Rd=m((kD,kd)=>{"use strict";var to=Pe(),ro=Y(),io=Ae(),bI=TypeError;kd.exports=function(a,e){var t,r;if(e==="string"&&ro(t=a.toString)&&!io(r=to(t,a))||ro(t=a.valueOf)&&!io(r=to(t,a))||e!=="string"&&ro(t=a.toString)&&!io(r=to(t,a)))return r;throw new bI("Can't convert object to primitive value")}});var He=m((RD,$d)=>{"use strict";$d.exports=!0});var Cd=m(($D,Md)=>{"use strict";var Ld=z(),gI=Object.defineProperty;Md.exports=function(a,e){try{gI(Ld,a,{value:e,configurable:!0,writable:!0})}catch(t){Ld[a]=e}return e}});var hi=m((LD,Vd)=>{"use strict";var vI=He(),SI=z(),yI=Cd(),Dd="__core-js_shared__",Od=Vd.exports=SI[Dd]||yI(Dd,{});(Od.versions||(Od.versions=[])).push({version:"3.38.0",mode:vI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var ao=m((MD,_d)=>{"use strict";var Bd=hi();_d.exports=function(a,e){return Bd[a]||(Bd[a]=e||{})}});var xr=m((CD,Nd)=>{"use strict";var TI=xt(),II=Object;Nd.exports=function(a){return II(TI(a))}});var je=m((DD,Fd)=>{"use strict";var EI=te(),xI=xr(),PI=EI({}.hasOwnProperty);Fd.exports=Object.hasOwn||function(e,t){return PI(xI(e),t)}});var so=m((OD,qd)=>{"use strict";var AI=te(),wI=0,kI=Math.random(),RI=AI(1 .toString);qd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+RI(++wI+kI,36)}});var le=m((VD,Hd)=>{"use strict";var $I=z(),LI=ao(),Ud=je(),MI=so(),CI=Xn(),DI=Zn(),Pr=$I.Symbol,no=LI("wks"),OI=DI?Pr.for||Pr:Pr&&Pr.withoutSetter||MI;Hd.exports=function(a){return Ud(no,a)||(no[a]=CI&&Ud(Pr,a)?Pr[a]:OI("Symbol."+a)),no[a]}});var Wd=m((BD,Qd)=>{"use strict";var VI=Pe(),jd=Ae(),Gd=eo(),BI=pi(),_I=Rd(),NI=le(),FI=TypeError,qI=NI("toPrimitive");Qd.exports=function(a,e){if(!jd(a)||Gd(a))return a;var t=BI(a,qI),r;if(t){if(e===void 0&&(e="default"),r=VI(t,a,e),!jd(r)||Gd(r))return r;throw new FI("Can't convert object to primitive value")}return e===void 0&&(e="number"),_I(a,e)}});var oo=m((_D,Yd)=>{"use strict";var UI=Wd(),HI=eo();Yd.exports=function(a){var e=UI(a,"string");return HI(e)?e:e+""}});var as=m((ND,Kd)=>{"use strict";var jI=z(),zd=Ae(),uo=jI.document,GI=zd(uo)&&zd(uo.createElement);Kd.exports=function(a){return GI?uo.createElement(a):{}}});var lo=m((FD,Jd)=>{"use strict";var QI=xe(),WI=ue(),YI=as();Jd.exports=!QI&&!WI(function(){return Object.defineProperty(YI("div"),"a",{get:function(){return 7}}).a!==7})});var ep=m(Zd=>{"use strict";var zI=xe(),KI=Pe(),JI=Qn(),XI=li(),ZI=Wt(),eE=oo(),tE=je(),rE=lo(),Xd=Object.getOwnPropertyDescriptor;Zd.f=zI?Xd:function(e,t){if(e=ZI(e),t=eE(t),rE)try{return Xd(e,t)}catch(r){}if(tE(e,t))return XI(!KI(JI.f,e,t),e[t])}});var co=m((UD,tp)=>{"use strict";var iE=ue(),aE=Y(),sE=/#|\.prototype\./,fi=function(a,e){var t=oE[nE(a)];return t===lE?!0:t===uE?!1:aE(e)?iE(e):!!e},nE=fi.normalize=function(a){return String(a).replace(sE,".").toLowerCase()},oE=fi.data={},uE=fi.NATIVE="N",lE=fi.POLYFILL="P";tp.exports=fi});var Ar=m((HD,ip)=>{"use strict";var rp=jn(),cE=Ke(),dE=ui(),pE=rp(rp.bind);ip.exports=function(a,e){return cE(a),e===void 0?a:dE?pE(a,e):function(){return a.apply(e,arguments)}}});var po=m((jD,ap)=>{"use strict";var hE=xe(),fE=ue();ap.exports=hE&&fE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Je=m((GD,sp)=>{"use strict";var mE=Ae(),bE=String,gE=TypeError;sp.exports=function(a){if(mE(a))return a;throw new gE(bE(a)+" is not an object")}});var zt=m(op=>{"use strict";var vE=xe(),SE=lo(),yE=po(),ss=Je(),np=oo(),TE=TypeError,ho=Object.defineProperty,IE=Object.getOwnPropertyDescriptor,fo="enumerable",mo="configurable",bo="writable";op.f=vE?yE?function(e,t,r){if(ss(e),t=np(t),ss(r),typeof e=="function"&&t==="prototype"&&"value"in r&&bo in r&&!r[bo]){var i=IE(e,t);i&&i[bo]&&(e[t]=r.value,r={configurable:mo in r?r[mo]:i[mo],enumerable:fo in r?r[fo]:i[fo],writable:!1})}return ho(e,t,r)}:ho:function(e,t,r){if(ss(e),t=np(t),ss(r),SE)try{return ho(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new TE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var wr=m((WD,up)=>{"use strict";var EE=xe(),xE=zt(),PE=li();up.exports=EE?function(a,e,t){return xE.f(a,e,PE(1,t))}:function(a,e,t){return a[e]=t,a}});var X=m((YD,cp)=>{"use strict";var mi=z(),AE=Un(),wE=jn(),kE=Y(),RE=ep().f,$E=co(),kr=Er(),LE=Ar(),Rr=wr(),lp=je();hi();var ME=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 AE(a,this,arguments)};return e.prototype=a.prototype,e};cp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?mi:i?mi[t]:mi[t]&&mi[t].prototype,o=r?kr:kr[t]||Rr(kr,t,{})[t],u=o.prototype,l,c,d,h,p,f,b,g,v;for(h in e)l=$E(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&lp(n,h),f=o[h],c&&(a.dontCallGetSet?(v=RE(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?g=LE(p,mi):a.wrap&&c?g=ME(p):s&&kE(p)?g=wE(p):g=p,(a.sham||p&&p.sham||f&&f.sham)&&Rr(g,"sham",!0),Rr(o,h,g),s&&(d=t+"Prototype",lp(kr,d)||Rr(kr,d,{}),Rr(kr[d],h,p),a.real&&u&&(l||!u[h])&&Rr(u,h,p)))}});var pp=m((zD,dp)=>{"use strict";var CE=Math.ceil,DE=Math.floor;dp.exports=Math.trunc||function(e){var t=+e;return(t>0?DE:CE)(t)}});var bi=m((KD,hp)=>{"use strict";var OE=pp();hp.exports=function(a){var e=+a;return e!==e||e===0?0:OE(e)}});var mp=m((JD,fp)=>{"use strict";var VE=bi(),BE=Math.max,_E=Math.min;fp.exports=function(a,e){var t=VE(a);return t<0?BE(t+e,0):_E(t,e)}});var go=m((XD,bp)=>{"use strict";var NE=bi(),FE=Math.min;bp.exports=function(a){var e=NE(a);return e>0?FE(e,9007199254740991):0}});var $r=m((ZD,gp)=>{"use strict";var qE=go();gp.exports=function(a){return qE(a.length)}});var vo=m((eO,Sp)=>{"use strict";var UE=Wt(),HE=mp(),jE=$r(),vp=function(a){return function(e,t,r){var i=UE(e),s=jE(i);if(s===0)return!a&&-1;var n=HE(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}};Sp.exports={includes:vp(!0),indexOf:vp(!1)}});var gi=m((tO,yp)=>{"use strict";yp.exports=function(){}});var Tp=m(()=>{"use strict";var GE=X(),QE=vo().includes,WE=ue(),YE=gi(),zE=WE(function(){return!Array(1).includes()});GE({target:"Array",proto:!0,forced:zE},{includes:function(e){return QE(this,e,arguments.length>1?arguments[1]:void 0)}});YE("includes")});var Pt=m((aO,Ip)=>{"use strict";var KE=at();Ip.exports=KE});var xp=m((sO,Ep)=>{"use strict";Tp();var JE=Pt();Ep.exports=JE("Array","includes")});var Ap=m((nO,Pp)=>{"use strict";var XE=xp();Pp.exports=XE});var Xe=m((oO,wp)=>{"use strict";var ZE=Ap();wp.exports=ZE});var us=m((SO,Op)=>{"use strict";var ox=ao(),ux=so(),Dp=ox("keys");Op.exports=function(a){return Dp[a]||(Dp[a]=ux(a))}});var Bp=m((yO,Vp)=>{"use strict";var lx=ue();Vp.exports=!lx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ls=m((TO,Np)=>{"use strict";var cx=je(),dx=Y(),px=xr(),hx=us(),fx=Bp(),_p=hx("IE_PROTO"),To=Object,mx=To.prototype;Np.exports=fx?To.getPrototypeOf:function(a){var e=px(a);if(cx(e,_p))return e[_p];var t=e.constructor;return dx(t)&&e instanceof t?t.prototype:e instanceof To?mx:null}});var cs=m((IO,Fp)=>{"use strict";Fp.exports={}});var Hp=m((EO,Up)=>{"use strict";var bx=te(),Io=je(),gx=Wt(),vx=vo().indexOf,Sx=cs(),qp=bx([].push);Up.exports=function(a,e){var t=gx(a),r=0,i=[],s;for(s in t)!Io(Sx,s)&&Io(t,s)&&qp(i,s);for(;e.length>r;)Io(t,s=e[r++])&&(~vx(i,s)||qp(i,s));return i}});var Eo=m((xO,jp)=>{"use strict";jp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var xo=m((PO,Gp)=>{"use strict";var yx=Hp(),Tx=Eo();Gp.exports=Object.keys||function(e){return yx(e,Tx)}});var Po=m((AO,Kp)=>{"use strict";var Wp=xe(),Ix=ue(),Yp=te(),Ex=ls(),xx=xo(),Px=Wt(),Ax=Qn().f,zp=Yp(Ax),wx=Yp([].push),kx=Wp&&Ix(function(){var a=Object.create(null);return a[2]=2,!zp(a,2)}),Qp=function(a){return function(e){for(var t=Px(e),r=xx(t),i=kx&&Ex(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Wp||(i?u in t:zp(t,u)))&&wx(o,a?[u,t[u]]:t[u]);return o}};Kp.exports={entries:Qp(!0),values:Qp(!1)}});var Jp=m(()=>{"use strict";var Rx=X(),$x=Po().entries;Rx({target:"Object",stat:!0},{entries:function(e){return $x(e)}})});var Zp=m((RO,Xp)=>{"use strict";Jp();var Lx=Er();Xp.exports=Lx.Object.entries});var th=m(($O,eh)=>{"use strict";var Mx=Zp();eh.exports=Mx});var Lr=m((LO,rh)=>{"use strict";var Cx=th();rh.exports=Cx});var Kt=m((MO,ih)=>{"use strict";ih.exports={}});var nh=m((CO,sh)=>{"use strict";var Dx=z(),Ox=Y(),ah=Dx.WeakMap;sh.exports=Ox(ah)&&/native code/.test(String(ah))});var Ro=m((DO,lh)=>{"use strict";var Vx=nh(),uh=z(),Bx=Ae(),_x=wr(),Ao=je(),wo=hi(),Nx=us(),Fx=cs(),oh="Object already initialized",ko=uh.TypeError,qx=uh.WeakMap,ds,vi,ps,Ux=function(a){return ps(a)?vi(a):ds(a,{})},Hx=function(a){return function(e){var t;if(!Bx(e)||(t=vi(e)).type!==a)throw new ko("Incompatible receiver, "+a+" required");return t}};Vx||wo.state?(Ge=wo.state||(wo.state=new qx),Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,ds=function(a,e){if(Ge.has(a))throw new ko(oh);return e.facade=a,Ge.set(a,e),e},vi=function(a){return Ge.get(a)||{}},ps=function(a){return Ge.has(a)}):(Jt=Nx("state"),Fx[Jt]=!0,ds=function(a,e){if(Ao(a,Jt))throw new ko(oh);return e.facade=a,_x(a,Jt,e),e},vi=function(a){return Ao(a,Jt)?a[Jt]:{}},ps=function(a){return Ao(a,Jt)});var Ge,Jt;lh.exports={set:ds,get:vi,has:ps,enforce:Ux,getterFor:Hx}});var Mo=m((OO,dh)=>{"use strict";var $o=xe(),jx=je(),ch=Function.prototype,Gx=$o&&Object.getOwnPropertyDescriptor,Lo=jx(ch,"name"),Qx=Lo&&function(){}.name==="something",Wx=Lo&&(!$o||$o&&Gx(ch,"name").configurable);dh.exports={EXISTS:Lo,PROPER:Qx,CONFIGURABLE:Wx}});var hh=m(ph=>{"use strict";var Yx=xe(),zx=po(),Kx=zt(),Jx=Je(),Xx=Wt(),Zx=xo();ph.f=Yx&&!zx?Object.defineProperties:function(e,t){Jx(e);for(var r=Xx(t),i=Zx(t),s=i.length,n=0,o;s>n;)Kx.f(e,o=i[n++],r[o]);return e}});var Co=m((BO,fh)=>{"use strict";var eP=at();fh.exports=eP("document","documentElement")});var Bo=m((_O,Th)=>{"use strict";var tP=Je(),rP=hh(),mh=Eo(),iP=cs(),aP=Co(),sP=as(),nP=us(),bh=">",gh="<",Oo="prototype",Vo="script",Sh=nP("IE_PROTO"),Do=function(){},yh=function(a){return gh+Vo+bh+a+gh+"/"+Vo+bh},vh=function(a){a.write(yh("")),a.close();var e=a.parentWindow.Object;return a=null,e},oP=function(){var a=sP("iframe"),e="java"+Vo+":",t;return a.style.display="none",aP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(yh("document.F=Object")),t.close(),t.F},hs,fs=function(){try{hs=new ActiveXObject("htmlfile")}catch(e){}fs=typeof document!="undefined"?document.domain&&hs?vh(hs):oP():vh(hs);for(var a=mh.length;a--;)delete fs[Oo][mh[a]];return fs()};iP[Sh]=!0;Th.exports=Object.create||function(e,t){var r;return e!==null?(Do[Oo]=tP(e),r=new Do,Do[Oo]=null,r[Sh]=e):r=fs(),t===void 0?r:rP.f(r,t)}});var Mr=m((NO,Ih)=>{"use strict";var uP=wr();Ih.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:uP(a,e,t),a}});var qo=m((FO,Ph)=>{"use strict";var lP=ue(),cP=Y(),dP=Ae(),pP=Bo(),Eh=ls(),hP=Mr(),fP=le(),mP=He(),Fo=fP("iterator"),xh=!1,st,_o,No;[].keys&&(No=[].keys(),"next"in No?(_o=Eh(Eh(No)),_o!==Object.prototype&&(st=_o)):xh=!0);var bP=!dP(st)||lP(function(){var a={};return st[Fo].call(a)!==a});bP?st={}:mP&&(st=pP(st));cP(st[Fo])||hP(st,Fo,function(){return this});Ph.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:xh}});var ms=m((qO,wh)=>{"use strict";var gP=le(),vP=gP("toStringTag"),Ah={};Ah[vP]="z";wh.exports=String(Ah)==="[object z]"});var Si=m((UO,kh)=>{"use strict";var SP=ms(),yP=Y(),bs=Qt(),TP=le(),IP=TP("toStringTag"),EP=Object,xP=bs(function(){return arguments}())==="Arguments",PP=function(a,e){try{return a[e]}catch(t){}};kh.exports=SP?bs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=PP(e=EP(a),IP))=="string"?t:xP?bs(e):(r=bs(e))==="Object"&&yP(e.callee)?"Arguments":r}});var $h=m((HO,Rh)=>{"use strict";var AP=ms(),wP=Si();Rh.exports=AP?{}.toString:function(){return"[object "+wP(this)+"]"}});var yi=m((jO,Mh)=>{"use strict";var kP=ms(),RP=zt().f,$P=wr(),LP=je(),MP=$h(),CP=le(),Lh=CP("toStringTag");Mh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(LP(i,Lh)||RP(i,Lh,{configurable:!0,value:e}),r&&!kP&&$P(i,"toString",MP))}});var Dh=m((GO,Ch)=>{"use strict";var DP=qo().IteratorPrototype,OP=Bo(),VP=li(),BP=yi(),_P=Kt(),NP=function(){return this};Ch.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=OP(DP,{next:VP(+!r,t)}),BP(a,i,!1,!0),_P[i]=NP,a}});var Vh=m((QO,Oh)=>{"use strict";var FP=te(),qP=Ke();Oh.exports=function(a,e,t){try{return FP(qP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var _h=m((WO,Bh)=>{"use strict";var UP=Ae();Bh.exports=function(a){return UP(a)||a===null}});var Fh=m((YO,Nh)=>{"use strict";var HP=_h(),jP=String,GP=TypeError;Nh.exports=function(a){if(HP(a))return a;throw new GP("Can't set "+jP(a)+" as a prototype")}});var Uo=m((zO,qh)=>{"use strict";var QP=Vh(),WP=Ae(),YP=xt(),zP=Fh();qh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=QP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return YP(i),zP(s),WP(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Xh=m((KO,Jh)=>{"use strict";var KP=X(),JP=Pe(),gs=He(),zh=Mo(),XP=Y(),ZP=Dh(),Uh=ls(),Hh=Uo(),eA=yi(),tA=wr(),Ho=Mr(),rA=le(),jh=Kt(),Kh=qo(),iA=zh.PROPER,aA=zh.CONFIGURABLE,Gh=Kh.IteratorPrototype,vs=Kh.BUGGY_SAFARI_ITERATORS,Ti=rA("iterator"),Qh="keys",Ii="values",Wh="entries",Yh=function(){return this};Jh.exports=function(a,e,t,r,i,s,n){ZP(t,e,r);var o=function(v){if(v===i&&h)return h;if(!vs&&v&&v in c)return c[v];switch(v){case Qh:return function(){return new t(this,v)};case Ii:return function(){return new t(this,v)};case Wh:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Ti]||c["@@iterator"]||i&&c[i],h=!vs&&d||o(i),p=e==="Array"&&c.entries||d,f,b,g;if(p&&(f=Uh(p.call(new a)),f!==Object.prototype&&f.next&&(!gs&&Uh(f)!==Gh&&(Hh?Hh(f,Gh):XP(f[Ti])||Ho(f,Ti,Yh)),eA(f,u,!0,!0),gs&&(jh[u]=Yh))),iA&&i===Ii&&d&&d.name!==Ii&&(!gs&&aA?tA(c,"name",Ii):(l=!0,h=function(){return JP(d,this)})),i)if(b={values:o(Ii),keys:s?h:o(Qh),entries:o(Wh)},n)for(g in b)(vs||l||!(g in c))&&Ho(c,g,b[g]);else KP({target:e,proto:!0,forced:vs||l},b);return(!gs||n)&&c[Ti]!==h&&Ho(c,Ti,h,{name:i}),jh[e]=h,b}});var ef=m((JO,Zh)=>{"use strict";Zh.exports=function(a,e){return{value:a,done:e}}});var Go=m((XO,nf)=>{"use strict";var sA=Wt(),jo=gi(),tf=Kt(),af=Ro(),nA=zt().f,oA=Xh(),Ss=ef(),uA=He(),lA=xe(),sf="Array Iterator",cA=af.set,dA=af.getterFor(sf);nf.exports=oA(Array,"Array",function(a,e){cA(this,{type:sf,target:sA(a),index:0,kind:e})},function(){var a=dA(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ss(void 0,!0);switch(a.kind){case"keys":return Ss(t,!1);case"values":return Ss(e[t],!1)}return Ss([t,e[t]],!1)},"values");var rf=tf.Arguments=tf.Array;jo("keys");jo("values");jo("entries");if(!uA&&lA&&rf.name!=="values")try{nA(rf,"name",{value:"values"})}catch(a){}});var uf=m((ZO,of)=>{"use strict";var pA=le(),hA=Kt(),fA=pA("iterator"),mA=Array.prototype;of.exports=function(a){return a!==void 0&&(hA.Array===a||mA[fA]===a)}});var Qo=m((eV,cf)=>{"use strict";var bA=Si(),lf=pi(),gA=Ir(),vA=Kt(),SA=le(),yA=SA("iterator");cf.exports=function(a){if(!gA(a))return lf(a,yA)||lf(a,"@@iterator")||vA[bA(a)]}});var pf=m((tV,df)=>{"use strict";var TA=Pe(),IA=Ke(),EA=Je(),xA=di(),PA=Qo(),AA=TypeError;df.exports=function(a,e){var t=arguments.length<2?PA(a):e;if(IA(t))return EA(TA(t,a));throw new AA(xA(a)+" is not iterable")}});var mf=m((rV,ff)=>{"use strict";var wA=Pe(),hf=Je(),kA=pi();ff.exports=function(a,e,t){var r,i;hf(a);try{if(r=kA(a,"return"),!r){if(e==="throw")throw t;return t}r=wA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return hf(r),t}});var Ts=m((iV,Sf)=>{"use strict";var RA=Ar(),$A=Pe(),LA=Je(),MA=di(),CA=uf(),DA=$r(),bf=ci(),OA=pf(),VA=Qo(),gf=mf(),BA=TypeError,ys=function(a,e){this.stopped=a,this.result=e},vf=ys.prototype;Sf.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=RA(e,r),l,c,d,h,p,f,b,g=function(S){return l&&gf(l,"normal",S),new ys(!0,S)},v=function(S){return i?(LA(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=VA(a),!c)throw new BA(MA(a)+" is not iterable");if(CA(c)){for(d=0,h=DA(a);h>d;d++)if(p=v(a[d]),p&&bf(vf,p))return p;return new ys(!1)}l=OA(a,c)}for(f=s?a.next:l.next;!(b=$A(f,l)).done;){try{p=v(b.value)}catch(S){gf(l,"throw",S)}if(typeof p=="object"&&p&&bf(vf,p))return p}return new ys(!1)}});var Tf=m((aV,yf)=>{"use strict";var _A=xe(),NA=zt(),FA=li();yf.exports=function(a,e,t){_A?NA.f(a,e,FA(0,t)):a[e]=t}});var If=m(()=>{"use strict";var qA=X(),UA=Ts(),HA=Tf();qA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return UA(e,function(r,i){HA(t,r,i)},{AS_ENTRIES:!0}),t}})});var xf=m((oV,Ef)=>{"use strict";Go();If();var jA=Er();Ef.exports=jA.Object.fromEntries});var Af=m((uV,Pf)=>{"use strict";Pf.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 kf=m(()=>{"use strict";Go();var GA=Af(),QA=z(),WA=yi(),wf=Kt();for(Is in GA)WA(QA[Is],Is),wf[Is]=wf.Array;var Is});var $f=m((dV,Rf)=>{"use strict";var YA=xf();kf();Rf.exports=YA});var Wo=m((pV,Lf)=>{"use strict";var zA=$f();Lf.exports=zA});var Mf=m(()=>{"use strict"});var Yo=m((mV,Cf)=>{"use strict";var Ei=z(),KA=Yt(),JA=Qt(),Es=function(a){return KA.slice(0,a.length)===a};Cf.exports=function(){return Es("Bun/")?"BUN":Es("Cloudflare-Workers")?"CLOUDFLARE":Es("Deno/")?"DENO":Es("Node.js/")?"NODE":Ei.Bun&&typeof Bun.version=="string"?"BUN":Ei.Deno&&typeof Deno.version=="object"?"DENO":JA(Ei.process)==="process"?"NODE":Ei.window&&Ei.document?"BROWSER":"REST"}()});var xs=m((bV,Df)=>{"use strict";var XA=Yo();Df.exports=XA==="NODE"});var Vf=m((gV,Of)=>{"use strict";var ZA=zt();Of.exports=function(a,e,t){return ZA.f(a,e,t)}});var Nf=m((vV,_f)=>{"use strict";var ew=at(),tw=Vf(),rw=le(),iw=xe(),Bf=rw("species");_f.exports=function(a){var e=ew(a);iw&&e&&!e[Bf]&&tw(e,Bf,{configurable:!0,get:function(){return this}})}});var qf=m((SV,Ff)=>{"use strict";var aw=ci(),sw=TypeError;Ff.exports=function(a,e){if(aw(e,a))return a;throw new sw("Incorrect invocation")}});var Ko=m((yV,Uf)=>{"use strict";var nw=te(),ow=Y(),zo=hi(),uw=nw(Function.toString);ow(zo.inspectSource)||(zo.inspectSource=function(a){return uw(a)});Uf.exports=zo.inspectSource});var Xo=m((TV,Wf)=>{"use strict";var lw=te(),cw=ue(),Hf=Y(),dw=Si(),pw=at(),hw=Ko(),jf=function(){},Gf=pw("Reflect","construct"),Jo=/^\s*(?:class|function)\b/,fw=lw(Jo.exec),mw=!Jo.test(jf),xi=function(e){if(!Hf(e))return!1;try{return Gf(jf,[],e),!0}catch(t){return!1}},Qf=function(e){if(!Hf(e))return!1;switch(dw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return mw||!!fw(Jo,hw(e))}catch(t){return!0}};Qf.sham=!0;Wf.exports=!Gf||cw(function(){var a;return xi(xi.call)||!xi(Object)||!xi(function(){a=!0})||a})?Qf:xi});var zf=m((IV,Yf)=>{"use strict";var bw=Xo(),gw=di(),vw=TypeError;Yf.exports=function(a){if(bw(a))return a;throw new vw(gw(a)+" is not a constructor")}});var Zo=m((EV,Jf)=>{"use strict";var Kf=Je(),Sw=zf(),yw=Ir(),Tw=le(),Iw=Tw("species");Jf.exports=function(a,e){var t=Kf(a).constructor,r;return t===void 0||yw(r=Kf(t)[Iw])?e:Sw(r)}});var Zf=m((xV,Xf)=>{"use strict";var Ew=te();Xf.exports=Ew([].slice)});var tm=m((PV,em)=>{"use strict";var xw=TypeError;em.exports=function(a,e){if(a<e)throw new xw("Not enough arguments");return a}});var eu=m((AV,rm)=>{"use strict";var Pw=Yt();rm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Pw)});var lu=m((wV,dm)=>{"use strict";var we=z(),Aw=Un(),ww=Ar(),im=Y(),kw=je(),cm=ue(),am=Co(),Rw=Zf(),sm=as(),$w=tm(),Lw=eu(),Mw=xs(),nu=we.setImmediate,ou=we.clearImmediate,Cw=we.process,tu=we.Dispatch,Dw=we.Function,nm=we.MessageChannel,Ow=we.String,ru=0,Pi={},om="onreadystatechange",Ai,Xt,iu,au;cm(function(){Ai=we.location});var uu=function(a){if(kw(Pi,a)){var e=Pi[a];delete Pi[a],e()}},su=function(a){return function(){uu(a)}},um=function(a){uu(a.data)},lm=function(a){we.postMessage(Ow(a),Ai.protocol+"//"+Ai.host)};(!nu||!ou)&&(nu=function(e){$w(arguments.length,1);var t=im(e)?e:Dw(e),r=Rw(arguments,1);return Pi[++ru]=function(){Aw(t,void 0,r)},Xt(ru),ru},ou=function(e){delete Pi[e]},Mw?Xt=function(a){Cw.nextTick(su(a))}:tu&&tu.now?Xt=function(a){tu.now(su(a))}:nm&&!Lw?(iu=new nm,au=iu.port2,iu.port1.onmessage=um,Xt=ww(au.postMessage,au)):we.addEventListener&&im(we.postMessage)&&!we.importScripts&&Ai&&Ai.protocol!=="file:"&&!cm(lm)?(Xt=lm,we.addEventListener("message",um,!1)):om in sm("script")?Xt=function(a){am.appendChild(sm("script"))[om]=function(){am.removeChild(this),uu(a)}}:Xt=function(a){setTimeout(su(a),0)});dm.exports={set:nu,clear:ou}});var fm=m((kV,hm)=>{"use strict";var pm=z(),Vw=xe(),Bw=Object.getOwnPropertyDescriptor;hm.exports=function(a){if(!Vw)return pm[a];var e=Bw(pm,a);return e&&e.value}});var cu=m((RV,bm)=>{"use strict";var mm=function(){this.head=null,this.tail=null};mm.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}}};bm.exports=mm});var vm=m(($V,gm)=>{"use strict";var _w=Yt();gm.exports=/ipad|iphone|ipod/i.test(_w)&&typeof Pebble!="undefined"});var ym=m((LV,Sm)=>{"use strict";var Nw=Yt();Sm.exports=/web0s(?!.*chrome)/i.test(Nw)});var wm=m((MV,Am)=>{"use strict";var Dr=z(),Fw=fm(),Tm=Ar(),du=lu().set,qw=cu(),Uw=eu(),Hw=vm(),jw=ym(),pu=xs(),Im=Dr.MutationObserver||Dr.WebKitMutationObserver,Em=Dr.document,xm=Dr.process,Ps=Dr.Promise,mu=Fw("queueMicrotask"),Cr,hu,fu,As,Pm;mu||(wi=new qw,ki=function(){var a,e;for(pu&&(a=xm.domain)&&a.exit();e=wi.get();)try{e()}catch(t){throw wi.head&&Cr(),t}a&&a.enter()},!Uw&&!pu&&!jw&&Im&&Em?(hu=!0,fu=Em.createTextNode(""),new Im(ki).observe(fu,{characterData:!0}),Cr=function(){fu.data=hu=!hu}):!Hw&&Ps&&Ps.resolve?(As=Ps.resolve(void 0),As.constructor=Ps,Pm=Tm(As.then,As),Cr=function(){Pm(ki)}):pu?Cr=function(){xm.nextTick(ki)}:(du=Tm(du,Dr),Cr=function(){du(ki)}),mu=function(a){wi.head||Cr(),wi.add(a)});var wi,ki;Am.exports=mu});var Rm=m((CV,km)=>{"use strict";km.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ws=m((DV,$m)=>{"use strict";$m.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Zt=m((OV,Lm)=>{"use strict";var Gw=z();Lm.exports=Gw.Promise});var Or=m((VV,Om)=>{"use strict";var Qw=z(),Ri=Zt(),Ww=Y(),Yw=co(),zw=Ko(),Kw=le(),Mm=Yo(),Jw=He(),bu=Jn(),Cm=Ri&&Ri.prototype,Xw=Kw("species"),gu=!1,Dm=Ww(Qw.PromiseRejectionEvent),Zw=Yw("Promise",function(){var a=zw(Ri),e=a!==String(Ri);if(!e&&bu===66||Jw&&!(Cm.catch&&Cm.finally))return!0;if(!bu||bu<51||!/native code/.test(a)){var t=new Ri(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Xw]=r,gu=t.then(function(){})instanceof r,!gu)return!0}return!e&&(Mm==="BROWSER"||Mm==="DENO")&&!Dm});Om.exports={CONSTRUCTOR:Zw,REJECTION_EVENT:Dm,SUBCLASSING:gu}});var Vr=m((BV,Bm)=>{"use strict";var Vm=Ke(),ek=TypeError,tk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new ek("Bad Promise constructor");e=r,t=i}),this.resolve=Vm(e),this.reject=Vm(t)};Bm.exports.f=function(a){return new tk(a)}});var rb=m(()=>{"use strict";var rk=X(),ik=He(),Ls=xs(),At=z(),Fr=Pe(),_m=Mr(),Nm=Uo(),ak=yi(),sk=Nf(),nk=Ke(),$s=Y(),ok=Ae(),uk=qf(),lk=Zo(),jm=lu().set,Iu=wm(),ck=Rm(),dk=ws(),pk=cu(),Gm=Ro(),Ms=Zt(),Eu=Or(),Qm=Vr(),Cs="Promise",Wm=Eu.CONSTRUCTOR,hk=Eu.REJECTION_EVENT,fk=Eu.SUBCLASSING,vu=Gm.getterFor(Cs),mk=Gm.set,Br=Ms&&Ms.prototype,er=Ms,ks=Br,Ym=At.TypeError,Su=At.document,xu=At.process,yu=Qm.f,bk=yu,gk=!!(Su&&Su.createEvent&&At.dispatchEvent),zm="unhandledrejection",vk="rejectionhandled",Fm=0,Km=1,Sk=2,Pu=1,Jm=2,Rs,qm,yk,Um,Xm=function(a){var e;return ok(a)&&$s(e=a.then)?e:!1},Zm=function(a,e){var t=e.value,r=e.state===Km,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Jm&&Ik(e),e.rejection=Pu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Ym("Promise-chain cycle")):(l=Xm(u))?Fr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},eb=function(a,e){a.notified||(a.notified=!0,Iu(function(){for(var t=a.reactions,r;r=t.get();)Zm(r,a);a.notified=!1,e&&!a.rejection&&Tk(a)}))},tb=function(a,e,t){var r,i;gk?(r=Su.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),At.dispatchEvent(r)):r={promise:e,reason:t},!hk&&(i=At["on"+a])?i(r):a===zm&&ck("Unhandled promise rejection",t)},Tk=function(a){Fr(jm,At,function(){var e=a.facade,t=a.value,r=Hm(a),i;if(r&&(i=dk(function(){Ls?xu.emit("unhandledRejection",t,e):tb(zm,e,t)}),a.rejection=Ls||Hm(a)?Jm:Pu,i.error))throw i.value})},Hm=function(a){return a.rejection!==Pu&&!a.parent},Ik=function(a){Fr(jm,At,function(){var e=a.facade;Ls?xu.emit("rejectionHandled",e):tb(vk,e,a.value)})},_r=function(a,e,t){return function(r){a(e,r,t)}},Nr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Sk,eb(a,!0))},Tu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Ym("Promise can't be resolved itself");var r=Xm(e);r?Iu(function(){var i={done:!1};try{Fr(r,e,_r(Tu,i,a),_r(Nr,i,a))}catch(s){Nr(i,s,a)}}):(a.value=e,a.state=Km,eb(a,!1))}catch(i){Nr({done:!1},i,a)}}};if(Wm&&(er=function(e){uk(this,ks),nk(e),Fr(Rs,this);var t=vu(this);try{e(_r(Tu,t),_r(Nr,t))}catch(r){Nr(t,r)}},ks=er.prototype,Rs=function(e){mk(this,{type:Cs,done:!1,notified:!1,parent:!1,reactions:new pk,rejection:!1,state:Fm,value:void 0})},Rs.prototype=_m(ks,"then",function(e,t){var r=vu(this),i=yu(lk(this,er));return r.parent=!0,i.ok=$s(e)?e:!0,i.fail=$s(t)&&t,i.domain=Ls?xu.domain:void 0,r.state===Fm?r.reactions.add(i):Iu(function(){Zm(i,r)}),i.promise}),qm=function(){var a=new Rs,e=vu(a);this.promise=a,this.resolve=_r(Tu,e),this.reject=_r(Nr,e)},Qm.f=yu=function(a){return a===er||a===yk?new qm(a):bk(a)},!ik&&$s(Ms)&&Br!==Object.prototype)){Um=Br.then,fk||_m(Br,"then",function(e,t){var r=this;return new er(function(i,s){Fr(Um,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Br.constructor}catch(a){}Nm&&Nm(Br,ks)}rk({global:!0,constructor:!0,wrap:!0,forced:Wm},{Promise:er});ak(er,Cs,!1,!0);sk(Cs)});var ob=m((FV,nb)=>{"use strict";var Ek=le(),ab=Ek("iterator"),sb=!1;try{ib=0,Au={next:function(){return{done:!!ib++}},return:function(){sb=!0}},Au[ab]=function(){return this},Array.from(Au,function(){throw 2})}catch(a){}var ib,Au;nb.exports=function(a,e){try{if(!e&&!sb)return!1}catch(i){return!1}var t=!1;try{var r={};r[ab]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var wu=m((qV,ub)=>{"use strict";var xk=Zt(),Pk=ob(),Ak=Or().CONSTRUCTOR;ub.exports=Ak||!Pk(function(a){xk.all(a).then(void 0,function(){})})});var lb=m(()=>{"use strict";var wk=X(),kk=Pe(),Rk=Ke(),$k=Vr(),Lk=ws(),Mk=Ts(),Ck=wu();wk({target:"Promise",stat:!0,forced:Ck},{all:function(e){var t=this,r=$k.f(t),i=r.resolve,s=r.reject,n=Lk(function(){var o=Rk(t.resolve),u=[],l=0,c=1;Mk(e,function(d){var h=l++,p=!1;c++,kk(o,t,d).then(function(f){p||(p=!0,u[h]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var db=m(()=>{"use strict";var Dk=X(),Ok=He(),Vk=Or().CONSTRUCTOR,Ru=Zt(),Bk=at(),_k=Y(),Nk=Mr(),cb=Ru&&Ru.prototype;Dk({target:"Promise",proto:!0,forced:Vk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Ok&&_k(Ru)&&(ku=Bk("Promise").prototype.catch,cb.catch!==ku&&Nk(cb,"catch",ku,{unsafe:!0}));var ku});var pb=m(()=>{"use strict";var Fk=X(),qk=Pe(),Uk=Ke(),Hk=Vr(),jk=ws(),Gk=Ts(),Qk=wu();Fk({target:"Promise",stat:!0,forced:Qk},{race:function(e){var t=this,r=Hk.f(t),i=r.reject,s=jk(function(){var n=Uk(t.resolve);Gk(e,function(o){qk(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var hb=m(()=>{"use strict";var Wk=X(),Yk=Vr(),zk=Or().CONSTRUCTOR;Wk({target:"Promise",stat:!0,forced:zk},{reject:function(e){var t=Yk.f(this),r=t.reject;return r(e),t.promise}})});var $u=m((KV,fb)=>{"use strict";var Kk=Je(),Jk=Ae(),Xk=Vr();fb.exports=function(a,e){if(Kk(a),Jk(e)&&e.constructor===a)return e;var t=Xk.f(a),r=t.resolve;return r(e),t.promise}});var gb=m(()=>{"use strict";var Zk=X(),eR=at(),mb=He(),tR=Zt(),bb=Or().CONSTRUCTOR,rR=$u(),iR=eR("Promise"),aR=mb&&!bb;Zk({target:"Promise",stat:!0,forced:mb||bb},{resolve:function(e){return rR(aR&&this===iR?tR:this,e)}})});var vb=m(()=>{"use strict";rb();lb();db();pb();hb();gb()});var Ib=m(()=>{"use strict";var sR=X(),nR=He(),Ds=Zt(),oR=ue(),yb=at(),Tb=Y(),uR=Zo(),Sb=$u(),lR=Mr(),Mu=Ds&&Ds.prototype,cR=!!Ds&&oR(function(){Mu.finally.call({then:function(){}},function(){})});sR({target:"Promise",proto:!0,real:!0,forced:cR},{finally:function(a){var e=uR(this,yb("Promise")),t=Tb(a);return this.then(t?function(r){return Sb(e,a()).then(function(){return r})}:a,t?function(r){return Sb(e,a()).then(function(){throw r})}:a)}});!nR&&Tb(Ds)&&(Lu=yb("Promise").prototype.finally,Mu.finally!==Lu&&lR(Mu,"finally",Lu,{unsafe:!0}));var Lu});var xb=m((iB,Eb)=>{"use strict";Mf();vb();Ib();var dR=Pt();Eb.exports=dR("Promise","finally")});var Ab=m((aB,Pb)=>{"use strict";var pR=xb();Pb.exports=pR});var Os=m((sB,wb)=>{"use strict";var hR=Ab();wb.exports=hR});var Fb=m(()=>{"use strict";var wR=X(),kR=Po().values;wR({target:"Object",stat:!0},{values:function(e){return kR(e)}})});var Ub=m((HB,qb)=>{"use strict";Fb();var RR=Er();qb.exports=RR.Object.values});var jb=m((jB,Hb)=>{"use strict";var $R=Ub();Hb.exports=$R});var Li=m((GB,Gb)=>{"use strict";var LR=jb();Gb.exports=LR});var ag=m(()=>{"use strict";var WR=X(),YR=xr(),zR=$r(),KR=bi(),JR=gi();WR({target:"Array",proto:!0},{at:function(e){var t=YR(this),r=zR(t),i=KR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});JR("at")});var ng=m((S_,sg)=>{"use strict";ag();var XR=Pt();sg.exports=XR("Array","at")});var ug=m((y_,og)=>{"use strict";var ZR=ng();og.exports=ZR});var Hr=m((T_,lg)=>{"use strict";var e$=ug();lg.exports=e$});var tl=m((WN,Ng)=>{"use strict";var O$=Qt();Ng.exports=Array.isArray||function(e){return O$(e)==="Array"}});var qg=m((YN,Fg)=>{"use strict";var V$=TypeError,B$=9007199254740991;Fg.exports=function(a){if(a>B$)throw V$("Maximum allowed index exceeded");return a}});var jg=m((zN,Hg)=>{"use strict";var _$=tl(),N$=$r(),F$=qg(),q$=Ar(),Ug=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?q$(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&_$(d)?(h=N$(d),u=Ug(a,e,d,h,u,s-1)-1):(F$(u+1),a[u]=d),u++),l++;return u};Hg.exports=Ug});var Yg=m((KN,Wg)=>{"use strict";var Gg=tl(),U$=Xo(),H$=Ae(),j$=le(),G$=j$("species"),Qg=Array;Wg.exports=function(a){var e;return Gg(a)&&(e=a.constructor,U$(e)&&(e===Qg||Gg(e.prototype))?e=void 0:H$(e)&&(e=e[G$],e===null&&(e=void 0))),e===void 0?Qg:e}});var Kg=m((JN,zg)=>{"use strict";var Q$=Yg();zg.exports=function(a,e){return new(Q$(a))(e===0?0:e)}});var Jg=m(()=>{"use strict";var W$=X(),Y$=jg(),z$=Ke(),K$=xr(),J$=$r(),X$=Kg();W$({target:"Array",proto:!0},{flatMap:function(e){var t=K$(this),r=J$(t),i;return z$(e),i=X$(t,0),i.length=Y$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Xg=m(()=>{"use strict";var Z$=gi();Z$("flatMap")});var ev=m((rF,Zg)=>{"use strict";Jg();Xg();var eL=Pt();Zg.exports=eL("Array","flatMap")});var rv=m((iF,tv)=>{"use strict";var tL=ev();tv.exports=tL});var rl=m((aF,iv)=>{"use strict";var rL=rv();iv.exports=rL});var Gi=m((fF,Ev)=>{"use strict";var cL=Si(),dL=String;Ev.exports=function(a){if(cL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return dL(a)}});var al=m((mF,xv)=>{"use strict";xv.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 wv=m((bF,Av)=>{"use strict";var pL=te(),hL=xt(),fL=Gi(),nl=al(),Pv=pL("".replace),mL=RegExp("^["+nl+"]+"),bL=RegExp("(^|[^"+nl+"])["+nl+"]+$"),sl=function(a){return function(e){var t=fL(hL(e));return a&1&&(t=Pv(t,mL,"")),a&2&&(t=Pv(t,bL,"$1")),t}};Av.exports={start:sl(1),end:sl(2),trim:sl(3)}});var Lv=m((gF,$v)=>{"use strict";var gL=Mo().PROPER,vL=ue(),kv=al(),Rv="\u200B\x85\u180E";$v.exports=function(a){return vL(function(){return!!kv[a]()||Rv[a]()!==Rv||gL&&kv[a].name!==a})}});var ol=m((vF,Mv)=>{"use strict";var SL=wv().start,yL=Lv();Mv.exports=yL("trimStart")?function(){return SL(this)}:"".trimStart});var Dv=m(()=>{"use strict";var TL=X(),Cv=ol();TL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Cv},{trimLeft:Cv})});var Vv=m(()=>{"use strict";Dv();var IL=X(),Ov=ol();IL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ov},{trimStart:Ov})});var _v=m((EF,Bv)=>{"use strict";Vv();var EL=Pt();Bv.exports=EL("String","trimLeft")});var Fv=m((xF,Nv)=>{"use strict";var xL=_v();Nv.exports=xL});var Uv=m((PF,qv)=>{"use strict";var PL=Fv();qv.exports=PL});var aS=m(()=>{"use strict"});var sS=m(()=>{"use strict"});var oS=m((zU,nS)=>{"use strict";var YL=Ae(),zL=Qt(),KL=le(),JL=KL("match");nS.exports=function(a){var e;return YL(a)&&((e=a[JL])!==void 0?!!e:zL(a)==="RegExp")}});var lS=m((KU,uS)=>{"use strict";var XL=Je();uS.exports=function(){var a=XL(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 pS=m((JU,dS)=>{"use strict";var ZL=Pe(),eM=je(),tM=ci(),rM=lS(),cS=RegExp.prototype;dS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in cS)&&!eM(a,"flags")&&tM(cS,a)?ZL(rM,a):e}});var fS=m((XU,hS)=>{"use strict";var bl=te(),iM=xr(),aM=Math.floor,fl=bl("".charAt),sM=bl("".replace),ml=bl("".slice),nM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,oM=/\$([$&'`]|\d{1,2})/g;hS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=oM;return i!==void 0&&(i=iM(i),u=nM),sM(s,u,function(l,c){var d;switch(fl(c,0)){case"$":return"$";case"&":return a;case"`":return ml(e,0,t);case"'":return ml(e,n);case"<":d=i[ml(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=aM(h/10);return p===0?l:p<=o?r[p-1]===void 0?fl(c,1):r[p-1]+fl(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var gS=m(()=>{"use strict";var uM=X(),lM=Pe(),vl=te(),mS=xt(),cM=Y(),dM=Ir(),pM=oS(),zr=Gi(),hM=pi(),fM=pS(),mM=fS(),bM=le(),gM=He(),vM=bM("replace"),SM=TypeError,gl=vl("".indexOf),yM=vl("".replace),bS=vl("".slice),TM=Math.max;uM({target:"String",proto:!0},{replaceAll:function(e,t){var r=mS(this),i,s,n,o,u,l,c,d,h,p,f=0,b="";if(!dM(e)){if(i=pM(e),i&&(s=zr(mS(fM(e))),!~gl(s,"g")))throw new SM("`.replaceAll` does not allow non-global regexes");if(n=hM(e,vM),n)return lM(n,e,r,t);if(gM&&i)return yM(zr(r),e,t)}for(o=zr(r),u=zr(e),l=cM(t),l||(t=zr(t)),c=u.length,d=TM(1,c),h=gl(o,u);h!==-1;)p=l?zr(t(u,h,o)):mM(u,o,h,[],void 0,t),b+=bS(o,f,h)+p,f=h+c,h=h+d>o.length?-1:gl(o,u,h+d);return f<o.length&&(b+=bS(o,f)),b}})});var SS=m((t1,vS)=>{"use strict";aS();sS();gS();var IM=Pt();vS.exports=IM("String","replaceAll")});var TS=m((r1,yS)=>{"use strict";var EM=SS();yS.exports=EM});var ES=m((i1,IS)=>{"use strict";var xM=TS();IS.exports=xM});var PS=m((a1,xS)=>{"use strict";var PM=bi(),AM=Gi(),wM=xt(),kM=RangeError;xS.exports=function(e){var t=AM(wM(this)),r="",i=PM(e);if(i<0||i===1/0)throw new kM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var $S=m((s1,RS)=>{"use strict";var kS=te(),RM=go(),AS=Gi(),$M=PS(),LM=xt(),MM=kS($M),CM=kS("".slice),DM=Math.ceil,wS=function(a){return function(e,t,r){var i=AS(LM(e)),s=RM(t),n=i.length,o=r===void 0?" ":AS(r),u,l;return s<=n||o===""?i:(u=s-n,l=MM(o,DM(u/o.length)),l.length>u&&(l=CM(l,0,u)),a?i+l:l+i)}};RS.exports={start:wS(!1),end:wS(!0)}});var MS=m((n1,LS)=>{"use strict";var OM=Yt();LS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(OM)});var CS=m(()=>{"use strict";var VM=X(),BM=$S().start,_M=MS();VM({target:"String",proto:!0,forced:_M},{padStart:function(e){return BM(this,e,arguments.length>1?arguments[1]:void 0)}})});var OS=m((l1,DS)=>{"use strict";CS();var NM=Pt();DS.exports=NM("String","padStart")});var BS=m((c1,VS)=>{"use strict";var FM=OS();VS.exports=FM});var NS=m((d1,_S)=>{"use strict";var qM=BS();_S.exports=qM});var Oc="2.0.123-dev.8ba72ee5.0";var me=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(me||{}),Et=(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))(Et||{});var ts=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ts||{}),Nn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Nn||{});var Fn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Fn||{});var mT=V(Xe(),1);import{assertNever as Cp,assertNonNullable as ex,isNonNullable as ns,ValueSubject as So,Subject as tx,Subscription as rx,merge as ix,observableFrom as ax,fromEvent as Rp,map as $p,tap as Lp,filterChanged as sx,isNullable as yo,ErrorCategory as Mp}from"@vkontakte/videoplayer-shared/es2018";var kp=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 os=class{constructor(e){this.connection$=new So(void 0);this.castState$=new So("NOT_AVAILABLE");this.errorEvent$=new tx;this.realCastState$=new So("NOT_AVAILABLE");this.subscription=new rx;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=ns((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||kp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Mp.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(){ns(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();yo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();yo(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(Rp(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 Cp(i.sessionState)}})).add(ix(Rp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Lp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),$p(i=>i.castState)),ax([r.getCastState()])).pipe(sx(),$p(nx),Lp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=ns(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();ex(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(yo(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"?ns(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:Mp.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 Cp(a)}};var Yl=V(Xe(),1),zy=V(Lr(),1),Ky=V(Wo(),1);var Bb=V(Os(),1);import{assertNever as kb}from"@vkontakte/videoplayer-shared/es2018";var ce=(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:kb(t)}return a},Vs=(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:kb(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as fR,Subject as Bs,merge as Rb}from"@vkontakte/videoplayer-shared/es2018";var L=class{constructor(e){this.transitionStarted$=new Bs;this.transitionEnded$=new Bs;this.transitionUpdated$=new Bs;this.forceChanged$=new Bs;this.stateChangeStarted$=Rb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Rb(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||fR(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 mR}from"@vkontakte/videoplayer-shared/es2018";var $b=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return mR(a)}};import{assertNever as qr,assertNonNullable as tr,debounce as Lb,ErrorCategory as Mb,fromEvent as rr,isNonNullable as Cb,map as Db,merge as Ob,observableFrom as bR,Subject as gR,Subscription as Cu,timeout as vR,getHighestQuality as SR}from"@vkontakte/videoplayer-shared/es2018";var yR=5,TR=5,IR=500,Vb=7e3,$i=class{constructor(e){this.subscription=new Cu;this.loadMediaTimeoutSubscription=new Cu;this.videoState=new L("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:qr(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:qr(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:qr(e)}break}default:qr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next($b(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 Cu;this.subscription.add(e),this.subscription.add(Ob(this.videoState.stateChangeStarted$.pipe(Db(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Db(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 gR;e.add(i.pipe(Lb(IR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(rr(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)>yR)&&i.next(o),s=o})),e.add(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(rr(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<TR&&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:qr(n)}}),t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Ob(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,bR(["init"])).pipe(Lb(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];tr(c);let d=SR(Object.keys(c));tr(d);let h=c[d];tr(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];tr(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];tr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];tr(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];tr(c),r=ce(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:Mb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return qr(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 Cb(o)&&(n.metadata.title=o),Cb(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(vR(Vb).subscribe(()=>s(`timeout(${Vb})`)))});(0,Bb.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:Mb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Zu=V(Xe(),1);import{clearVideoElement as Nb}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as ER}from"@vkontakte/videoplayer-shared/es2018";var _b=a=>{try{a.pause(),a.playbackRate=0,ER(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as xR,Subscription as PR}from"@vkontakte/videoplayer-shared/es2018";var Du=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)}},Ou=window.WeakMap?new WeakMap:new Du,Vu=window.WeakMap?new WeakMap:new Map,AR=(a,e=20)=>{let t=0;return xR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},be=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Nb(t):(t=document.createElement("video"),a.appendChild(t)),Ou.set(t,r);let i=new PR;return i.add(AR(t,e)),Vu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ge=a=>{let e=Vu.get(a);e==null||e.unsubscribe(),Vu.delete(a);let t=Ou.get(a);Ou.delete(a),t?Nb(a):_b(a)};var _u=V(Li(),1);import{assertNonNullable as Mi,isNonNullable as et,isNullable as DR,fromEvent as Ur,merge as Qb,observableFrom as Wb,filterChanged as Yb,map as Ci,Subject as zb,Subscription as OR,ValueSubject as VR,ErrorCategory as BR}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Bu,isNullable as MR,Subscription as CR}from"@vkontakte/videoplayer-shared/es2018";var _s=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=MR(i),l=new CR;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},Ze=(a,e,t)=>_s(e,()=>a.loop,r=>{Bu(r)&&(a.loop=r)},{onError:t}),ve=(a,e,t,r)=>_s(e,()=>({muted:a.muted,volume:a.volume}),i=>{Bu(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}),De=(a,e,t,r)=>_s(e,()=>a.playbackRate,i=>{Bu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),wt=_s;var _R=a=>["__",a.language,a.label].join("|"),NR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Nu=class a{constructor(){this.available$=new zb;this.current$=new VR(void 0);this.error$=new zb;this.subscription=new OR;this.externalTracks=new Map;this.internalTracks=new Map}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(wt(t.internalTextTracks,()=>(0,_u.default)(this.internalTracks),s=>{et(s)&&this.setInternal(s)},{equal:(s,n)=>et(s)&&et(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ci(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(wt(t.externalTextTracks,()=>(0,_u.default)(this.externalTracks),s=>{et(s)&&this.setExternal(s)},{equal:(s,n)=>et(s)&&et(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ci(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(wt(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(wt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Mi(this.video);let{textTracks:e}=this.video;this.subscription.add(Ur(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Qb(Ur(e,"addtrack"),Ur(e,"removetrack"),Wb(["init"])).pipe(Ci(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Yb((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Qb(Ur(e,"change"),Wb(["init"])).pipe(Ci(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ci(r=>r&&this.htmlTextTrackToITextTrack(r).id),Yb()).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(Ur(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Ur(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;et(t.align)&&(i.align=t.align),et(t.position)&&(i.position=t.position),et(t.size)&&(i.size=t.size),et(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Mi(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:_R(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){Mi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(DR(e)||!NR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Mi(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Mi(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)}},Oe=Nu;var ot=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 Kb=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},Fu=a=>{let e=Kb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Jb=a=>{let e=Kb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ve,map as kt,merge as Zb,filterChanged as qR,isNonNullable as eg,Subject as UR,filter as tg,mapTo as rg,combine as HR,once as jR,ErrorCategory as GR,ValueSubject as ig,clientChecker as QR}from"@vkontakte/videoplayer-shared/es2018";var FR=3,Xb=(a,e,t=FR)=>{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 Se=a=>{let e=y=>Ve(a,y).pipe(rg(void 0)),r=Zb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Ve(a,y))).pipe(kt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),qR()),i=Zb(Ve(a,"progress"),Ve(a,"timeupdate")).pipe(kt(()=>Xb(a.buffered,a.currentTime))),s=QR.isSafari?HR({play:e("play").pipe(jR()),playing:e("playing")}).pipe(rg(void 0)):e("playing"),n=Ve(a,"volumechange").pipe(kt(()=>({muted:a.muted,volume:a.volume}))),o=Ve(a,"ratechange").pipe(kt(()=>a.playbackRate)),u=Ve(a,"error").pipe(tg(()=>!!(a.error||a.played.length)),kt(()=>{var E;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:GR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=Ve(a,"timeupdate").pipe(kt(()=>a.currentTime)),c=new UR,d=.3,h;l.subscribe(y=>{a.loop&&eg(h)&&eg(y)&&h>=a.duration-d&&y<=d&&c.next(h),h=y});let p=e("pause").pipe(tg(()=>!a.error&&h!==a.duration)),f=Ve(a,"enterpictureinpicture"),b=Ve(a,"leavepictureinpicture"),g=new ig(Jb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new ig(Fu(a));return Ve(a,"fullscreenchange").pipe(kt(()=>Fu(a))).subscribe(v),{playing$:s,pause$:p,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$:Ve(a,"durationchange").pipe(kt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as Rt}from"@vkontakte/videoplayer-shared/es2018";var $t=a=>{switch(a){case"mobile":return Rt.Q_144P;case"lowest":return Rt.Q_240P;case"low":return Rt.Q_360P;case"sd":case"medium":return Rt.Q_480P;case"hd":case"high":return Rt.Q_720P;case"fullhd":case"full":return Rt.Q_1080P;case"quadhd":case"quad":return Rt.Q_1440P;case"ultrahd":case"ultra":return Rt.Q_2160P}};var Lt=V(Hr(),1),bg=V(Xe(),1),Ns=V(Lr(),1);import{isNonNullable as re,isNullable as Uu,now as gg,isHigher as Hu,isHigherOrEqual as ju,isInvariantQuality as hg,isLower as fg,isLowerOrEqual as Gu,videoSizeToQuality as t$,assertNotEmptyArray as vg,assertNonNullable as r$}from"@vkontakte/videoplayer-shared/es2018";var qu=!1,ut={},cg=a=>{qu=a},dg=()=>{ut={}},pg=a=>{a(ut)},Di=(a,e)=>{var t;qu&&(ut.meta=(t=ut.meta)!=null?t:{},ut.meta[a]=e)},pe=class{constructor(e){this.name=e}next(e){var r,i;if(!qu)return;ut.series=(r=ut.series)!=null?r:{};let t=(i=ut.series[this.name])!=null?i:[];t.push([Date.now(),e]),ut.series[this.name]=t}};var i$=new pe("best_bitrate"),Sg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Qu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Oi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=gg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},yg='Assertion "ABR Tracks is empty array" failed',Fs=(a,e,t,r)=>{var u;let i=[...e].sort(Qu(1)),s=[...t].sort(Qu(1)),n=s.filter(l=>re(l.bitrate)&&re(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Lt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Lt.default)(s,-1);return o&&(0,bg.default)(n,o)?o:n.length?(0,Lt.default)(n,-1):(0,Lt.default)(s,0)},mg=a=>"quality"in a,Tg=(a,e,t,r)=>{var n;let i=re((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&re(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&gg()-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=mg(o)?"video":"audio",l=mg(o)?o.quality:o.bitrate;return e({message:`
6
+ var MT=Object.create;var qc=Object.defineProperty;var CT=Object.getOwnPropertyDescriptor;var DT=Object.getOwnPropertyNames;var OT=Object.getPrototypeOf,BT=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var VT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of DT(e))!BT.call(a,i)&&i!==t&&qc(a,i,{get:()=>e[i],enumerable:!(r=CT(e,i))||r.enumerable});return a};var B=(a,e,t)=>(t=a!=null?MT(OT(a)):{},VT(e||!a||!a.__esModule?qc(t,"default",{value:a,enumerable:!0}):t,a));var J=m((Wn,Hc)=>{"use strict";var mi=function(a){return a&&a.Math===Math&&a};Hc.exports=mi(typeof globalThis=="object"&&globalThis)||mi(typeof window=="object"&&window)||mi(typeof self=="object"&&self)||mi(typeof global=="object"&&global)||mi(typeof Wn=="object"&&Wn)||function(){return this}()||Function("return this")()});var ue=m((oD,jc)=>{"use strict";jc.exports=function(a){try{return!!a()}catch(e){return!0}}});var bi=m((uD,Gc)=>{"use strict";var _T=ue();Gc.exports=!_T(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Yn=m((lD,zc)=>{"use strict";var NT=bi(),Yc=Function.prototype,Qc=Yc.apply,Wc=Yc.call;zc.exports=typeof Reflect=="object"&&Reflect.apply||(NT?Wc.bind(Qc):function(){return Wc.apply(Qc,arguments)})});var re=m((cD,Xc)=>{"use strict";var Kc=bi(),Jc=Function.prototype,zn=Jc.call,FT=Kc&&Jc.bind.bind(zn,zn);Xc.exports=Kc?FT:function(a){return function(){return zn.apply(a,arguments)}}});var Jt=m((dD,ed)=>{"use strict";var Zc=re(),qT=Zc({}.toString),UT=Zc("".slice);ed.exports=function(a){return UT(qT(a),8,-1)}});var Kn=m((pD,td)=>{"use strict";var HT=Jt(),jT=re();td.exports=function(a){if(HT(a)==="Function")return jT(a)}});var z=m((hD,rd)=>{"use strict";var Jn=typeof document=="object"&&document.all;rd.exports=typeof Jn=="undefined"&&Jn!==void 0?function(a){return typeof a=="function"||a===Jn}:function(a){return typeof a=="function"}});var we=m((fD,id)=>{"use strict";var GT=ue();id.exports=!GT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ae=m((mD,ad)=>{"use strict";var QT=bi(),ls=Function.prototype.call;ad.exports=QT?ls.bind(ls):function(){return ls.apply(ls,arguments)}});var Xn=m(od=>{"use strict";var sd={}.propertyIsEnumerable,nd=Object.getOwnPropertyDescriptor,WT=nd&&!sd.call({1:2},1);od.f=WT?function(e){var t=nd(this,e);return!!t&&t.enumerable}:sd});var gi=m((gD,ud)=>{"use strict";ud.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var cd=m((vD,ld)=>{"use strict";var YT=re(),zT=ue(),KT=Jt(),Zn=Object,JT=YT("".split);ld.exports=zT(function(){return!Zn("z").propertyIsEnumerable(0)})?function(a){return KT(a)==="String"?JT(a,""):Zn(a)}:Zn});var kr=m((SD,dd)=>{"use strict";dd.exports=function(a){return a==null}});var At=m((yD,pd)=>{"use strict";var XT=kr(),ZT=TypeError;pd.exports=function(a){if(XT(a))throw new ZT("Can't call method on "+a);return a}});var Xt=m((TD,hd)=>{"use strict";var eI=cd(),tI=At();hd.exports=function(a){return eI(tI(a))}});var ke=m((ID,fd)=>{"use strict";var rI=z();fd.exports=function(a){return typeof a=="object"?a!==null:rI(a)}});var Rr=m((ED,md)=>{"use strict";md.exports={}});var nt=m((xD,gd)=>{"use strict";var eo=Rr(),to=J(),iI=z(),bd=function(a){return iI(a)?a:void 0};gd.exports=function(a,e){return arguments.length<2?bd(eo[a])||bd(to[a]):eo[a]&&eo[a][e]||to[a]&&to[a][e]}});var vi=m((PD,vd)=>{"use strict";var aI=re();vd.exports=aI({}.isPrototypeOf)});var Zt=m((wD,Td)=>{"use strict";var sI=J(),Sd=sI.navigator,yd=Sd&&Sd.userAgent;Td.exports=yd?String(yd):""});var io=m((AD,Ad)=>{"use strict";var wd=J(),ro=Zt(),Id=wd.process,Ed=wd.Deno,xd=Id&&Id.versions||Ed&&Ed.version,Pd=xd&&xd.v8,je,cs;Pd&&(je=Pd.split("."),cs=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!cs&&ro&&(je=ro.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=ro.match(/Chrome\/(\d+)/),je&&(cs=+je[1])));Ad.exports=cs});var ao=m((kD,Rd)=>{"use strict";var kd=io(),nI=ue(),oI=J(),uI=oI.String;Rd.exports=!!Object.getOwnPropertySymbols&&!nI(function(){var a=Symbol("symbol detection");return!uI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&kd&&kd<41})});var so=m((RD,$d)=>{"use strict";var lI=ao();$d.exports=lI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var no=m(($D,Ld)=>{"use strict";var cI=nt(),dI=z(),pI=vi(),hI=so(),fI=Object;Ld.exports=hI?function(a){return typeof a=="symbol"}:function(a){var e=cI("Symbol");return dI(e)&&pI(e.prototype,fI(a))}});var Si=m((LD,Md)=>{"use strict";var mI=String;Md.exports=function(a){try{return mI(a)}catch(e){return"Object"}}});var Ze=m((MD,Cd)=>{"use strict";var bI=z(),gI=Si(),vI=TypeError;Cd.exports=function(a){if(bI(a))return a;throw new vI(gI(a)+" is not a function")}});var yi=m((CD,Dd)=>{"use strict";var SI=Ze(),yI=kr();Dd.exports=function(a,e){var t=a[e];return yI(t)?void 0:SI(t)}});var Bd=m((DD,Od)=>{"use strict";var oo=Ae(),uo=z(),lo=ke(),TI=TypeError;Od.exports=function(a,e){var t,r;if(e==="string"&&uo(t=a.toString)&&!lo(r=oo(t,a))||uo(t=a.valueOf)&&!lo(r=oo(t,a))||e!=="string"&&uo(t=a.toString)&&!lo(r=oo(t,a)))return r;throw new TI("Can't convert object to primitive value")}});var Ge=m((OD,Vd)=>{"use strict";Vd.exports=!0});var Fd=m((BD,Nd)=>{"use strict";var _d=J(),II=Object.defineProperty;Nd.exports=function(a,e){try{II(_d,a,{value:e,configurable:!0,writable:!0})}catch(t){_d[a]=e}return e}});var Ti=m((VD,Hd)=>{"use strict";var EI=Ge(),xI=J(),PI=Fd(),qd="__core-js_shared__",Ud=Hd.exports=xI[qd]||PI(qd,{});(Ud.versions||(Ud.versions=[])).push({version:"3.38.0",mode:EI?"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 co=m((_D,Gd)=>{"use strict";var jd=Ti();Gd.exports=function(a,e){return jd[a]||(jd[a]=e||{})}});var $r=m((ND,Qd)=>{"use strict";var wI=At(),AI=Object;Qd.exports=function(a){return AI(wI(a))}});var Qe=m((FD,Wd)=>{"use strict";var kI=re(),RI=$r(),$I=kI({}.hasOwnProperty);Wd.exports=Object.hasOwn||function(e,t){return $I(RI(e),t)}});var po=m((qD,Yd)=>{"use strict";var LI=re(),MI=0,CI=Math.random(),DI=LI(1 .toString);Yd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+DI(++MI+CI,36)}});var le=m((UD,Kd)=>{"use strict";var OI=J(),BI=co(),zd=Qe(),VI=po(),_I=ao(),NI=so(),Lr=OI.Symbol,ho=BI("wks"),FI=NI?Lr.for||Lr:Lr&&Lr.withoutSetter||VI;Kd.exports=function(a){return zd(ho,a)||(ho[a]=_I&&zd(Lr,a)?Lr[a]:FI("Symbol."+a)),ho[a]}});var ep=m((HD,Zd)=>{"use strict";var qI=Ae(),Jd=ke(),Xd=no(),UI=yi(),HI=Bd(),jI=le(),GI=TypeError,QI=jI("toPrimitive");Zd.exports=function(a,e){if(!Jd(a)||Xd(a))return a;var t=UI(a,QI),r;if(t){if(e===void 0&&(e="default"),r=qI(t,a,e),!Jd(r)||Xd(r))return r;throw new GI("Can't convert object to primitive value")}return e===void 0&&(e="number"),HI(a,e)}});var fo=m((jD,tp)=>{"use strict";var WI=ep(),YI=no();tp.exports=function(a){var e=WI(a,"string");return YI(e)?e:e+""}});var ds=m((GD,ip)=>{"use strict";var zI=J(),rp=ke(),mo=zI.document,KI=rp(mo)&&rp(mo.createElement);ip.exports=function(a){return KI?mo.createElement(a):{}}});var bo=m((QD,ap)=>{"use strict";var JI=we(),XI=ue(),ZI=ds();ap.exports=!JI&&!XI(function(){return Object.defineProperty(ZI("div"),"a",{get:function(){return 7}}).a!==7})});var op=m(np=>{"use strict";var eE=we(),tE=Ae(),rE=Xn(),iE=gi(),aE=Xt(),sE=fo(),nE=Qe(),oE=bo(),sp=Object.getOwnPropertyDescriptor;np.f=eE?sp:function(e,t){if(e=aE(e),t=sE(t),oE)try{return sp(e,t)}catch(r){}if(nE(e,t))return iE(!tE(rE.f,e,t),e[t])}});var go=m((YD,up)=>{"use strict";var uE=ue(),lE=z(),cE=/#|\.prototype\./,Ii=function(a,e){var t=pE[dE(a)];return t===fE?!0:t===hE?!1:lE(e)?uE(e):!!e},dE=Ii.normalize=function(a){return String(a).replace(cE,".").toLowerCase()},pE=Ii.data={},hE=Ii.NATIVE="N",fE=Ii.POLYFILL="P";up.exports=Ii});var Mr=m((zD,cp)=>{"use strict";var lp=Kn(),mE=Ze(),bE=bi(),gE=lp(lp.bind);cp.exports=function(a,e){return mE(a),e===void 0?a:bE?gE(a,e):function(){return a.apply(e,arguments)}}});var vo=m((KD,dp)=>{"use strict";var vE=we(),SE=ue();dp.exports=vE&&SE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var et=m((JD,pp)=>{"use strict";var yE=ke(),TE=String,IE=TypeError;pp.exports=function(a){if(yE(a))return a;throw new IE(TE(a)+" is not an object")}});var er=m(fp=>{"use strict";var EE=we(),xE=bo(),PE=vo(),ps=et(),hp=fo(),wE=TypeError,So=Object.defineProperty,AE=Object.getOwnPropertyDescriptor,yo="enumerable",To="configurable",Io="writable";fp.f=EE?PE?function(e,t,r){if(ps(e),t=hp(t),ps(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Io in r&&!r[Io]){var i=AE(e,t);i&&i[Io]&&(e[t]=r.value,r={configurable:To in r?r[To]:i[To],enumerable:yo in r?r[yo]:i[yo],writable:!1})}return So(e,t,r)}:So:function(e,t,r){if(ps(e),t=hp(t),ps(r),xE)try{return So(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new wE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Cr=m((ZD,mp)=>{"use strict";var kE=we(),RE=er(),$E=gi();mp.exports=kE?function(a,e,t){return RE.f(a,e,$E(1,t))}:function(a,e,t){return a[e]=t,a}});var ee=m((eO,gp)=>{"use strict";var Ei=J(),LE=Yn(),ME=Kn(),CE=z(),DE=op().f,OE=go(),Dr=Rr(),BE=Mr(),Or=Cr(),bp=Qe();Ti();var VE=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 LE(a,this,arguments)};return e.prototype=a.prototype,e};gp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Ei:i?Ei[t]:Ei[t]&&Ei[t].prototype,o=r?Dr:Dr[t]||Or(Dr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,v;for(p in e)l=OE(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&bp(n,p),f=o[p],c&&(a.dontCallGetSet?(v=DE(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=BE(h,Ei):a.wrap&&c?g=VE(h):s&&CE(h)?g=ME(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Or(g,"sham",!0),Or(o,p,g),s&&(d=t+"Prototype",bp(Dr,d)||Or(Dr,d,{}),Or(Dr[d],p,h),a.real&&u&&(l||!u[p])&&Or(u,p,h)))}});var Sp=m((tO,vp)=>{"use strict";var _E=Math.ceil,NE=Math.floor;vp.exports=Math.trunc||function(e){var t=+e;return(t>0?NE:_E)(t)}});var xi=m((rO,yp)=>{"use strict";var FE=Sp();yp.exports=function(a){var e=+a;return e!==e||e===0?0:FE(e)}});var Ip=m((iO,Tp)=>{"use strict";var qE=xi(),UE=Math.max,HE=Math.min;Tp.exports=function(a,e){var t=qE(a);return t<0?UE(t+e,0):HE(t,e)}});var Eo=m((aO,Ep)=>{"use strict";var jE=xi(),GE=Math.min;Ep.exports=function(a){var e=jE(a);return e>0?GE(e,9007199254740991):0}});var Br=m((sO,xp)=>{"use strict";var QE=Eo();xp.exports=function(a){return QE(a.length)}});var xo=m((nO,wp)=>{"use strict";var WE=Xt(),YE=Ip(),zE=Br(),Pp=function(a){return function(e,t,r){var i=WE(e),s=zE(i);if(s===0)return!a&&-1;var n=YE(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}};wp.exports={includes:Pp(!0),indexOf:Pp(!1)}});var Pi=m((oO,Ap)=>{"use strict";Ap.exports=function(){}});var kp=m(()=>{"use strict";var KE=ee(),JE=xo().includes,XE=ue(),ZE=Pi(),ex=XE(function(){return!Array(1).includes()});KE({target:"Array",proto:!0,forced:ex},{includes:function(e){return JE(this,e,arguments.length>1?arguments[1]:void 0)}});ZE("includes")});var kt=m((cO,Rp)=>{"use strict";var tx=nt();Rp.exports=tx});var Lp=m((dO,$p)=>{"use strict";kp();var rx=kt();$p.exports=rx("Array","includes")});var Cp=m((pO,Mp)=>{"use strict";var ix=Lp();Mp.exports=ix});var We=m((hO,Dp)=>{"use strict";var ax=Cp();Dp.exports=ax});var ms=m((PO,Up)=>{"use strict";var px=co(),hx=po(),qp=px("keys");Up.exports=function(a){return qp[a]||(qp[a]=hx(a))}});var jp=m((wO,Hp)=>{"use strict";var fx=ue();Hp.exports=!fx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var bs=m((AO,Qp)=>{"use strict";var mx=Qe(),bx=z(),gx=$r(),vx=ms(),Sx=jp(),Gp=vx("IE_PROTO"),Ao=Object,yx=Ao.prototype;Qp.exports=Sx?Ao.getPrototypeOf:function(a){var e=gx(a);if(mx(e,Gp))return e[Gp];var t=e.constructor;return bx(t)&&e instanceof t?t.prototype:e instanceof Ao?yx:null}});var gs=m((kO,Wp)=>{"use strict";Wp.exports={}});var Kp=m((RO,zp)=>{"use strict";var Tx=re(),ko=Qe(),Ix=Xt(),Ex=xo().indexOf,xx=gs(),Yp=Tx([].push);zp.exports=function(a,e){var t=Ix(a),r=0,i=[],s;for(s in t)!ko(xx,s)&&ko(t,s)&&Yp(i,s);for(;e.length>r;)ko(t,s=e[r++])&&(~Ex(i,s)||Yp(i,s));return i}});var Ro=m(($O,Jp)=>{"use strict";Jp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var $o=m((LO,Xp)=>{"use strict";var Px=Kp(),wx=Ro();Xp.exports=Object.keys||function(e){return Px(e,wx)}});var Lo=m((MO,ih)=>{"use strict";var eh=we(),Ax=ue(),th=re(),kx=bs(),Rx=$o(),$x=Xt(),Lx=Xn().f,rh=th(Lx),Mx=th([].push),Cx=eh&&Ax(function(){var a=Object.create(null);return a[2]=2,!rh(a,2)}),Zp=function(a){return function(e){for(var t=$x(e),r=Rx(t),i=Cx&&kx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!eh||(i?u in t:rh(t,u)))&&Mx(o,a?[u,t[u]]:t[u]);return o}};ih.exports={entries:Zp(!0),values:Zp(!1)}});var ah=m(()=>{"use strict";var Dx=ee(),Ox=Lo().entries;Dx({target:"Object",stat:!0},{entries:function(e){return Ox(e)}})});var nh=m((OO,sh)=>{"use strict";ah();var Bx=Rr();sh.exports=Bx.Object.entries});var uh=m((BO,oh)=>{"use strict";var Vx=nh();oh.exports=Vx});var Vr=m((VO,lh)=>{"use strict";var _x=uh();lh.exports=_x});var tr=m((_O,ch)=>{"use strict";ch.exports={}});var hh=m((NO,ph)=>{"use strict";var Nx=J(),Fx=z(),dh=Nx.WeakMap;ph.exports=Fx(dh)&&/native code/.test(String(dh))});var Oo=m((FO,bh)=>{"use strict";var qx=hh(),mh=J(),Ux=ke(),Hx=Cr(),Mo=Qe(),Co=Ti(),jx=ms(),Gx=gs(),fh="Object already initialized",Do=mh.TypeError,Qx=mh.WeakMap,vs,wi,Ss,Wx=function(a){return Ss(a)?wi(a):vs(a,{})},Yx=function(a){return function(e){var t;if(!Ux(e)||(t=wi(e)).type!==a)throw new Do("Incompatible receiver, "+a+" required");return t}};qx||Co.state?(Ye=Co.state||(Co.state=new Qx),Ye.get=Ye.get,Ye.has=Ye.has,Ye.set=Ye.set,vs=function(a,e){if(Ye.has(a))throw new Do(fh);return e.facade=a,Ye.set(a,e),e},wi=function(a){return Ye.get(a)||{}},Ss=function(a){return Ye.has(a)}):(rr=jx("state"),Gx[rr]=!0,vs=function(a,e){if(Mo(a,rr))throw new Do(fh);return e.facade=a,Hx(a,rr,e),e},wi=function(a){return Mo(a,rr)?a[rr]:{}},Ss=function(a){return Mo(a,rr)});var Ye,rr;bh.exports={set:vs,get:wi,has:Ss,enforce:Wx,getterFor:Yx}});var _o=m((qO,vh)=>{"use strict";var Bo=we(),zx=Qe(),gh=Function.prototype,Kx=Bo&&Object.getOwnPropertyDescriptor,Vo=zx(gh,"name"),Jx=Vo&&function(){}.name==="something",Xx=Vo&&(!Bo||Bo&&Kx(gh,"name").configurable);vh.exports={EXISTS:Vo,PROPER:Jx,CONFIGURABLE:Xx}});var yh=m(Sh=>{"use strict";var Zx=we(),eP=vo(),tP=er(),rP=et(),iP=Xt(),aP=$o();Sh.f=Zx&&!eP?Object.defineProperties:function(e,t){rP(e);for(var r=iP(t),i=aP(t),s=i.length,n=0,o;s>n;)tP.f(e,o=i[n++],r[o]);return e}});var No=m((HO,Th)=>{"use strict";var sP=nt();Th.exports=sP("document","documentElement")});var Ho=m((jO,kh)=>{"use strict";var nP=et(),oP=yh(),Ih=Ro(),uP=gs(),lP=No(),cP=ds(),dP=ms(),Eh=">",xh="<",qo="prototype",Uo="script",wh=dP("IE_PROTO"),Fo=function(){},Ah=function(a){return xh+Uo+Eh+a+xh+"/"+Uo+Eh},Ph=function(a){a.write(Ah("")),a.close();var e=a.parentWindow.Object;return a=null,e},pP=function(){var a=cP("iframe"),e="java"+Uo+":",t;return a.style.display="none",lP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Ah("document.F=Object")),t.close(),t.F},ys,Ts=function(){try{ys=new ActiveXObject("htmlfile")}catch(e){}Ts=typeof document!="undefined"?document.domain&&ys?Ph(ys):pP():Ph(ys);for(var a=Ih.length;a--;)delete Ts[qo][Ih[a]];return Ts()};uP[wh]=!0;kh.exports=Object.create||function(e,t){var r;return e!==null?(Fo[qo]=nP(e),r=new Fo,Fo[qo]=null,r[wh]=e):r=Ts(),t===void 0?r:oP.f(r,t)}});var _r=m((GO,Rh)=>{"use strict";var hP=Cr();Rh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:hP(a,e,t),a}});var Wo=m((QO,Mh)=>{"use strict";var fP=ue(),mP=z(),bP=ke(),gP=Ho(),$h=bs(),vP=_r(),SP=le(),yP=Ge(),Qo=SP("iterator"),Lh=!1,ot,jo,Go;[].keys&&(Go=[].keys(),"next"in Go?(jo=$h($h(Go)),jo!==Object.prototype&&(ot=jo)):Lh=!0);var TP=!bP(ot)||fP(function(){var a={};return ot[Qo].call(a)!==a});TP?ot={}:yP&&(ot=gP(ot));mP(ot[Qo])||vP(ot,Qo,function(){return this});Mh.exports={IteratorPrototype:ot,BUGGY_SAFARI_ITERATORS:Lh}});var Is=m((WO,Dh)=>{"use strict";var IP=le(),EP=IP("toStringTag"),Ch={};Ch[EP]="z";Dh.exports=String(Ch)==="[object z]"});var Ai=m((YO,Oh)=>{"use strict";var xP=Is(),PP=z(),Es=Jt(),wP=le(),AP=wP("toStringTag"),kP=Object,RP=Es(function(){return arguments}())==="Arguments",$P=function(a,e){try{return a[e]}catch(t){}};Oh.exports=xP?Es:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=$P(e=kP(a),AP))=="string"?t:RP?Es(e):(r=Es(e))==="Object"&&PP(e.callee)?"Arguments":r}});var Vh=m((zO,Bh)=>{"use strict";var LP=Is(),MP=Ai();Bh.exports=LP?{}.toString:function(){return"[object "+MP(this)+"]"}});var ki=m((KO,Nh)=>{"use strict";var CP=Is(),DP=er().f,OP=Cr(),BP=Qe(),VP=Vh(),_P=le(),_h=_P("toStringTag");Nh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(BP(i,_h)||DP(i,_h,{configurable:!0,value:e}),r&&!CP&&OP(i,"toString",VP))}});var qh=m((JO,Fh)=>{"use strict";var NP=Wo().IteratorPrototype,FP=Ho(),qP=gi(),UP=ki(),HP=tr(),jP=function(){return this};Fh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=FP(NP,{next:qP(+!r,t)}),UP(a,i,!1,!0),HP[i]=jP,a}});var Hh=m((XO,Uh)=>{"use strict";var GP=re(),QP=Ze();Uh.exports=function(a,e,t){try{return GP(QP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Gh=m((ZO,jh)=>{"use strict";var WP=ke();jh.exports=function(a){return WP(a)||a===null}});var Wh=m((eB,Qh)=>{"use strict";var YP=Gh(),zP=String,KP=TypeError;Qh.exports=function(a){if(YP(a))return a;throw new KP("Can't set "+zP(a)+" as a prototype")}});var Yo=m((tB,Yh)=>{"use strict";var JP=Hh(),XP=ke(),ZP=At(),ew=Wh();Yh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=JP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return ZP(i),ew(s),XP(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var nf=m((rB,sf)=>{"use strict";var tw=ee(),rw=Ae(),xs=Ge(),rf=_o(),iw=z(),aw=qh(),zh=bs(),Kh=Yo(),sw=ki(),nw=Cr(),zo=_r(),ow=le(),Jh=tr(),af=Wo(),uw=rf.PROPER,lw=rf.CONFIGURABLE,Xh=af.IteratorPrototype,Ps=af.BUGGY_SAFARI_ITERATORS,Ri=ow("iterator"),Zh="keys",$i="values",ef="entries",tf=function(){return this};sf.exports=function(a,e,t,r,i,s,n){aw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ps&&v&&v in c)return c[v];switch(v){case Zh:return function(){return new t(this,v)};case $i:return function(){return new t(this,v)};case ef:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Ri]||c["@@iterator"]||i&&c[i],p=!Ps&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=zh(h.call(new a)),f!==Object.prototype&&f.next&&(!xs&&zh(f)!==Xh&&(Kh?Kh(f,Xh):iw(f[Ri])||zo(f,Ri,tf)),sw(f,u,!0,!0),xs&&(Jh[u]=tf))),uw&&i===$i&&d&&d.name!==$i&&(!xs&&lw?nw(c,"name",$i):(l=!0,p=function(){return rw(d,this)})),i)if(b={values:o($i),keys:s?p:o(Zh),entries:o(ef)},n)for(g in b)(Ps||l||!(g in c))&&zo(c,g,b[g]);else tw({target:e,proto:!0,forced:Ps||l},b);return(!xs||n)&&c[Ri]!==p&&zo(c,Ri,p,{name:i}),Jh[e]=p,b}});var uf=m((iB,of)=>{"use strict";of.exports=function(a,e){return{value:a,done:e}}});var Jo=m((aB,hf)=>{"use strict";var cw=Xt(),Ko=Pi(),lf=tr(),df=Oo(),dw=er().f,pw=nf(),ws=uf(),hw=Ge(),fw=we(),pf="Array Iterator",mw=df.set,bw=df.getterFor(pf);hf.exports=pw(Array,"Array",function(a,e){mw(this,{type:pf,target:cw(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,ws(void 0,!0);switch(a.kind){case"keys":return ws(t,!1);case"values":return ws(e[t],!1)}return ws([t,e[t]],!1)},"values");var cf=lf.Arguments=lf.Array;Ko("keys");Ko("values");Ko("entries");if(!hw&&fw&&cf.name!=="values")try{dw(cf,"name",{value:"values"})}catch(a){}});var mf=m((sB,ff)=>{"use strict";var gw=le(),vw=tr(),Sw=gw("iterator"),yw=Array.prototype;ff.exports=function(a){return a!==void 0&&(vw.Array===a||yw[Sw]===a)}});var Xo=m((nB,gf)=>{"use strict";var Tw=Ai(),bf=yi(),Iw=kr(),Ew=tr(),xw=le(),Pw=xw("iterator");gf.exports=function(a){if(!Iw(a))return bf(a,Pw)||bf(a,"@@iterator")||Ew[Tw(a)]}});var Sf=m((oB,vf)=>{"use strict";var ww=Ae(),Aw=Ze(),kw=et(),Rw=Si(),$w=Xo(),Lw=TypeError;vf.exports=function(a,e){var t=arguments.length<2?$w(a):e;if(Aw(t))return kw(ww(t,a));throw new Lw(Rw(a)+" is not iterable")}});var If=m((uB,Tf)=>{"use strict";var Mw=Ae(),yf=et(),Cw=yi();Tf.exports=function(a,e,t){var r,i;yf(a);try{if(r=Cw(a,"return"),!r){if(e==="throw")throw t;return t}r=Mw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return yf(r),t}});var ks=m((lB,wf)=>{"use strict";var Dw=Mr(),Ow=Ae(),Bw=et(),Vw=Si(),_w=mf(),Nw=Br(),Ef=vi(),Fw=Sf(),qw=Xo(),xf=If(),Uw=TypeError,As=function(a,e){this.stopped=a,this.result=e},Pf=As.prototype;wf.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=Dw(e,r),l,c,d,p,h,f,b,g=function(S){return l&&xf(l,"normal",S),new As(!0,S)},v=function(S){return i?(Bw(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=qw(a),!c)throw new Uw(Vw(a)+" is not iterable");if(_w(c)){for(d=0,p=Nw(a);p>d;d++)if(h=v(a[d]),h&&Ef(Pf,h))return h;return new As(!1)}l=Fw(a,c)}for(f=s?a.next:l.next;!(b=Ow(f,l)).done;){try{h=v(b.value)}catch(S){xf(l,"throw",S)}if(typeof h=="object"&&h&&Ef(Pf,h))return h}return new As(!1)}});var kf=m((cB,Af)=>{"use strict";var Hw=we(),jw=er(),Gw=gi();Af.exports=function(a,e,t){Hw?jw.f(a,e,Gw(0,t)):a[e]=t}});var Rf=m(()=>{"use strict";var Qw=ee(),Ww=ks(),Yw=kf();Qw({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Ww(e,function(r,i){Yw(t,r,i)},{AS_ENTRIES:!0}),t}})});var Lf=m((hB,$f)=>{"use strict";Jo();Rf();var zw=Rr();$f.exports=zw.Object.fromEntries});var Cf=m((fB,Mf)=>{"use strict";Mf.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 Of=m(()=>{"use strict";Jo();var Kw=Cf(),Jw=J(),Xw=ki(),Df=tr();for(Rs in Kw)Xw(Jw[Rs],Rs),Df[Rs]=Df.Array;var Rs});var Vf=m((gB,Bf)=>{"use strict";var Zw=Lf();Of();Bf.exports=Zw});var Zo=m((vB,_f)=>{"use strict";var eA=Vf();_f.exports=eA});var Nf=m(()=>{"use strict"});var eu=m((TB,Ff)=>{"use strict";var Li=J(),tA=Zt(),rA=Jt(),$s=function(a){return tA.slice(0,a.length)===a};Ff.exports=function(){return $s("Bun/")?"BUN":$s("Cloudflare-Workers")?"CLOUDFLARE":$s("Deno/")?"DENO":$s("Node.js/")?"NODE":Li.Bun&&typeof Bun.version=="string"?"BUN":Li.Deno&&typeof Deno.version=="object"?"DENO":rA(Li.process)==="process"?"NODE":Li.window&&Li.document?"BROWSER":"REST"}()});var Ls=m((IB,qf)=>{"use strict";var iA=eu();qf.exports=iA==="NODE"});var Hf=m((EB,Uf)=>{"use strict";var aA=er();Uf.exports=function(a,e,t){return aA.f(a,e,t)}});var Qf=m((xB,Gf)=>{"use strict";var sA=nt(),nA=Hf(),oA=le(),uA=we(),jf=oA("species");Gf.exports=function(a){var e=sA(a);uA&&e&&!e[jf]&&nA(e,jf,{configurable:!0,get:function(){return this}})}});var Yf=m((PB,Wf)=>{"use strict";var lA=vi(),cA=TypeError;Wf.exports=function(a,e){if(lA(e,a))return a;throw new cA("Incorrect invocation")}});var ru=m((wB,zf)=>{"use strict";var dA=re(),pA=z(),tu=Ti(),hA=dA(Function.toString);pA(tu.inspectSource)||(tu.inspectSource=function(a){return hA(a)});zf.exports=tu.inspectSource});var au=m((AB,em)=>{"use strict";var fA=re(),mA=ue(),Kf=z(),bA=Ai(),gA=nt(),vA=ru(),Jf=function(){},Xf=gA("Reflect","construct"),iu=/^\s*(?:class|function)\b/,SA=fA(iu.exec),yA=!iu.test(Jf),Mi=function(e){if(!Kf(e))return!1;try{return Xf(Jf,[],e),!0}catch(t){return!1}},Zf=function(e){if(!Kf(e))return!1;switch(bA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return yA||!!SA(iu,vA(e))}catch(t){return!0}};Zf.sham=!0;em.exports=!Xf||mA(function(){var a;return Mi(Mi.call)||!Mi(Object)||!Mi(function(){a=!0})||a})?Zf:Mi});var rm=m((kB,tm)=>{"use strict";var TA=au(),IA=Si(),EA=TypeError;tm.exports=function(a){if(TA(a))return a;throw new EA(IA(a)+" is not a constructor")}});var su=m((RB,am)=>{"use strict";var im=et(),xA=rm(),PA=kr(),wA=le(),AA=wA("species");am.exports=function(a,e){var t=im(a).constructor,r;return t===void 0||PA(r=im(t)[AA])?e:xA(r)}});var nm=m(($B,sm)=>{"use strict";var kA=re();sm.exports=kA([].slice)});var um=m((LB,om)=>{"use strict";var RA=TypeError;om.exports=function(a,e){if(a<e)throw new RA("Not enough arguments");return a}});var nu=m((MB,lm)=>{"use strict";var $A=Zt();lm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test($A)});var mu=m((CB,vm)=>{"use strict";var Re=J(),LA=Yn(),MA=Mr(),cm=z(),CA=Qe(),gm=ue(),dm=No(),DA=nm(),pm=ds(),OA=um(),BA=nu(),VA=Ls(),pu=Re.setImmediate,hu=Re.clearImmediate,_A=Re.process,ou=Re.Dispatch,NA=Re.Function,hm=Re.MessageChannel,FA=Re.String,uu=0,Ci={},fm="onreadystatechange",Di,ir,lu,cu;gm(function(){Di=Re.location});var fu=function(a){if(CA(Ci,a)){var e=Ci[a];delete Ci[a],e()}},du=function(a){return function(){fu(a)}},mm=function(a){fu(a.data)},bm=function(a){Re.postMessage(FA(a),Di.protocol+"//"+Di.host)};(!pu||!hu)&&(pu=function(e){OA(arguments.length,1);var t=cm(e)?e:NA(e),r=DA(arguments,1);return Ci[++uu]=function(){LA(t,void 0,r)},ir(uu),uu},hu=function(e){delete Ci[e]},VA?ir=function(a){_A.nextTick(du(a))}:ou&&ou.now?ir=function(a){ou.now(du(a))}:hm&&!BA?(lu=new hm,cu=lu.port2,lu.port1.onmessage=mm,ir=MA(cu.postMessage,cu)):Re.addEventListener&&cm(Re.postMessage)&&!Re.importScripts&&Di&&Di.protocol!=="file:"&&!gm(bm)?(ir=bm,Re.addEventListener("message",mm,!1)):fm in pm("script")?ir=function(a){dm.appendChild(pm("script"))[fm]=function(){dm.removeChild(this),fu(a)}}:ir=function(a){setTimeout(du(a),0)});vm.exports={set:pu,clear:hu}});var Tm=m((DB,ym)=>{"use strict";var Sm=J(),qA=we(),UA=Object.getOwnPropertyDescriptor;ym.exports=function(a){if(!qA)return Sm[a];var e=UA(Sm,a);return e&&e.value}});var bu=m((OB,Em)=>{"use strict";var Im=function(){this.head=null,this.tail=null};Im.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}}};Em.exports=Im});var Pm=m((BB,xm)=>{"use strict";var HA=Zt();xm.exports=/ipad|iphone|ipod/i.test(HA)&&typeof Pebble!="undefined"});var Am=m((VB,wm)=>{"use strict";var jA=Zt();wm.exports=/web0s(?!.*chrome)/i.test(jA)});var Dm=m((_B,Cm)=>{"use strict";var Fr=J(),GA=Tm(),km=Mr(),gu=mu().set,QA=bu(),WA=nu(),YA=Pm(),zA=Am(),vu=Ls(),Rm=Fr.MutationObserver||Fr.WebKitMutationObserver,$m=Fr.document,Lm=Fr.process,Ms=Fr.Promise,Tu=GA("queueMicrotask"),Nr,Su,yu,Cs,Mm;Tu||(Oi=new QA,Bi=function(){var a,e;for(vu&&(a=Lm.domain)&&a.exit();e=Oi.get();)try{e()}catch(t){throw Oi.head&&Nr(),t}a&&a.enter()},!WA&&!vu&&!zA&&Rm&&$m?(Su=!0,yu=$m.createTextNode(""),new Rm(Bi).observe(yu,{characterData:!0}),Nr=function(){yu.data=Su=!Su}):!YA&&Ms&&Ms.resolve?(Cs=Ms.resolve(void 0),Cs.constructor=Ms,Mm=km(Cs.then,Cs),Nr=function(){Mm(Bi)}):vu?Nr=function(){Lm.nextTick(Bi)}:(gu=km(gu,Fr),Nr=function(){gu(Bi)}),Tu=function(a){Oi.head||Nr(),Oi.add(a)});var Oi,Bi;Cm.exports=Tu});var Bm=m((NB,Om)=>{"use strict";Om.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ds=m((FB,Vm)=>{"use strict";Vm.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ar=m((qB,_m)=>{"use strict";var KA=J();_m.exports=KA.Promise});var qr=m((UB,Um)=>{"use strict";var JA=J(),Vi=ar(),XA=z(),ZA=go(),ek=ru(),tk=le(),Nm=eu(),rk=Ge(),Iu=io(),Fm=Vi&&Vi.prototype,ik=tk("species"),Eu=!1,qm=XA(JA.PromiseRejectionEvent),ak=ZA("Promise",function(){var a=ek(Vi),e=a!==String(Vi);if(!e&&Iu===66||rk&&!(Fm.catch&&Fm.finally))return!0;if(!Iu||Iu<51||!/native code/.test(a)){var t=new Vi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[ik]=r,Eu=t.then(function(){})instanceof r,!Eu)return!0}return!e&&(Nm==="BROWSER"||Nm==="DENO")&&!qm});Um.exports={CONSTRUCTOR:ak,REJECTION_EVENT:qm,SUBCLASSING:Eu}});var Ur=m((HB,jm)=>{"use strict";var Hm=Ze(),sk=TypeError,nk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new sk("Bad Promise constructor");e=r,t=i}),this.resolve=Hm(e),this.reject=Hm(t)};jm.exports.f=function(a){return new nk(a)}});var lb=m(()=>{"use strict";var ok=ee(),uk=Ge(),_s=Ls(),Rt=J(),Qr=Ae(),Gm=_r(),Qm=Yo(),lk=ki(),ck=Qf(),dk=Ze(),Vs=z(),pk=ke(),hk=Yf(),fk=su(),Jm=mu().set,ku=Dm(),mk=Bm(),bk=Ds(),gk=bu(),Xm=Oo(),Ns=ar(),Ru=qr(),Zm=Ur(),Fs="Promise",eb=Ru.CONSTRUCTOR,vk=Ru.REJECTION_EVENT,Sk=Ru.SUBCLASSING,xu=Xm.getterFor(Fs),yk=Xm.set,Hr=Ns&&Ns.prototype,sr=Ns,Os=Hr,tb=Rt.TypeError,Pu=Rt.document,$u=Rt.process,wu=Zm.f,Tk=wu,Ik=!!(Pu&&Pu.createEvent&&Rt.dispatchEvent),rb="unhandledrejection",Ek="rejectionhandled",Wm=0,ib=1,xk=2,Lu=1,ab=2,Bs,Ym,Pk,zm,sb=function(a){var e;return pk(a)&&Vs(e=a.then)?e:!1},nb=function(a,e){var t=e.value,r=e.state===ib,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===ab&&Ak(e),e.rejection=Lu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new tb("Promise-chain cycle")):(l=sb(u))?Qr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},ob=function(a,e){a.notified||(a.notified=!0,ku(function(){for(var t=a.reactions,r;r=t.get();)nb(r,a);a.notified=!1,e&&!a.rejection&&wk(a)}))},ub=function(a,e,t){var r,i;Ik?(r=Pu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Rt.dispatchEvent(r)):r={promise:e,reason:t},!vk&&(i=Rt["on"+a])?i(r):a===rb&&mk("Unhandled promise rejection",t)},wk=function(a){Qr(Jm,Rt,function(){var e=a.facade,t=a.value,r=Km(a),i;if(r&&(i=bk(function(){_s?$u.emit("unhandledRejection",t,e):ub(rb,e,t)}),a.rejection=_s||Km(a)?ab:Lu,i.error))throw i.value})},Km=function(a){return a.rejection!==Lu&&!a.parent},Ak=function(a){Qr(Jm,Rt,function(){var e=a.facade;_s?$u.emit("rejectionHandled",e):ub(Ek,e,a.value)})},jr=function(a,e,t){return function(r){a(e,r,t)}},Gr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=xk,ob(a,!0))},Au=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new tb("Promise can't be resolved itself");var r=sb(e);r?ku(function(){var i={done:!1};try{Qr(r,e,jr(Au,i,a),jr(Gr,i,a))}catch(s){Gr(i,s,a)}}):(a.value=e,a.state=ib,ob(a,!1))}catch(i){Gr({done:!1},i,a)}}};if(eb&&(sr=function(e){hk(this,Os),dk(e),Qr(Bs,this);var t=xu(this);try{e(jr(Au,t),jr(Gr,t))}catch(r){Gr(t,r)}},Os=sr.prototype,Bs=function(e){yk(this,{type:Fs,done:!1,notified:!1,parent:!1,reactions:new gk,rejection:!1,state:Wm,value:void 0})},Bs.prototype=Gm(Os,"then",function(e,t){var r=xu(this),i=wu(fk(this,sr));return r.parent=!0,i.ok=Vs(e)?e:!0,i.fail=Vs(t)&&t,i.domain=_s?$u.domain:void 0,r.state===Wm?r.reactions.add(i):ku(function(){nb(i,r)}),i.promise}),Ym=function(){var a=new Bs,e=xu(a);this.promise=a,this.resolve=jr(Au,e),this.reject=jr(Gr,e)},Zm.f=wu=function(a){return a===sr||a===Pk?new Ym(a):Tk(a)},!uk&&Vs(Ns)&&Hr!==Object.prototype)){zm=Hr.then,Sk||Gm(Hr,"then",function(e,t){var r=this;return new sr(function(i,s){Qr(zm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Hr.constructor}catch(a){}Qm&&Qm(Hr,Os)}ok({global:!0,constructor:!0,wrap:!0,forced:eb},{Promise:sr});lk(sr,Fs,!1,!0);ck(Fs)});var fb=m((QB,hb)=>{"use strict";var kk=le(),db=kk("iterator"),pb=!1;try{cb=0,Mu={next:function(){return{done:!!cb++}},return:function(){pb=!0}},Mu[db]=function(){return this},Array.from(Mu,function(){throw 2})}catch(a){}var cb,Mu;hb.exports=function(a,e){try{if(!e&&!pb)return!1}catch(i){return!1}var t=!1;try{var r={};r[db]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Cu=m((WB,mb)=>{"use strict";var Rk=ar(),$k=fb(),Lk=qr().CONSTRUCTOR;mb.exports=Lk||!$k(function(a){Rk.all(a).then(void 0,function(){})})});var bb=m(()=>{"use strict";var Mk=ee(),Ck=Ae(),Dk=Ze(),Ok=Ur(),Bk=Ds(),Vk=ks(),_k=Cu();Mk({target:"Promise",stat:!0,forced:_k},{all:function(e){var t=this,r=Ok.f(t),i=r.resolve,s=r.reject,n=Bk(function(){var o=Dk(t.resolve),u=[],l=0,c=1;Vk(e,function(d){var p=l++,h=!1;c++,Ck(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 Nk=ee(),Fk=Ge(),qk=qr().CONSTRUCTOR,Ou=ar(),Uk=nt(),Hk=z(),jk=_r(),gb=Ou&&Ou.prototype;Nk({target:"Promise",proto:!0,forced:qk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Fk&&Hk(Ou)&&(Du=Uk("Promise").prototype.catch,gb.catch!==Du&&jk(gb,"catch",Du,{unsafe:!0}));var Du});var Sb=m(()=>{"use strict";var Gk=ee(),Qk=Ae(),Wk=Ze(),Yk=Ur(),zk=Ds(),Kk=ks(),Jk=Cu();Gk({target:"Promise",stat:!0,forced:Jk},{race:function(e){var t=this,r=Yk.f(t),i=r.reject,s=zk(function(){var n=Wk(t.resolve);Kk(e,function(o){Qk(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var yb=m(()=>{"use strict";var Xk=ee(),Zk=Ur(),eR=qr().CONSTRUCTOR;Xk({target:"Promise",stat:!0,forced:eR},{reject:function(e){var t=Zk.f(this),r=t.reject;return r(e),t.promise}})});var Bu=m((rV,Tb)=>{"use strict";var tR=et(),rR=ke(),iR=Ur();Tb.exports=function(a,e){if(tR(a),rR(e)&&e.constructor===a)return e;var t=iR.f(a),r=t.resolve;return r(e),t.promise}});var xb=m(()=>{"use strict";var aR=ee(),sR=nt(),Ib=Ge(),nR=ar(),Eb=qr().CONSTRUCTOR,oR=Bu(),uR=sR("Promise"),lR=Ib&&!Eb;aR({target:"Promise",stat:!0,forced:Ib||Eb},{resolve:function(e){return oR(lR&&this===uR?nR:this,e)}})});var Pb=m(()=>{"use strict";lb();bb();vb();Sb();yb();xb()});var Rb=m(()=>{"use strict";var cR=ee(),dR=Ge(),qs=ar(),pR=ue(),Ab=nt(),kb=z(),hR=su(),wb=Bu(),fR=_r(),_u=qs&&qs.prototype,mR=!!qs&&pR(function(){_u.finally.call({then:function(){}},function(){})});cR({target:"Promise",proto:!0,real:!0,forced:mR},{finally:function(a){var e=hR(this,Ab("Promise")),t=kb(a);return this.then(t?function(r){return wb(e,a()).then(function(){return r})}:a,t?function(r){return wb(e,a()).then(function(){throw r})}:a)}});!dR&&kb(qs)&&(Vu=Ab("Promise").prototype.finally,_u.finally!==Vu&&fR(_u,"finally",Vu,{unsafe:!0}));var Vu});var Lb=m((lV,$b)=>{"use strict";Nf();Pb();Rb();var bR=kt();$b.exports=bR("Promise","finally")});var Cb=m((cV,Mb)=>{"use strict";var gR=Lb();Mb.exports=gR});var Us=m((dV,Db)=>{"use strict";var vR=Cb();Db.exports=vR});var Wb=m(()=>{"use strict";var MR=ee(),CR=Lo().values;MR({target:"Object",stat:!0},{values:function(e){return CR(e)}})});var zb=m((zV,Yb)=>{"use strict";Wb();var DR=Rr();Yb.exports=DR.Object.values});var Jb=m((KV,Kb)=>{"use strict";var OR=zb();Kb.exports=OR});var Yr=m((JV,Xb)=>{"use strict";var BR=Jb();Xb.exports=BR});var dg=m(()=>{"use strict";var XR=ee(),ZR=$r(),e$=Br(),t$=xi(),r$=Pi();XR({target:"Array",proto:!0},{at:function(e){var t=ZR(this),r=e$(t),i=t$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});r$("at")});var hg=m((P_,pg)=>{"use strict";dg();var i$=kt();pg.exports=i$("Array","at")});var mg=m((w_,fg)=>{"use strict";var a$=hg();fg.exports=a$});var Kr=m((A_,bg)=>{"use strict";var s$=mg();bg.exports=s$});var ol=m((ZN,Qg)=>{"use strict";var F$=Jt();Qg.exports=Array.isArray||function(e){return F$(e)==="Array"}});var Yg=m((eF,Wg)=>{"use strict";var q$=TypeError,U$=9007199254740991;Wg.exports=function(a){if(a>U$)throw q$("Maximum allowed index exceeded");return a}});var Jg=m((tF,Kg)=>{"use strict";var H$=ol(),j$=Br(),G$=Yg(),Q$=Mr(),zg=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?Q$(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&H$(d)?(p=j$(d),u=zg(a,e,d,p,u,s-1)-1):(G$(u+1),a[u]=d),u++),l++;return u};Kg.exports=zg});var tv=m((rF,ev)=>{"use strict";var Xg=ol(),W$=au(),Y$=ke(),z$=le(),K$=z$("species"),Zg=Array;ev.exports=function(a){var e;return Xg(a)&&(e=a.constructor,W$(e)&&(e===Zg||Xg(e.prototype))?e=void 0:Y$(e)&&(e=e[K$],e===null&&(e=void 0))),e===void 0?Zg:e}});var iv=m((iF,rv)=>{"use strict";var J$=tv();rv.exports=function(a,e){return new(J$(a))(e===0?0:e)}});var av=m(()=>{"use strict";var X$=ee(),Z$=Jg(),eL=Ze(),tL=$r(),rL=Br(),iL=iv();X$({target:"Array",proto:!0},{flatMap:function(e){var t=tL(this),r=rL(t),i;return eL(e),i=iL(t,0),i.length=Z$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var sv=m(()=>{"use strict";var aL=Pi();aL("flatMap")});var ov=m((uF,nv)=>{"use strict";av();sv();var sL=kt();nv.exports=sL("Array","flatMap")});var lv=m((lF,uv)=>{"use strict";var nL=ov();uv.exports=nL});var ul=m((cF,cv)=>{"use strict";var oL=lv();cv.exports=oL});var Xi=m((yF,$v)=>{"use strict";var mL=Ai(),bL=String;$v.exports=function(a){if(mL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return bL(a)}});var cl=m((TF,Lv)=>{"use strict";Lv.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 Dv=m((IF,Cv)=>{"use strict";var gL=re(),vL=At(),SL=Xi(),pl=cl(),Mv=gL("".replace),yL=RegExp("^["+pl+"]+"),TL=RegExp("(^|[^"+pl+"])["+pl+"]+$"),dl=function(a){return function(e){var t=SL(vL(e));return a&1&&(t=Mv(t,yL,"")),a&2&&(t=Mv(t,TL,"$1")),t}};Cv.exports={start:dl(1),end:dl(2),trim:dl(3)}});var _v=m((EF,Vv)=>{"use strict";var IL=_o().PROPER,EL=ue(),Ov=cl(),Bv="\u200B\x85\u180E";Vv.exports=function(a){return EL(function(){return!!Ov[a]()||Bv[a]()!==Bv||IL&&Ov[a].name!==a})}});var hl=m((xF,Nv)=>{"use strict";var xL=Dv().start,PL=_v();Nv.exports=PL("trimStart")?function(){return xL(this)}:"".trimStart});var qv=m(()=>{"use strict";var wL=ee(),Fv=hl();wL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Fv},{trimLeft:Fv})});var Hv=m(()=>{"use strict";qv();var AL=ee(),Uv=hl();AL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Uv},{trimStart:Uv})});var Gv=m((RF,jv)=>{"use strict";Hv();var kL=kt();jv.exports=kL("String","trimLeft")});var Wv=m(($F,Qv)=>{"use strict";var RL=Gv();Qv.exports=RL});var zv=m((LF,Yv)=>{"use strict";var $L=Wv();Yv.exports=$L});var dS=m(()=>{"use strict"});var pS=m(()=>{"use strict"});var fS=m((t1,hS)=>{"use strict";var ZL=ke(),eM=Jt(),tM=le(),rM=tM("match");hS.exports=function(a){var e;return ZL(a)&&((e=a[rM])!==void 0?!!e:eM(a)==="RegExp")}});var bS=m((r1,mS)=>{"use strict";var iM=et();mS.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 SS=m((i1,vS)=>{"use strict";var aM=Ae(),sM=Qe(),nM=vi(),oM=bS(),gS=RegExp.prototype;vS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in gS)&&!sM(a,"flags")&&nM(gS,a)?aM(oM,a):e}});var TS=m((a1,yS)=>{"use strict";var Il=re(),uM=$r(),lM=Math.floor,yl=Il("".charAt),cM=Il("".replace),Tl=Il("".slice),dM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,pM=/\$([$&'`]|\d{1,2})/g;yS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=pM;return i!==void 0&&(i=uM(i),u=dM),cM(s,u,function(l,c){var d;switch(yl(c,0)){case"$":return"$";case"&":return a;case"`":return Tl(e,0,t);case"'":return Tl(e,n);case"<":d=i[Tl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=lM(p/10);return h===0?l:h<=o?r[h-1]===void 0?yl(c,1):r[h-1]+yl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var xS=m(()=>{"use strict";var hM=ee(),fM=Ae(),xl=re(),IS=At(),mM=z(),bM=kr(),gM=fS(),ri=Xi(),vM=yi(),SM=SS(),yM=TS(),TM=le(),IM=Ge(),EM=TM("replace"),xM=TypeError,El=xl("".indexOf),PM=xl("".replace),ES=xl("".slice),wM=Math.max;hM({target:"String",proto:!0},{replaceAll:function(e,t){var r=IS(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!bM(e)){if(i=gM(e),i&&(s=ri(IS(SM(e))),!~El(s,"g")))throw new xM("`.replaceAll` does not allow non-global regexes");if(n=vM(e,EM),n)return fM(n,e,r,t);if(IM&&i)return PM(ri(r),e,t)}for(o=ri(r),u=ri(e),l=mM(t),l||(t=ri(t)),c=u.length,d=wM(1,c),p=El(o,u);p!==-1;)h=l?ri(t(u,p,o)):yM(u,o,p,[],void 0,t),b+=ES(o,f,p)+h,f=p+c,p=p+d>o.length?-1:El(o,u,p+d);return f<o.length&&(b+=ES(o,f)),b}})});var wS=m((o1,PS)=>{"use strict";dS();pS();xS();var AM=kt();PS.exports=AM("String","replaceAll")});var kS=m((u1,AS)=>{"use strict";var kM=wS();AS.exports=kM});var $S=m((l1,RS)=>{"use strict";var RM=kS();RS.exports=RM});var MS=m((c1,LS)=>{"use strict";var $M=xi(),LM=Xi(),MM=At(),CM=RangeError;LS.exports=function(e){var t=LM(MM(this)),r="",i=$M(e);if(i<0||i===1/0)throw new CM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var VS=m((d1,BS)=>{"use strict";var OS=re(),DM=Eo(),CS=Xi(),OM=MS(),BM=At(),VM=OS(OM),_M=OS("".slice),NM=Math.ceil,DS=function(a){return function(e,t,r){var i=CS(BM(e)),s=DM(t),n=i.length,o=r===void 0?" ":CS(r),u,l;return s<=n||o===""?i:(u=s-n,l=VM(o,NM(u/o.length)),l.length>u&&(l=_M(l,0,u)),a?i+l:l+i)}};BS.exports={start:DS(!1),end:DS(!0)}});var NS=m((p1,_S)=>{"use strict";var FM=Zt();_S.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(FM)});var FS=m(()=>{"use strict";var qM=ee(),UM=VS().start,HM=NS();qM({target:"String",proto:!0,forced:HM},{padStart:function(e){return UM(this,e,arguments.length>1?arguments[1]:void 0)}})});var US=m((m1,qS)=>{"use strict";FS();var jM=kt();qS.exports=jM("String","padStart")});var jS=m((b1,HS)=>{"use strict";var GM=US();HS.exports=GM});var QS=m((g1,GS)=>{"use strict";var QM=jS();GS.exports=QM});var Uc="2.0.123-dev.92e9449d.0";var me=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(me||{}),wt=(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))(wt||{});var us=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(us||{}),Gn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Gn||{});var Qn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Qn||{});var ET=B(We(),1);import{assertNever as Fp,assertNonNullable as sx,isNonNullable as hs,ValueSubject as Po,Subject as nx,Subscription as ox,merge as ux,observableFrom as lx,fromEvent as Bp,map as Vp,tap as _p,filterChanged as cx,isNullable as wo,ErrorCategory as Np}from"@vkontakte/videoplayer-shared/es2018";var Op=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 fs=class{constructor(e){this.connection$=new Po(void 0);this.castState$=new Po("NOT_AVAILABLE");this.errorEvent$=new nx;this.realCastState$=new Po("NOT_AVAILABLE");this.subscription=new ox;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=hs((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||Op("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Np.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(){hs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();wo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();wo(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(Bp(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 Fp(i.sessionState)}})).add(ux(Bp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_p(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Vp(i=>i.castState)),lx([r.getCastState()])).pipe(cx(),Vp(dx),_p(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=hs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();sx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(wo(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"?hs(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:Np.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},dx=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 Fp(a)}};var tc=B(We(),1),iT=B(Vr(),1),aT=B(Zo(),1);var jb=B(Us(),1);import{assertNever as Ob}from"@vkontakte/videoplayer-shared/es2018";var ce=(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:Ob(t)}return a},Hs=(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:Ob(e)}};var E=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as SR,Subject as js,merge as Bb}from"@vkontakte/videoplayer-shared/es2018";var L=class{constructor(e){this.transitionStarted$=new js;this.transitionEnded$=new js;this.transitionUpdated$=new js;this.forceChanged$=new js;this.stateChangeStarted$=Bb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Bb(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||SR(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 yR}from"@vkontakte/videoplayer-shared/es2018";var Vb=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 yR(a)}};import{assertNever as Wr,assertNonNullable as nr,debounce as _b,ErrorCategory as Nb,fromEvent as or,isNonNullable as Fb,map as qb,merge as Ub,observableFrom as TR,Subject as IR,Subscription as Nu,timeout as ER,getHighestQuality as xR}from"@vkontakte/videoplayer-shared/es2018";var PR=5,wR=5,AR=500,Hb=7e3,_i=class{constructor(e){this.subscription=new Nu;this.loadMediaTimeoutSubscription=new Nu;this.videoState=new L("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:Wr(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:Wr(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:Wr(e)}break}default:Wr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Vb(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 Nu;this.subscription.add(e),this.subscription.add(Ub(this.videoState.stateChangeStarted$.pipe(qb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(qb(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 IR;e.add(i.pipe(_b(AR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(or(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)>PR)&&i.next(o),s=o})),e.add(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(or(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<wR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:Wr(n)}}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Ub(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,TR(["init"])).pipe(_b(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"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(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"),E(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"),E(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"&&E(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];nr(c);let d=xR(Object.keys(c));nr(d);let p=c[d];nr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];nr(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];nr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];nr(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];nr(c),r=ce(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:Nb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Wr(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 Fb(o)&&(n.metadata.title=o),Fb(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(ER(Hb).subscribe(()=>s(`timeout(${Hb})`)))});(0,jb.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:Nb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var sl=B(We(),1);import{clearVideoElement as Qb}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as kR}from"@vkontakte/videoplayer-shared/es2018";var Gb=a=>{try{a.pause(),a.playbackRate=0,kR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as RR,Subscription as $R}from"@vkontakte/videoplayer-shared/es2018";var Fu=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)}},qu=window.WeakMap?new WeakMap:new Fu,Uu=window.WeakMap?new WeakMap:new Map,LR=(a,e=20)=>{let t=0;return RR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},be=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Qb(t):(t=document.createElement("video"),a.appendChild(t)),qu.set(t,r);let i=new $R;return i.add(LR(t,e)),Uu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ge=a=>{let e=Uu.get(a);e==null||e.unsubscribe(),Uu.delete(a);let t=qu.get(a);qu.delete(a),t?Qb(a):Gb(a)};var ju=B(Yr(),1);import{assertNonNullable as Ni,isNonNullable as rt,isNullable as NR,fromEvent as zr,merge as Zb,observableFrom as eg,filterChanged as tg,map as Fi,Subject as rg,Subscription as FR,ValueSubject as qR,ErrorCategory as UR}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Hu,isNullable as VR,Subscription as _R}from"@vkontakte/videoplayer-shared/es2018";var Gs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=VR(i),l=new _R;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},tt=(a,e,t)=>Gs(e,()=>a.loop,r=>{Hu(r)&&(a.loop=r)},{onError:t}),ve=(a,e,t,r)=>Gs(e,()=>({muted:a.muted,volume:a.volume}),i=>{Hu(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}),Oe=(a,e,t,r)=>Gs(e,()=>a.playbackRate,i=>{Hu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),$t=Gs;var HR=a=>["__",a.language,a.label].join("|"),jR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Gu=class a{constructor(){this.available$=new rg;this.current$=new qR(void 0);this.error$=new rg;this.subscription=new FR;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:UR.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($t(t.internalTextTracks,()=>(0,ju.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Fi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add($t(t.externalTextTracks,()=>(0,ju.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Fi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add($t(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($t(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ni(this.video);let{textTracks:e}=this.video;this.subscription.add(zr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Zb(zr(e,"addtrack"),zr(e,"removetrack"),eg(["init"])).pipe(Fi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),tg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Zb(zr(e,"change"),eg(["init"])).pipe(Fi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Fi(r=>r&&this.htmlTextTrackToITextTrack(r).id),tg()).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(zr(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(zr(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;rt(t.align)&&(i.align=t.align),rt(t.position)&&(i.position=t.position),rt(t.size)&&(i.size=t.size),rt(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Ni(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:HR(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){Ni(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(NR(e)||!jR(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){Ni(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Ni(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)}},Be=Gu;var lt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var ig=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Qu=a=>{let e=ig(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ag=a=>{let e=ig(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ve,map as Lt,merge as ng,filterChanged as QR,isNonNullable as og,Subject as WR,filter as ug,mapTo as lg,combine as YR,once as zR,ErrorCategory as KR,ValueSubject as cg,clientChecker as JR}from"@vkontakte/videoplayer-shared/es2018";var GR=3,sg=(a,e,t=GR)=>{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 Se=a=>{let e=y=>Ve(a,y).pipe(lg(void 0)),r=ng(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Ve(a,y))).pipe(Lt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),QR()),i=ng(Ve(a,"progress"),Ve(a,"timeupdate")).pipe(Lt(()=>sg(a.buffered,a.currentTime))),s=JR.isSafari?YR({play:e("play").pipe(zR()),playing:e("playing")}).pipe(lg(void 0)):e("playing"),n=Ve(a,"volumechange").pipe(Lt(()=>({muted:a.muted,volume:a.volume}))),o=Ve(a,"ratechange").pipe(Lt(()=>a.playbackRate)),u=Ve(a,"error").pipe(ug(()=>!!(a.error||a.played.length)),Lt(()=>{var x;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:KR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(x=a.error)!=null?x:void 0}})),l=Ve(a,"timeupdate").pipe(Lt(()=>a.currentTime)),c=new WR,d=.3,p;l.subscribe(y=>{a.loop&&og(p)&&og(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(ug(()=>!a.error&&p!==a.duration)),f=Ve(a,"enterpictureinpicture"),b=Ve(a,"leavepictureinpicture"),g=new cg(ag(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new cg(Qu(a));return Ve(a,"fullscreenchange").pipe(Lt(()=>Qu(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$:Ve(a,"durationchange").pipe(Lt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as Mt}from"@vkontakte/videoplayer-shared/es2018";var Ct=a=>{switch(a){case"mobile":return Mt.Q_144P;case"lowest":return Mt.Q_240P;case"low":return Mt.Q_360P;case"sd":case"medium":return Mt.Q_480P;case"hd":case"high":return Mt.Q_720P;case"fullhd":case"full":return Mt.Q_1080P;case"quadhd":case"quad":return Mt.Q_1440P;case"ultrahd":case"ultra":return Mt.Q_2160P}};var Dt=B(Kr(),1),Eg=B(We(),1),Qs=B(Vr(),1);import{isNonNullable as ie,isNullable as Yu,now as xg,isHigher as zu,isHigherOrEqual as Ku,isInvariantQuality as yg,isLower as Tg,isLowerOrEqual as Ju,videoSizeToQuality as n$,assertNotEmptyArray as Pg,assertNonNullable as o$}from"@vkontakte/videoplayer-shared/es2018";var Wu=!1,ct={},gg=a=>{Wu=a},vg=()=>{ct={}},Sg=a=>{a(ct)},qi=(a,e)=>{var t;Wu&&(ct.meta=(t=ct.meta)!=null?t:{},ct.meta[a]=e)},pe=class{constructor(e){this.name=e}next(e){var r,i;if(!Wu)return;ct.series=(r=ct.series)!=null?r:{};let t=(i=ct.series[this.name])!=null?i:[];t.push([Date.now(),e]),ct.series[this.name]=t}};var u$=new pe("best_bitrate"),wg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Xu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ui=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=xg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Ag='Assertion "ABR Tracks is empty array" failed',Ws=(a,e,t,r)=>{var u;let i=[...e].sort(Xu(1)),s=[...t].sort(Xu(1)),n=s.filter(l=>ie(l.bitrate)&&ie(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Dt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Dt.default)(s,-1);return o&&(0,Eg.default)(n,o)?o:n.length?(0,Dt.default)(n,-1):(0,Dt.default)(s,0)},Ig=a=>"quality"in a,kg=(a,e,t,r)=>{var n;let i=ie((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&ie(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&xg()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Ig(o)?"video":"audio",l=Ig(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return r==null||r.recordSwitch(t),t},a$=(a,e)=>Math.log(e)/Math.log(a),Mt=(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:h,stallsPredictedThroughput:p,abrLogger:f})=>{var _,k,w,H,J,A;vg(a,yg);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let O=r.pixelRatioLogBase,[M=0,Z=0,Le=0]=r.pixelRatioLogCoefficients,mt=a$(O,M*T+Z)+Le;Number.isFinite(mt)&&(b*=mt)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,v=r.considerPlaybackRate&&re(o)?o:1,S=a.filter(T=>!hg(T.quality)).sort((T,O)=>Hu(T.quality,O.quality)?-1:1),y=(_=(0,Lt.default)(S,-1))==null?void 0:_.quality,E=(k=(0,Lt.default)(S,0))==null?void 0:k.quality,I=Uu(i)||re(i.min)&&re(i.max)&&fg(i.max,i.min)||re(i.min)&&E&&Hu(i.min,E)||re(i.max)&&y&&fg(i.max,y),R=v*Sg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),C={},$=S.filter(T=>{let O=!0;if(g)if(T.size)O=T.size.width<=g.width&&T.size.height<=g.height;else{let ne=g&&t$(g);O=ne?Gu(T.quality,ne):!0}if(!O)return C[T.quality]="FitsContainer",!1;let M=p||t;if(!(re(M)&&isFinite(M)&&re(T.bitrate)?M-s>=T.bitrate*R:!0))return C[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&re(r.minBufferToSwitchUp)&&u&&!hg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Hu(T.quality,u.quality))return C[T.quality]="Buffer",!1;if(!!d&&ju(T.quality,d))return C[T.quality]="DroppedFramesLimit",!1;if(!!h&&ju(T.quality,h))return C[T.quality]="StallsLimit",!1;let F=I||(Uu(i.max)||Gu(T.quality,i.max))&&(Uu(i.min)||ju(T.quality,i.min)),se=re(c)&&!c?Gu(T.quality,r.backgroundVideoQualityLimit):!0;return!F||!se?(C[T.quality]="FitsQualityLimits",!1):!0})[0];$&&$.bitrate&&i$.next($.bitrate);let B=(w=$!=null?$:(0,Lt.default)(S,-1))!=null?w:a[0];return B.quality!==((H=l==null?void 0:l.last)==null?void 0:H.quality)&&f({message:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},l$=(a,e)=>Math.log(e)/Math.log(a),Ot=(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 N,A,k,j,Z,w;Pg(a,Ag);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let $=r.pixelRatioLogBase,[R=0,te=0,Me=0]=r.pixelRatioLogCoefficients,gt=l$($,R*T+te)+Me;Number.isFinite(gt)&&(b*=gt)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,v=r.considerPlaybackRate&&ie(o)?o:1,S=a.filter(T=>!yg(T.quality)).sort((T,$)=>zu(T.quality,$.quality)?-1:1),y=(N=(0,Dt.default)(S,-1))==null?void 0:N.quality,x=(A=(0,Dt.default)(S,0))==null?void 0:A.quality,I=Yu(i)||ie(i.min)&&ie(i.max)&&Tg(i.max,i.min)||ie(i.min)&&x&&zu(i.min,x)||ie(i.max)&&y&&Tg(i.max,y),M=v*wg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),C={},O=S.filter(T=>{let $=!0;if(g)if(T.size)$=T.size.width<=g.width&&T.size.height<=g.height;else{let oe=g&&n$(g);$=oe?Ju(T.quality,oe):!0}if(!$)return C[T.quality]="FitsContainer",!1;let R=h||t;if(!(ie(R)&&isFinite(R)&&ie(T.bitrate)?R-s>=T.bitrate*M:!0))return C[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&ie(r.minBufferToSwitchUp)&&u&&!yg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&zu(T.quality,u.quality))return C[T.quality]="Buffer",!1;if(!!d&&Ku(T.quality,d))return C[T.quality]="DroppedFramesLimit",!1;if(!!p&&Ku(T.quality,p))return C[T.quality]="StallsLimit",!1;let F=I||(Yu(i.max)||Ju(T.quality,i.max))&&(Yu(i.min)||Ku(T.quality,i.min)),ne=ie(c)&&!c?Ju(T.quality,r.backgroundVideoQualityLimit):!0;return!F||!ne?(C[T.quality]="FitsQualityLimits",!1):!0})[0];O&&O.bitrate&&u$.next(O.bitrate);let V=(k=O!=null?O:(0,Dt.default)(S,-1))!=null?k:a[0];return V.quality!==((j=l==null?void 0:l.last)==null?void 0:j.quality)&&f({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate} }`).join(`
12
+ ${a.map(T=>{var $,R;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${($=T.size)==null?void 0:$.width}:${(R=T.size)==null?void 0:R.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,Ns.default)(r!=null?r:{}).map(([T,O])=>`${T}: ${O}`).join(`
16
+ ${(0,Qs.default)(r!=null?r:{}).map(([T,$])=>`${T}: ${$}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
- containerSizeLimit: ${(J=g==null?void 0:g.width)!=null?J:0} x ${(A=g==null?void 0:g.width)!=null?A:0},
20
+ containerSizeFactor: ${b},
21
+ containerSizeLimit: ${(Z=g==null?void 0:g.width)!=null?Z:0} x ${(w=g==null?void 0:g.height)!=null?w:0},
21
22
  estimatedThroughput: ${t},
22
- stallsPredictedThroughput: ${p},
23
+ stallsPredictedThroughput: ${h},
23
24
  reserve: ${s},
24
25
  playbackRate: ${o},
25
26
  playbackRateFactor: ${v},
26
27
  forwardBufferHealth: ${n},
27
- bitrateFactor: ${R},
28
+ bitrateFactor: ${M},
28
29
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
29
30
  droppedVideoMaxQualityLimit: ${d},
30
- stallsVideoMaxQualityLimit: ${h},
31
+ stallsVideoMaxQualityLimit: ${p},
31
32
  limitsAreInvalid: ${I},
32
33
  maxQualityLimit: ${i==null?void 0:i.max},
33
34
  minQualityLimit: ${i==null?void 0:i.min},
34
35
 
35
36
  [limited video tracks]
36
- ${(0,Ns.default)(C).map(([T,O])=>`${T}: ${O}`).join(`
37
+ ${(0,Qs.default)(C).map(([T,$])=>`${T}: ${$}`).join(`
37
38
  `)||"All tracks are available"}
38
39
 
39
- [best video track] ${$==null?void 0:$.quality}
40
- [selected video track] ${B==null?void 0:B.quality}
41
- `}),Tg(r,f,B,l)},Ig=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;vg(t,yg);let c=i.considerPlaybackRate&&re(s)?s:1,d=[...t].sort(Qu(-1)),h=a.bitrate;r$(h);let p=c*Sg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=Fs(a,e,t,i.minVideoAudioRatio),g=l||r;return re(g)&&isFinite(g)&&(f=d.find(S=>re(S.bitrate)&&re(b==null?void 0:b.bitrate)?g-h>=S.bitrate*p&&S.bitrate>=b.bitrate:!1)),f||(f=b),(f==null?void 0:f.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
40
+ [best video track] ${O==null?void 0:O.quality}
41
+ [selected video track] ${V==null?void 0:V.quality}
42
+ `}),kg(r,f,V,l)},Rg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Pg(t,Ag);let c=i.considerPlaybackRate&&ie(s)?s:1,d=[...t].sort(Xu(-1)),p=a.bitrate;o$(p);let h=c*wg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=Ws(a,e,t,i.minVideoAudioRatio),g=l||r;return ie(g)&&isFinite(g)&&(f=d.find(S=>ie(S.bitrate)&&ie(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
43
  [AUDIO TRACKS ABR]
43
44
  [available audio tracks]
44
45
  ${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
45
46
  `)}
46
47
 
47
48
  [tuning]
48
- ${(0,Ns.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
49
+ ${(0,Qs.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
49
50
  `)}
50
51
 
51
52
  [limit params]
52
53
  estimatedThroughput: ${r},
53
54
  stallsPredictedThroughput: ${l},
54
- reserve: ${h},
55
+ reserve: ${p},
55
56
  playbackRate: ${s},
56
57
  playbackRateFactor: ${c},
57
58
  forwardBufferHealth: ${n},
58
- bitrateFactor: ${p},
59
+ bitrateFactor: ${h},
59
60
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
60
61
 
61
62
  [selected audio track] ${f==null?void 0:f.id}
62
- `}),f&&Tg(i,u,f,o)};var ie=a=>new URL(a).hostname;import{assertNever as Mg,assertNonNullable as Cg,combine as P$,debounce as A$,ErrorCategory as Dg,filter as Og,filterChanged as w$,isNonNullable as Ju,map as Gs,merge as Vg,observableFrom as k$,once as R$,Subscription as $$,ValueSubject as Xu,videoQualityToHeight as L$,videoSizeToQuality as M$}from"@vkontakte/videoplayer-shared/es2018";var xg=V(Xe(),1),Eg=a=>{if(a instanceof DOMException&&(0,xg.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"))},ye=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!Eg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return Eg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Us,isNullable as o$,assertNonNullable as _i}from"@vkontakte/videoplayer-shared/es2018";var Ag=V(Li(),1);import{isNonNullable as Pg,assertNonNullable as qs,now as s$}from"@vkontakte/videoplayer-shared/es2018";function ae(){return s$()}function Wu(a){return ae()-a}function Yu(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 wg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function jr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;qs(c);let k=Wu(c),w;if(k<b){w=b-k,setTimeout(g,w);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,R()},v=k=>(s=k,_),S=k=>(d=k,_),y=()=>(p="json",_),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=k=>(h=k,_),R=()=>{c=ae(),n=new i,n.open("get",a);let k=0,w,H=0,J=()=>(qs(c),Math.max(c,Math.max(w||0,H||0)));if(s&&n.addEventListener("progress",A=>{let T=ae();s.updateChunk&&A.loaded>k&&(s.updateChunk(J(),A.loaded-k),k=A.loaded,w=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;qs(n);let A=n.status;if(A>=200&&A<300){if(n.response.byteLength&&s){let T=n.response.byteLength-k;T&&s.updateChunk&&s.updateChunk(J(),T)}n.responseType==="json"&&!(0,Ag.default)(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),h){let A=()=>{qs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(H=ae(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=p,n.send(),_},_={withBitrateReporting:v,withParallel:I,withJSONResponse:y,withRetryCount:k=>(l=k,_),withRetryInterval:(k,w)=>(Pg(k)&&(b=k),Pg(w)&&(f=w),_),withTimeout:k=>(o=k,_),withFinally:S,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return _}var Vi=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 kg=V(Li(),1);var Bi=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=ae(),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=ae()-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=jr(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=ae()}_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=ae();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,kg.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 u$}from"@vkontakte/videoplayer-shared/es2018";var Hs=1e4,zu=3;var l$=6e4,c$=10,d$=1,p$=500,Ni=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 u$,this.chunkRateEstimator=new Vi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Yu(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=Yu(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||Us(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=()=>{wg(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 Bi(zu,Hs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let E=s&&(!c||c===this.rep);return E||t("Not running!"),E},h=(E,I,R)=>{u&&u.abort(),u=jr(this.urlResolver.resolve(E,!1),I,R,()=>this._retryCallback()).withTimeout(Hs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(zu).withFinally(()=>{u=null}).send()},p=(E,I,R)=>{_i(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=E=>{let I=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),r.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=ae()-1e4,C=0;for(let $=0;$<this.bufferStates.length;$++){let B=this.bufferStates[$];E=Math.min(E,B.buf),B.ts<R&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${E} drop=${C} jitter=${this.sourceJitter}`);let G=E-d$;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?f(1.15):G>1?f(1.1):G>.3?f(1.05):f(1)}},v=E=>{let I,R=()=>I&&I.start?I.start.length:0,C=A=>I.start[A]/1e3,G=A=>I.dur[A]/1e3,$=A=>I.fragIndex+A,B=(A,T)=>({chunkIdx:$(A),startTS:C(A),dur:G(A),discontinuity:T}),_=()=>{let A=0;if(I&&I.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,O=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,M=T;this.sourceJitter>1&&(M+=this.sourceJitter-1);let Z=I.dur.length-1;for(;Z>=0&&(M-=I.dur[Z],!(M<=0));--Z);A=Math.min(Z,I.dur.length-1-O),A=Math.max(A,0)}return B(A,!0)},k=A=>{let T=R();if(!(T<=0)){if(Us(A)){for(let O=0;O<T;O++)if(C(O)>A)return B(O)}return _()}},w=A=>{let T=R(),O=A?A.chunkIdx+1:0,M=O-I.fragIndex;if(!(T<=0)){if(!A||M<0||M-T>c$)return t(`Resync: offset=${M} bChunks=${T} chunk=`+JSON.stringify(A)),_();if(!(M>=T))return B(O-I.fragIndex,!1)}},H=(A,T,O)=>{l&&l.abort(),l=jr(this.urlResolver.resolve(A,!0,this.lowLatency),T,O,()=>this._retryCallback()).withTimeout(Hs).withRetryCount(zu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,T)=>{H(E,O=>{if(!d())return;I=O;let M=!!I.lowLatency;M!==this.lowLatency&&b(M);let Z=0;for(let Le=0;Le<I.dur.length;++Le)Z+=I.dur[Le];Z>0&&(_i(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,A(k(T))},()=>this._handleNetworkError())},nextChunk:w}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),_i(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:I,logger:R}=this.params,C=v(e.jidxUrl),G,$,B,_,k=0,w,H,J,A=()=>{w&&(clearTimeout(w),w=void 0);let F=Math.max(p$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),se=k+F,ne=ae(),Me=Math.min(1e4,se-ne);k=ne;let bt=()=>{l||d()&&C.seek(()=>{d()&&(k=ae(),T(),A())})};Me>0?w=window.setTimeout(()=>{this.paused?A():bt()},Me):bt()},T=()=>{let F;for(;F=C.nextChunk(_);)_=F,mt(F);let se=C.nextChunk(B);if(se){if(B&&se.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?A():(S(),this._initPlayerWith(e));return}Le(se)}else A()},O=(F,se)=>{if(!d()||!this.sourceBuffer)return;let ne,Me,bt,fr=gt=>{window.setTimeout(()=>{d()&&O(F,se)},gt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),fr(100);else{let gt=ae(),qt=I.currentTime;!this.paused&&I.buffered.length>1&&H===qt&&gt-J>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),H!==qt&&(H=qt,J=gt);let mr=this._getBufferSizeSec();if(mr>30)R(`Buffered ${mr} seconds; delaying appendBuffer`),fr(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:gt,buf:mr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),se&&se()}catch(ti){if(ti.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),bt=this.sourceBuffer.buffered.length,bt!==0&&(ne=this.sourceBuffer.buffered.start(0),Me=qt,Me-ne>4&&this.sourceBuffer.remove(ne,Me-3)),fr(1e3);else throw ti}}},M=()=>{$&&G&&(R([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(B)]),O($,function(){$=null,T()}))},Z=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),Le=F=>{d()&&p(Z(F),(se,ne)=>{if(d()){if(ne/=1e3,$=se,B=F,n=F.startTS,ne){let Me=Math.min(10,F.dur/ne);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Me:Me}M()}},()=>this._handleNetworkError())},mt=F=>{d()&&(_i(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(F),!1)))},hr=F=>{d()&&(e.cachedHeader=F,O(F,()=>{G=!0,M()}))};s=!0,C.seek(F=>{if(d()){if(k=ae(),!F){A();return}_=F,!o$(E)||F.startTS>E?Le(F):(B=F,T())}},E),e.cachedHeader?hr(e.cachedHeader):h(e.headerUrl,hr,()=>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(),Us(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,_i(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Us(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),f=d/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let f=ae();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Wu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ae();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=jr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Hs).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;ye(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))},l$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Lg=V(Lr(),1);import{debounce as h$,filter as Rg,fromEvent as f$,interval as m$,isHigher as b$,isInvariantQuality as g$,isLower as v$,merge as S$,Subject as $g,Subscription as y$}from"@vkontakte/videoplayer-shared/es2018";var Ku=class{constructor(){this.onDroopedVideoFramesLimit$=new $g;this.subscription=new y$;this.playing=!1;this.tracks=[];this.forceChecker$=new $g;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&&!g$(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&&b$(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(f$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=m$(this.droppedFramesChecker.checkTime).pipe(Rg(()=>this.playing),Rg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(h$(this.droppedFramesChecker.checkTime)),r=S$(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,Lg.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>v$(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}},js=Ku;import{map as T$,Observable as I$}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as E$}from"@vkontakte/videoplayer-shared/es2018";var Fi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var x$=(a,e)=>new I$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Fi()))},{...r,...e});i.observe(a);let s=E$(document,"visibilitychange").pipe(T$(n=>!document.hidden||Fi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Be=x$;var C$=["paused","playing","ready"],D$=["paused","playing","ready"],qi=class{constructor(e){this.subscription=new $$;this.videoState=new L("stopped");this.representations$=new Xu([]);this.textTracksManager=new Oe;this.droppedFramesManager=new js;this.maxSeekBackTime$=new Xu(1/0);this.zeroTime$=new Xu(void 0);this.liveOffset=new ot;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:Dg.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:M$(u.video),d=u.bitrate/1e3,h={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((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),Ju(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,Zu.default)(D$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Zu.default)(C$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ce(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(ce(this.params.source.url,u))}return;default:return Mg(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Dg.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Vg(this.videoState.stateChangeStarted$.pipe(Gs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Gs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=be(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(ie(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=Se(this.video);this.subscription.add(this.representations$.pipe(Gs(i=>i.map(({track:s})=>s)),Og(i=>!!i.length),R$()).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(w$(),Gs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(P$({zeroTime:this.zeroTime$.pipe(Og(Ju)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ze(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(De(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(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&L$(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 Mg(i.to)}},t)).add(Vg(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,k$(["init"])).pipe(A$(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),ge(this.video)}createLiveDashPlayer(){let e=new Ni({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,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=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Ju(t)?t:Mt(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=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.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;Cg(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;Cg(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(ce(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Bg=qi;var yy=V(Xe(),1);var tt=(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 yC,assertNonNullable as TC,debounce as IC,ErrorCategory as _l,filter as gy,filterChanged as ka,fromEvent as EC,isNonNullable as vy,map as Nl,merge as yn,observableFrom as xC,once as Sy,Subscription as PC}from"@vkontakte/videoplayer-shared/es2018";var Qs=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}},Gr=class extends Qs{constructor(){super(),this.listeners||Qs.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)}},Ui=class{constructor(){Object.defineProperty(this,"signal",{value:new Gr,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&&(Ui.prototype[Symbol.toStringTag]="AbortController",Gr.prototype[Symbol.toStringTag]="AbortSignal");function Ws(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 el(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Ws({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 h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Hi=Ws({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),_g=Hi?el({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=Hi?_g.fetch:window.fetch,jN=Hi?_g.Request:window.Request,ke=Hi?Ui:window.AbortController,GN=Hi?Gr:window.AbortSignal;var Ol=V(rl(),1);var rn=V(Hr(),1);var ct=()=>window.ManagedMediaSource||window.MediaSource,Ys=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},av=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},sv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as sn,clientChecker as an}from"@vkontakte/videoplayer-shared/es2018";var _e=document.createElement("video"),sL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',nL='video/mp4; codecs="hev1.1.6.L93.B0"',bv='video/webm; codecs="vp09.00.10.08"',gv='video/webm; codecs="av01.0.00M.08"',oL='audio/mp4; codecs="mp4a.40.2"',uL='audio/webm; codecs="opus"',nv,ov,ji={mms:Ys(),mse:av(),hls:!!((nv=_e.canPlayType)!=null&&nv.call(_e,"application/x-mpegurl")||(ov=_e.canPlayType)!=null&&ov.call(_e,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},uv,lv,Te={mp4:!!((uv=_e.canPlayType)!=null&&uv.call(_e,"video/mp4")),webm:!!((lv=_e.canPlayType)!=null&&lv.call(_e,"video/webm")),cmaf:!0},Ks,cv,Js,dv,Xs,pv,Zs,hv,en,fv,tn,mv,Ie={h264:!!((cv=(Ks=ct())==null?void 0:Ks.isTypeSupported)!=null&&cv.call(Ks,sL)),h265:!!((dv=(Js=ct())==null?void 0:Js.isTypeSupported)!=null&&dv.call(Js,nL)),vp9:!!((pv=(Xs=ct())==null?void 0:Xs.isTypeSupported)!=null&&pv.call(Xs,bv)),av1:!!((hv=(Zs=ct())==null?void 0:Zs.isTypeSupported)!=null&&hv.call(Zs,gv)),aac:!!((fv=(en=ct())==null?void 0:en.isTypeSupported)!=null&&fv.call(en,oL)),opus:!!((mv=(tn=ct())==null?void 0:tn.isTypeSupported)!=null&&mv.call(tn,uL))},Qr=(Ie.h264||Ie.h265)&&Ie.aac,ir,lL=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:gv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:bv}})]);ir={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{lL()}catch(a){console.error(a)}var Wr=ji.hls&&Te.mp4,vv=()=>Object.keys(Ie).filter(a=>Ie[a]),Sv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ji.mse&&(!r||!!window.MediaStreamTrack)||ji.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Te.mp4&&Qr;case"DASH_WEBM":return i&&Te.webm&&Ie.vp9&&Ie.opus;case"DASH_WEBM_AV1":return i&&Te.webm&&Ie.av1&&Ie.opus;case"DASH_STREAMS":return i&&(Te.mp4&&Qr||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return i&&Te.mp4&&Qr;case"DASH_LIVE_CMAF":return i&&Te.mp4&&Qr&&Te.cmaf;case"DASH_ONDEMAND":return i&&Te.mp4&&Qr;case"HLS":case"HLS_ONDEMAND":return Wr||e&&i&&Te.mp4&&Qr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Wr;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ji.webrtc&&ji.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return sn(s)}})},zs=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 ir?ir[t].smooth?[t,e]:ir[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ir?ir[t].powerEfficient?[t,e]:ir[e].powerEfficient?[e,t]:[t,e]:[e,t];default:sn(a)}return[e,t]},yv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...zs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(an.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",...zs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...zs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...zs(a),...i,"HLS","HLS_ONDEMAND"];default:sn(e)}return Wr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Tv=({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=an.isMac&&an.isSafari;if(an.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:sn(a)}else Wr&&!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"]},il=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Iv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,rn.default)(t.value.split("."),0)}for(let t of a){let r=(0,rn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,rn.default)(e.value.split("."),0)};var Hv=V(Uv(),1);import{ErrorCategory as Qi}from"@vkontakte/videoplayer-shared/es2018";var jv=a=>{if(!a)return{id:"EmptyResponse",category:Qi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Qi.NETWORK,message:`UV Error ${a}`};let e=(0,Hv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Qi.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:Qi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Qi.PARSER,message:"Response is valid XML, but parser failed"}};var Ct=(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 Ml,assertNonNullable as lr,clientChecker as eC,combine as xa,ErrorCategory as Bt,filter as fn,filterChanged as Cl,flattenObject as Pa,fromEvent as cr,getTraceSubscriptionMethod as tC,interval as Dl,isNonNullable as uy,map as Aa,merge as dr,now as rC,Subject as ly,Subscription as cy,tap as iC,throttle as aC,ValueSubject as K}from"@vkontakte/videoplayer-shared/es2018";var un=V(Xe(),1),Jr=V(Hr(),1),ln=V(rl(),1);var AL=(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)},wL=a=>window.clearTimeout(a),Gv=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Qv=!Gv(window.requestIdleCallback)||!Gv(window.cancelIdleCallback),ul=Qv?AL:window.requestIdleCallback,Wi=Qv?wL:window.cancelIdleCallback;var ey=V(Os(),1);import{assertNever as kL,ErrorCategory as Wv,clientChecker as ll,Subject as Yv}from"@vkontakte/videoplayer-shared/es2018";var RL=18,zv=!1;try{zv=ll.isSafari&&!!ll.macVersion&&ll.macVersion<=RL}catch(a){console.error(a)}var cl=class{constructor(e){this.bufferFull$=new Yv;this.error$=new Yv;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Wv.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){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()})}async abort(e){return new Promise(t=>{let r;zv&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)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:Wv.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:kL(t)}}},Kv=cl;var dl=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 nr,assertNonNullable as he,ErrorCategory as Ot,fromEvent as wl,getExponentialDelay as kl,isNonNullable as nn,isNullable as Ne,now as on,once as jM,Subject as GM,Subscription as QM,ValueSubject as Kr}from"@vkontakte/videoplayer-shared/es2018";var U=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),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let 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 Yr=class extends U{};var Yi=class extends U{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 zi=class extends U{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 Ki=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var W=class extends U{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ji=class extends W{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 Xi=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zi=class extends U{constructor(e,t){super(e,t),this.data=this.content}};var ar=class extends W{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 ea=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ta=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends W{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 ia=class extends W{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var aa=class extends W{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 U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var na=class extends W{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 oa=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ua=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var la=class extends W{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ca=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends W{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 W{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 ha=class extends W{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 LL={ftyp:zi,moov:Ki,mvhd:Ji,moof:Xi,mdat:Zi,sidx:ar,trak:ea,mdia:sa,mfhd:la,tkhd:na,traf:ca,tfhd:da,tfdt:pa,trun:ha,minf:oa,sv3d:ta,st3d:ra,prhd:ia,proj:ua,equi:aa,uuid:Yi,unknown:Yr},dt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=LL[e];return r?new r(t,new a):new Yr(t,new a)}};var Dt=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 CL=new TextDecoder("ascii"),DL=a=>CL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",OL=a=>{let e=new ar(a,new dt),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})},VL=(a,e)=>{let r=new dt().parse(a),i=new Dt(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)},BL=a=>{let t=new dt().parse(a),r=new Dt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},_L=a=>{var i;let t=new dt().parse(a);return(i=new Dt(t).find("sidx"))==null?void 0:i.timescale},NL=(a,e)=>{let r=new dt().parse(a),s=new Dt(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,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},FL=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 dt().parse(a),i=new Dt(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},Jv={validateData:DL,parseInit:FL,getIndexRange:()=>{},parseSegments:OL,parseFeedableSegmentChunk:VL,getChunkEndTime:NL,getServerLatencyTimestamps:BL,getTimescaleFromIndex:_L};var ma=V(Xe(),1);import{assertNonNullable as hl,isNonNullable as tS,isNullable as UL}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as qL}from"@vkontakte/videoplayer-shared/es2018";var Xv={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"}},Zv=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=fa(a,t),i=r in Xv,s=i?Xv[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=fa(u),d=l*2**((o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},fa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Qe=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return fa(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:qL(e)}},sr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Zv(r);if(!e(i))return;i.type==="master"&&sr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},eS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Zv(a);return sr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Qe(o,n):s===17026?t=Qe(o,n):s===17029&&(r=Qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var rS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],HL=[231,22612,22743,167,171,163,160,175],jL=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return sr(a,({tag:h,type:p,value:f,valueSize:b})=>{if(h===21419){let g=Qe(f,p);l=fa(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Qe(f,p):h===17545?i=Qe(f,p):h===21420&&l===475249515?u=Qe(f,p):h===374648427?sr(f,({tag:g,type:v,value:S})=>g===30321?(c=Qe(S,v)===1,!1):!0):s&&n&&(0,ma.default)(rS,h)&&(o=!0),!o}),hl(e,"Failed to parse webm Segment start"),hl(t,"Failed to parse webm Segment end"),hl(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}}}},GL=a=>{if(UL(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},QL=(a,e)=>{let t=!1,r=!1,i=o=>tS(o.time)&&tS(o.position),s=[],n;return sr(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=Qe(l,u));break;case 183:break;case 241:n&&(n.position=Qe(l,u));break;default:t&&(0,ma.default)(rS,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}}})},WL=a=>{let e=0,t=!1;try{sr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ma.default)(HL,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},iS={validateData:eS,parseInit:jL,getIndexRange:GL,parseSegments:QL,parseFeedableSegmentChunk:WL};var ba=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return iS;case"mp4":return Jv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var yl=V(ES(),1),QS=V(Lr(),1),WS=V(NS(),1),YS=V(Hr(),1);var FS=V(Xe(),1),Sl=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,FS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as HS,isNullable as jS}from"@vkontakte/videoplayer-shared/es2018";var qS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var US=a=>{var e;try{let t=UM(),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 UM(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
63
+ `}),f&&kg(i,u,f,o)};var ae=a=>new URL(a).hostname;import{assertNever as Ng,assertNonNullable as Fg,combine as $$,debounce as L$,ErrorCategory as qg,filter as Ug,filterChanged as M$,isNonNullable as il,map as Xs,merge as Hg,observableFrom as C$,once as D$,Subscription as O$,ValueSubject as al,videoQualityToHeight as B$,videoSizeToQuality as V$}from"@vkontakte/videoplayer-shared/es2018";var Lg=B(We(),1),$g=a=>{if(a instanceof DOMException&&(0,Lg.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"))},ye=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!$g(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return $g(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as zs,isNullable as p$,assertNonNullable as Gi}from"@vkontakte/videoplayer-shared/es2018";var Cg=B(Yr(),1);import{isNonNullable as Mg,assertNonNullable as Ys,now as c$}from"@vkontakte/videoplayer-shared/es2018";function se(){return c$()}function Zu(a){return se()-a}function el(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 Dg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Jr(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;Ys(c);let A=Zu(c),k;if(A<b){k=b-A,setTimeout(g,k);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,M()},v=A=>(s=A,N),S=A=>(d=A,N),y=()=>(h="json",N),x=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=A=>(p=A,N),M=()=>{c=se(),n=new i,n.open("get",a);let A=0,k,j=0,Z=()=>(Ys(c),Math.max(c,Math.max(k||0,j||0)));if(s&&n.addEventListener("progress",w=>{let T=se();s.updateChunk&&w.loaded>A&&(s.updateChunk(Z(),w.loaded-A),A=w.loaded,k=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(u)return;Ys(n);let w=n.status;if(w>=200&&w<300){if(n.response.byteLength&&s){let T=n.response.byteLength-A;T&&s.updateChunk&&s.updateChunk(Z(),T)}n.responseType==="json"&&!(0,Cg.default)(n.response).length?x():(d&&d(),e(n.response))}else x()}),n.addEventListener("error",()=>{x()}),p){let w=()=>{Ys(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(j=se(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=h,n.send(),N},N={withBitrateReporting:v,withParallel:I,withJSONResponse:y,withRetryCount:A=>(l=A,N),withRetryInterval:(A,k)=>(Mg(A)&&(b=A),Mg(k)&&(f=k),N),withTimeout:A=>(o=A,N),withFinally:S,send:M,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return N}var Hi=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 Og=B(Yr(),1);var ji=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=se(),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=se()-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=Jr(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=se()}_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=se();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,Og.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 h$}from"@vkontakte/videoplayer-shared/es2018";var Ks=1e4,tl=3;var f$=6e4,m$=10,b$=1,g$=500,Qi=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 h$,this.chunkRateEstimator=new Hi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=el(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=el(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||zs(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=()=>{Dg(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ji(tl,Ks,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,I,M)=>{u&&u.abort(),u=Jr(this.urlResolver.resolve(x,!1),I,M,()=>this._retryCallback()).withTimeout(Ks).withBitrateReporting(this.bitrateSwitcher).withRetryCount(tl).withFinally(()=>{u=null}).send()},h=(x,I,M)=>{Gi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),I,M,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=x=>{let I=r.playbackRate;r.playbackRate!==x&&(t(`Playback rate switch: ${I}=>${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 M=se()-1e4,C=0;for(let O=0;O<this.bufferStates.length;O++){let V=this.bufferStates[O];x=Math.min(x,V.buf),V.ts<M&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${x} drop=${C} jitter=${this.sourceJitter}`);let U=x-b$;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?f(1.15):U>1?f(1.1):U>.3?f(1.05):f(1)}},v=x=>{let I,M=()=>I&&I.start?I.start.length:0,C=w=>I.start[w]/1e3,U=w=>I.dur[w]/1e3,O=w=>I.fragIndex+w,V=(w,T)=>({chunkIdx:O(w),startTS:C(w),dur:U(w),discontinuity:T}),N=()=>{let w=0;if(I&&I.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,$=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,R=T;this.sourceJitter>1&&(R+=this.sourceJitter-1);let te=I.dur.length-1;for(;te>=0&&(R-=I.dur[te],!(R<=0));--te);w=Math.min(te,I.dur.length-1-$),w=Math.max(w,0)}return V(w,!0)},A=w=>{let T=M();if(!(T<=0)){if(zs(w)){for(let $=0;$<T;$++)if(C($)>w)return V($)}return N()}},k=w=>{let T=M(),$=w?w.chunkIdx+1:0,R=$-I.fragIndex;if(!(T<=0)){if(!w||R<0||R-T>m$)return t(`Resync: offset=${R} bChunks=${T} chunk=`+JSON.stringify(w)),N();if(!(R>=T))return V($-I.fragIndex,!1)}},j=(w,T,$)=>{l&&l.abort(),l=Jr(this.urlResolver.resolve(w,!0,this.lowLatency),T,$,()=>this._retryCallback()).withTimeout(Ks).withRetryCount(tl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,T)=>{j(x,$=>{if(!d())return;I=$;let R=!!I.lowLatency;R!==this.lowLatency&&b(R);let te=0;for(let Me=0;Me<I.dur.length;++Me)te+=I.dur[Me];te>0&&(Gi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,w(A(T))},()=>this._handleNetworkError())},nextChunk:k}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Gi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:x=>{let{videoElement:I,logger:M}=this.params,C=v(e.jidxUrl),U,O,V,N,A=0,k,j,Z,w=()=>{k&&(clearTimeout(k),k=void 0);let F=Math.max(g$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=A+F,oe=se(),Ce=Math.min(1e4,ne-oe);A=oe;let vt=()=>{l||d()&&C.seek(()=>{d()&&(A=se(),T(),w())})};Ce>0?k=window.setTimeout(()=>{this.paused?w():vt()},Ce):vt()},T=()=>{let F;for(;F=C.nextChunk(N);)N=F,gt(F);let ne=C.nextChunk(V);if(ne){if(V&&ne.discontinuity){M("Detected discontinuity; restarting playback"),this.paused?w():(S(),this._initPlayerWith(e));return}Me(ne)}else w()},$=(F,ne)=>{if(!d()||!this.sourceBuffer)return;let oe,Ce,vt,yr=St=>{window.setTimeout(()=>{d()&&$(F,ne)},St)};if(this.sourceBuffer.updating)M("Source buffer is updating; delaying appendBuffer"),yr(100);else{let St=se(),jt=I.currentTime;!this.paused&&I.buffered.length>1&&j===jt&&St-Z>500&&(M("Stall suspected; trying to fix"),this._fixupStall()),j!==jt&&(j=jt,Z=St);let Tr=this._getBufferSizeSec();if(Tr>30)M(`Buffered ${Tr} seconds; delaying appendBuffer`),yr(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:Tr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(ui){if(ui.name==="QuotaExceededError")M("QuotaExceededError; delaying appendBuffer"),vt=this.sourceBuffer.buffered.length,vt!==0&&(oe=this.sourceBuffer.buffered.start(0),Ce=jt,Ce-oe>4&&this.sourceBuffer.remove(oe,Ce-3)),yr(1e3);else throw ui}}},R=()=>{O&&U&&(M([`Appending chunk, sz=${O.byteLength}:`,JSON.stringify(V)]),$(O,function(){O=null,T()}))},te=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),Me=F=>{d()&&h(te(F),(ne,oe)=>{if(d()){if(oe/=1e3,O=ne,V=F,n=F.startTS,oe){let Ce=Math.min(10,F.dur/oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ce:Ce}R()}},()=>this._handleNetworkError())},gt=F=>{d()&&(Gi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(F),!1)))},Sr=F=>{d()&&(e.cachedHeader=F,$(F,()=>{U=!0,R()}))};s=!0,C.seek(F=>{if(d()){if(A=se(),!F){w();return}N=F,!p$(x)||F.startTS>x?Me(F):(V=F,T())}},x),e.cachedHeader?Sr(e.cachedHeader):p(e.headerUrl,Sr,()=>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(),zs(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,Gi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return zs(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=se();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&&Zu(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=se();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Jr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ks).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;ye(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))},f$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var _g=B(Vr(),1);import{debounce as v$,filter as Bg,fromEvent as S$,interval as y$,isHigher as T$,isInvariantQuality as I$,isLower as E$,merge as x$,Subject as Vg,Subscription as P$}from"@vkontakte/videoplayer-shared/es2018";var rl=class{constructor(){this.onDroopedVideoFramesLimit$=new Vg;this.subscription=new P$;this.playing=!1;this.tracks=[];this.forceChecker$=new Vg;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!I$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&T$(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(S$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=y$(this.droppedFramesChecker.checkTime).pipe(Bg(()=>this.playing),Bg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(v$(this.droppedFramesChecker.checkTime)),r=x$(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,_g.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}},Js=rl;import{map as w$,Observable as A$}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as k$}from"@vkontakte/videoplayer-shared/es2018";var Wi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var R$=(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||Wi()))},{...r,...e});i.observe(a);let s=k$(document,"visibilitychange").pipe(w$(n=>!document.hidden||Wi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),_e=R$;var _$=["paused","playing","ready"],N$=["paused","playing","ready"],Yi=class{constructor(e){this.subscription=new O$;this.videoState=new L("stopped");this.representations$=new al([]);this.textTracksManager=new Be;this.droppedFramesManager=new Js;this.maxSeekBackTime$=new al(1/0);this.zeroTime$=new al(void 0);this.liveOffset=new lt;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:qg.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=Ct(u.name))!=null?r:V$(u.video),d=u.bitrate/1e3,p={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),il(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,sl.default)(N$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,sl.default)(_$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ce(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(ce(this.params.source.url,u))}return;default:return Ng(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:qg.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Hg(this.videoState.stateChangeStarted$.pipe(Xs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Xs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=be(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(ae(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=Se(this.video);this.subscription.add(this.representations$.pipe(Xs(i=>i.map(({track:s})=>s)),Ug(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(M$(),Xs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add($$({zeroTime:this.zeroTime$.pipe(Ug(il)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Oe(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(_e(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&B$(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 Ng(i.to)}},t)).add(Hg(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(L$(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),ge(this.video)}createLiveDashPlayer(){let e=new Qi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&il(t)?t:Ot(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;Fg(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;Fg(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(ce(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var jg=Yi;var ky=B(We(),1);var it=(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 A0,assertNonNullable as k0,debounce as R0,ErrorCategory as jl,filter as Py,filterChanged as Ba,fromEvent as $0,isNonNullable as wy,map as Gl,merge as wn,observableFrom as Ql,once as Ay,Subscription as L0}from"@vkontakte/videoplayer-shared/es2018";var Zs=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}},Xr=class extends Zs{constructor(){super(),this.listeners||Zs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},zi=class{constructor(){Object.defineProperty(this,"signal",{value:new Xr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(zi.prototype[Symbol.toStringTag]="AbortController",Xr.prototype[Symbol.toStringTag]="AbortSignal");function en(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 nl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!en({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 Ki=en({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Gg=Ki?nl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,dt=Ki?Gg.fetch:window.fetch,KN=Ki?Gg.Request:window.Request,$e=Ki?zi:window.AbortController,JN=Ki?Xr:window.AbortSignal;var ql=B(ul(),1);var cn=B(Kr(),1);var pt=()=>window.ManagedMediaSource||window.MediaSource,tn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},dv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},pv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as pn,clientChecker as dn}from"@vkontakte/videoplayer-shared/es2018";var Ne=document.createElement("video"),cL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',dL='video/mp4; codecs="hev1.1.6.L93.B0"',Ev='video/webm; codecs="vp09.00.10.08"',xv='video/webm; codecs="av01.0.00M.08"',pL='audio/mp4; codecs="mp4a.40.2"',hL='audio/webm; codecs="opus"',hv,fv,Ji={mms:tn(),mse:dv(),hls:!!((hv=Ne.canPlayType)!=null&&hv.call(Ne,"application/x-mpegurl")||(fv=Ne.canPlayType)!=null&&fv.call(Ne,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},mv,bv,Te={mp4:!!((mv=Ne.canPlayType)!=null&&mv.call(Ne,"video/mp4")),webm:!!((bv=Ne.canPlayType)!=null&&bv.call(Ne,"video/webm")),cmaf:!0},an,gv,sn,vv,nn,Sv,on,yv,un,Tv,ln,Iv,Ie={h264:!!((gv=(an=pt())==null?void 0:an.isTypeSupported)!=null&&gv.call(an,cL)),h265:!!((vv=(sn=pt())==null?void 0:sn.isTypeSupported)!=null&&vv.call(sn,dL)),vp9:!!((Sv=(nn=pt())==null?void 0:nn.isTypeSupported)!=null&&Sv.call(nn,Ev)),av1:!!((yv=(on=pt())==null?void 0:on.isTypeSupported)!=null&&yv.call(on,xv)),aac:!!((Tv=(un=pt())==null?void 0:un.isTypeSupported)!=null&&Tv.call(un,pL)),opus:!!((Iv=(ln=pt())==null?void 0:ln.isTypeSupported)!=null&&Iv.call(ln,hL))},Zr=(Ie.h264||Ie.h265)&&Ie.aac,ur,fL=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:xv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Ev}})]);ur={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{fL()}catch(a){console.error(a)}var ei=Ji.hls&&Te.mp4,Pv=()=>Object.keys(Ie).filter(a=>Ie[a]),wv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Ji.mse&&(!r||!!window.MediaStreamTrack)||Ji.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Te.mp4&&Zr;case"DASH_WEBM":return i&&Te.webm&&Ie.vp9&&Ie.opus;case"DASH_WEBM_AV1":return i&&Te.webm&&Ie.av1&&Ie.opus;case"DASH_STREAMS":return i&&(Te.mp4&&Zr||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return i&&Te.mp4&&Zr;case"DASH_LIVE_CMAF":return i&&Te.mp4&&Zr&&Te.cmaf;case"DASH_ONDEMAND":return i&&Te.mp4&&Zr;case"HLS":case"HLS_ONDEMAND":return ei||e&&i&&Te.mp4&&Zr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ei;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ji.webrtc&&Ji.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return pn(s)}})},rn=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 ur?ur[t].smooth?[t,e]:ur[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ur?ur[t].powerEfficient?[t,e]:ur[e].powerEfficient?[e,t]:[t,e]:[e,t];default:pn(a)}return[e,t]},Av=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...rn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(dn.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",...rn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...rn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...rn(a),...i,"HLS","HLS_ONDEMAND"];default:pn(e)}return ei?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},kv=({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=dn.isMac&&dn.isSafari;if(dn.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:pn(a)}else ei&&!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"]},ll=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Rv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,cn.default)(t.value.split("."),0)}for(let t of a){let r=(0,cn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,cn.default)(e.value.split("."),0)};var Kv=B(zv(),1);import{ErrorCategory as Zi}from"@vkontakte/videoplayer-shared/es2018";var Jv=a=>{if(!a)return{id:"EmptyResponse",category:Zi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Zi.NETWORK,message:`UV Error ${a}`};let e=(0,Kv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Zi.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:Zi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Zi.PARSER,message:"Response is valid XML, but parser failed"}};var Bt=(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 Nl,assertNonNullable as mr,clientChecker as o0,combine as si,ErrorCategory as Ft,filter as Ma,filterChanged as yn,flattenObject as Ca,fromEvent as br,getTraceSubscriptionMethod as u0,interval as Fl,isNonNullable as by,map as Da,merge as gr,now as l0,Subject as gy,Subscription as vy,tap as c0,throttle as d0,ValueSubject as X}from"@vkontakte/videoplayer-shared/es2018";var fn=B(We(),1),ii=B(Kr(),1),mn=B(ul(),1);var LL=(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)},ML=a=>window.clearTimeout(a),Xv=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Zv=!Xv(window.requestIdleCallback)||!Xv(window.cancelIdleCallback),fl=Zv?LL:window.requestIdleCallback,ea=Zv?ML:window.cancelIdleCallback;var uy=B(Us(),1);import{assertNever as CL,ErrorCategory as eS,clientChecker as ml,Subject as tS}from"@vkontakte/videoplayer-shared/es2018";var DL=18,rS=!1;try{rS=ml.isSafari&&!!ml.macVersion&&ml.macVersion<=DL}catch(a){console.error(a)}var bl=class{constructor(e){this.bufferFull$=new tS;this.error$=new tS;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:eS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){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()})}async abort(e){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:eS.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:CL(t)}}},iS=bl;var gl=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 dr,assertNonNullable as Fe,clientChecker as KM,ErrorCategory as _t,fromEvent as Dl,getExponentialDelay as Ol,isNonNullable as Pa,isNullable as xe,now as hn,once as JM,Subject as XM,Subscription as ZM,ValueSubject as pr}from"@vkontakte/videoplayer-shared/es2018";var H=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ti=class extends H{};var ta=class extends H{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ra=class extends H{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ia=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Y=class extends H{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var aa=class extends Y{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 sa=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var na=class extends H{constructor(e,t){super(e,t),this.data=this.content}};var lr=class extends Y{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 oa=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ua=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var la=class extends Y{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 ca=class extends Y{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var da=class extends Y{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var pa=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ha=class extends Y{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 fa=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ma=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ba=class extends Y{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ga=class extends H{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var va=class extends Y{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 Sa=class extends Y{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 ya=class extends Y{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 BL={ftyp:ra,moov:ia,mvhd:aa,moof:sa,mdat:na,sidx:lr,trak:oa,mdia:pa,mfhd:ba,tkhd:ha,traf:ga,tfhd:va,tfdt:Sa,trun:ya,minf:fa,sv3d:ua,st3d:la,prhd:ca,proj:ma,equi:da,uuid:ta,unknown:ti},ht=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=BL[e];return r?new r(t,new a):new ti(t,new a)}};var Vt=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 _L=new TextDecoder("ascii"),NL=a=>_L.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",FL=a=>{let e=new lr(a,new ht),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})},qL=(a,e)=>{let r=new ht().parse(a),i=new Vt(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)},UL=a=>{let t=new ht().parse(a),r=new Vt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},HL=a=>{var i;let t=new ht().parse(a);return(i=new Vt(t).find("sidx"))==null?void 0:i.timescale},jL=(a,e)=>{let r=new ht().parse(a),s=new Vt(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},GL=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 ht().parse(a),i=new Vt(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},aS={validateData:NL,parseInit:GL,getIndexRange:()=>{},parseSegments:FL,parseFeedableSegmentChunk:qL,getChunkEndTime:jL,getServerLatencyTimestamps:UL,getTimescaleFromIndex:HL};var Ia=B(We(),1);import{assertNonNullable as Sl,isNonNullable as uS,isNullable as WL}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as QL}from"@vkontakte/videoplayer-shared/es2018";var sS={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"}},nS=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=Ta(a,t),i=r in sS,s=i?sS[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=Ta(u),d=l*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}},Ta=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ta(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:QL(e)}},cr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=nS(r);if(!e(i))return;i.type==="master"&&cr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},oS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=nS(a);return cr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=ze(o,n):s===17026?t=ze(o,n):s===17029&&(r=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var lS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],YL=[231,22612,22743,167,171,163,160,175],zL=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return cr(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=ze(f,h);l=Ta(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=ze(f,h):p===17545?i=ze(f,h):p===21420&&l===475249515?u=ze(f,h):p===374648427?cr(f,({tag:g,type:v,value:S})=>g===30321?(c=ze(S,v)===1,!1):!0):s&&n&&(0,Ia.default)(lS,p)&&(o=!0),!o}),Sl(e,"Failed to parse webm Segment start"),Sl(t,"Failed to parse webm Segment end"),Sl(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}}}},KL=a=>{if(WL(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},JL=(a,e)=>{let t=!1,r=!1,i=o=>uS(o.time)&&uS(o.position),s=[],n;return cr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=ze(l,u));break;case 183:break;case 241:n&&(n.position=ze(l,u));break;default:t&&(0,Ia.default)(lS,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}}})},XL=a=>{let e=0,t=!1;try{cr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Ia.default)(YL,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Ia.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},cS={validateData:oS,parseInit:zL,getIndexRange:KL,parseSegments:JL,parseFeedableSegmentChunk:XL};var Ea=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return cS;case"mp4":return aS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ll=B($S(),1),ry=B(Vr(),1),iy=B(QS(),1),ay=B(Kr(),1),Ml=B(Yr(),1);var WS=B(We(),1),Pl=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,WS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as zM,isNullable as ey}from"@vkontakte/videoplayer-shared/es2018";var YS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var zS=a=>{var e;try{let t=WM(),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 WM(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
63
64
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
64
65
  (-(?<script>[a-z]{4}))?
65
66
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
66
67
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
67
68
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
68
69
  (?:-(?<privateuse>(?:${e})))?
69
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var GS=a=>{if(!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},pt=(a,e)=>{let t=a;t=(0,yl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,QS.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,yl.default)(t,n,(o,u)=>jS(s)?o:jS(u)?s:(0,WS.default)(s,parseInt(u,10),"0"))}return t},zS=(a,e)=>{var I,R,C,G,$,B,_,k,w,H,J,A,T,O,M,Z,Le,mt,hr,F,se,ne,Me,bt,fr,gt,qt,mr,ti,tc,rc,ic,ac,sc,nc,oc,uc,lc,cc,dc,pc,hc,fc,mc,bc,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(oe=>{var Ua,vt;return(vt=(Ua=oe.textContent)==null?void 0:Ua.trim())!=null?vt:""}),u=(I=(0,YS.default)(o,0))!=null?I:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],v=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=GS(f);else if(b){let oe=GS(b);HS(oe)&&(p=oe)}else v&&(p=parseInt(v,10));let S=0,y=(C=(R=s.getAttribute("profiles"))==null?void 0:R.split(","))!=null?C:[];for(let oe of l){let Ua=(G=oe.getAttribute("id"))!=null?G:"id"+(S++).toString(10),vt=($=oe.getAttribute("mimeType"))!=null?$:"",Dn=(B=oe.getAttribute("codecs"))!=null?B:"",On=(_=oe.getAttribute("contentType"))!=null?_:vt==null?void 0:vt.split("/")[0],bT=(w=(k=oe.getAttribute("profiles"))==null?void 0:k.split(","))!=null?w:[],Mc=(J=US((H=oe.getAttribute("lang"))!=null?H:""))!=null?J:{},gT=(O=(T=(A=oe.querySelector("Label"))==null?void 0:A.textContent)==null?void 0:T.trim())!=null?O:void 0,vT=oe.querySelectorAll("Representation"),ST=oe.querySelector("SegmentTemplate"),yT=(Z=(M=oe.querySelector("Role"))==null?void 0:M.getAttribute("value"))!=null?Z:void 0,ri=On,ee={id:Ua,language:Mc.language,isDefault:yT==="main",label:gT,codecs:Dn,hdr:ri==="video"&&Sl(Dn),mime:vt,representations:[]};for(let Q of vT){let TT=(Le=Q.getAttribute("lang"))!=null?Le:void 0,IT=(mt=Q.getAttribute("label"))!=null?mt:void 0,ET=(se=(F=(hr=Q.querySelector("BaseURL"))==null?void 0:hr.textContent)==null?void 0:F.trim())!=null?se:"",Ha=new URL(ET||u,e).toString(),br=(ne=Q.getAttribute("mimeType"))!=null?ne:vt,ja=(bt=(Me=Q.getAttribute("codecs"))!=null?Me:Dn)!=null?bt:"",Ga;if(On==="text"){let St=Q.getAttribute("id")||"",Qa=((fr=Mc.privateuse)==null?void 0:fr.includes("x-auto"))||St.includes("_auto"),Ut=Q.querySelector("SegmentTemplate");if(Ut){let ii={representationId:(gt=Q.getAttribute("id"))!=null?gt:void 0,bandwidth:(qt=Q.getAttribute("bandwidth"))!=null?qt:void 0},Wa=parseInt((mr=Q.getAttribute("bandwidth"))!=null?mr:"",10)/1e3,Ya=(tc=parseInt((ti=Ut.getAttribute("startNumber"))!=null?ti:"",10))!=null?tc:1,gr=parseInt((rc=Ut.getAttribute("timescale"))!=null?rc:"",10),Vn=(ic=Ut.querySelectorAll("SegmentTimeline S"))!=null?ic:[],vr=Ut.getAttribute("media");if(!vr)continue;let za=[],Ka=0,Ja="",Sr=0,ai=Ya,de=0;for(let Fe of Vn){let Ht=parseInt((ac=Fe.getAttribute("d"))!=null?ac:"",10),Ce=parseInt((sc=Fe.getAttribute("r"))!=null?sc:"",10)||0,yt=parseInt((nc=Fe.getAttribute("t"))!=null?nc:"",10);de=Number.isFinite(yt)?yt:de;let jt=Ht/gr*1e3,Tt=de/gr*1e3;for(let Ye=0;Ye<Ce+1;Ye++){let It=pt(vr,{...ii,segmentNumber:ai.toString(10),segmentTime:(de+Ye*Ht).toString(10)}),yr=(Tt!=null?Tt:0)+Ye*jt,ni=yr+jt;ai++,za.push({time:{from:yr,to:ni},url:It})}de+=(Ce+1)*Ht,Ka+=(Ce+1)*jt}Sr=de/gr*1e3,Ja=pt(vr,{...ii,segmentNumber:ai.toString(10),segmentTime:de.toString(10)});let si={time:{from:Sr,to:1/0},url:Ja},it={type:"template",baseUrl:Ha,segmentTemplateUrl:vr,initUrl:"",totalSegmentsDurationMs:Ka,segments:za,nextSegmentBeyondManifest:si,timescale:gr};Ga={id:St,kind:"text",segmentReference:it,profiles:[],duration:p,bitrate:Wa,mime:"",codecs:"",width:0,height:0,isAuto:Qa}}else Ga={id:St,isAuto:Qa,kind:"text",url:Ha}}else{let St=(uc=(oc=Q.getAttribute("contentType"))!=null?oc:br==null?void 0:br.split("/")[0])!=null?uc:On,Qa=(cc=(lc=oe.getAttribute("profiles"))==null?void 0:lc.split(","))!=null?cc:[],Ut=parseInt((dc=Q.getAttribute("width"))!=null?dc:"",10),ii=parseInt((pc=Q.getAttribute("height"))!=null?pc:"",10),Wa=parseInt((hc=Q.getAttribute("bandwidth"))!=null?hc:"",10)/1e3,Ya=(fc=Q.getAttribute("frameRate"))!=null?fc:"",gr=(mc=Q.getAttribute("quality"))!=null?mc:void 0,Vn=Ya?qS(Ya):void 0,vr=(bc=Q.getAttribute("id"))!=null?bc:"id"+(S++).toString(10),za=St==="video"?`${ii}p`:St==="audio"?`${Wa}Kbps`:ja,Ka=`${vr}@${za}`,Ja=[...y,...bT,...Qa],Sr,ai=Q.querySelector("SegmentBase"),de=(gc=Q.querySelector("SegmentTemplate"))!=null?gc:ST;if(ai){let it=(Sc=(vc=Q.querySelector("SegmentBase Initialization"))==null?void 0:vc.getAttribute("range"))!=null?Sc:"",[Fe,Ht]=it.split("-").map(It=>parseInt(It,10)),Ce={from:Fe,to:Ht},yt=(yc=Q.querySelector("SegmentBase"))==null?void 0:yc.getAttribute("indexRange"),[jt,Tt]=yt?yt.split("-").map(It=>parseInt(It,10)):[],Ye=yt?{from:jt,to:Tt}:void 0;Sr={type:"byteRange",url:Ha,initRange:Ce,indexRange:Ye}}else if(de){let it={representationId:(Tc=Q.getAttribute("id"))!=null?Tc:void 0,bandwidth:(Ic=Q.getAttribute("bandwidth"))!=null?Ic:void 0},Fe=parseInt((Ec=de.getAttribute("timescale"))!=null?Ec:"",10),Ht=(xc=de.getAttribute("initialization"))!=null?xc:"",Ce=de.getAttribute("media"),yt=(Ac=parseInt((Pc=de.getAttribute("startNumber"))!=null?Pc:"",10))!=null?Ac:1,jt=pt(Ht,it);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");let Tt=(wc=de.querySelectorAll("SegmentTimeline S"))!=null?wc:[],Ye=[],It=0,yr="",ni=0;if(Tt.length){let Xa=yt,qe=0;for(let Tr of Tt){let ze=parseInt((kc=Tr.getAttribute("d"))!=null?kc:"",10),Gt=parseInt((Rc=Tr.getAttribute("r"))!=null?Rc:"",10)||0,Za=parseInt(($c=Tr.getAttribute("t"))!=null?$c:"",10);qe=Number.isFinite(Za)?Za:qe;let Bn=ze/Fe*1e3,_n=qe/Fe*1e3;for(let es=0;es<Gt+1;es++){let PT=pt(Ce,{...it,segmentNumber:Xa.toString(10),segmentTime:(qe+es*ze).toString(10)}),Cc=(_n!=null?_n:0)+es*Bn,AT=Cc+Bn;Xa++,Ye.push({time:{from:Cc,to:AT},url:PT})}qe+=(Gt+1)*ze,It+=(Gt+1)*Bn}ni=qe/Fe*1e3,yr=pt(Ce,{...it,segmentNumber:Xa.toString(10),segmentTime:qe.toString(10)})}else if(HS(p)){let qe=parseInt((Lc=de.getAttribute("duration"))!=null?Lc:"",10)/Fe*1e3,Tr=Math.ceil(p/qe),ze=0;for(let Gt=1;Gt<Tr;Gt++){let Za=pt(Ce,{...it,segmentNumber:Gt.toString(10),segmentTime:ze.toString(10)});Ye.push({time:{from:ze,to:ze+qe},url:Za}),ze+=qe}ni=ze,yr=pt(Ce,{...it,segmentNumber:Tr.toString(10),segmentTime:ze.toString(10)})}let xT={time:{from:ni,to:1/0},url:yr};Sr={type:"template",baseUrl:Ha,segmentTemplateUrl:Ce,initUrl:jt,totalSegmentsDurationMs:It,segments:Ye,nextSegmentBeyondManifest:xT,timescale:Fe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!St||!br)continue;let si={video:"video",audio:"audio",text:"text"}[St];if(!si)continue;ri||(ri=si),Ga={id:Ka,kind:si,segmentReference:Sr,profiles:Ja,duration:p,bitrate:Wa,mime:br,codecs:ja,width:Ut,height:ii,fps:Vn,quality:gr}}ee.language||(ee.language=TT),ee.label||(ee.label=IT),ee.mime||(ee.mime=br),ee.codecs||(ee.codecs=ja),ee.hdr||(ee.hdr=ri==="video"&&Sl(ja)),ee.representations.push(Ga)}ri&&i[ri].push(ee)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var El=V(Hr(),1);import{videoSizeToQuality as HM}from"@vkontakte/videoplayer-shared/es2018";var KS=({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:HM({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},JS=({id:a,bitrate:e})=>({id:a,bitrate:e}),XS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ZS=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),xl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,El.default)(r.split("."),0),isDefault:i}),Pl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,El.default)(i.split("."),0)}),Al=a=>"url"in a,Re=a=>a.type==="template",ga=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var va=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Kr(0);this.currentSegmentLength$=new Kr(0);this.onLastSegment$=new Kr(!1);this.fullyBuffered$=new Kr(!1);this.playingRepresentation$=new Kr(void 0);this.playingRepresentationInit$=new Kr(void 0);this.error$=new GM;this.gaps=[];this.subscription=new QM;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ke;this.switchAbortController=new ke;this.destroyAbortController=new ke;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=nr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);he(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Kv(this.sourceBuffer),this.subscription.add(wl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(wl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ot.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,dl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=tt(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);he(r,"No init buffer for starting representation"),he(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.switchToOld=nr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);he(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ne(s)||Ne(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),he(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(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();nn(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=nr(this.destroyAbortController.signal,async function*(e){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(f=>f.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Re(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);he(i);let s=this.segments.get(r);he(s,"No segments for starting representation");let n=this.initData.get(r);if(he(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,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}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ke,nr(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);he(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Ne(o)||Ne(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),he(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(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();nn(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))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ke,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Ne(e)||Ne(this.downloadingRepresentationId)||Ne(this.playingRepresentationId)||Ne(this.sourceBuffer)||nn(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(he(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=tt(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&dl(this.sourceBuffer.buffered)>=this.bufferLimit){let d=tt(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,un.default)(o,i))d="high";else{let h=(0,Jr.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&tt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Jr.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;nn(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,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:[];for(let o of t){if(!o||!Re(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Jr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;he(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Re(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=pt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}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&&Wi&&Wi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Wi&&Wi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.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:h,to:p}},f)=>{let b=h<=r&&p>=r,g=h>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=r+v||p<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&!(Ct(this.sourceBuffer.buffered,h)&&Ct(this.sourceBuffer.buffered,p)))&&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 h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,r="auto"){Re(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){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&&(await nr(o,async function*(){let c=kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=on(),!c)return;let d=new DataView(c),h=ba(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=h.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(d);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),ga(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())Re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await nr(n,async function*(){let u=kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),wl(window,"online").pipe(jM()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=on(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ga(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Re(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Jr.default)(e,0).byte.from,to:(0,Jr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=on(),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:Ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Re(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=on();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:Ot.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,un.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=ba(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){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)continue;if(s.aborted){n();continue}let c=l.byte.from-r,d=l.byte.to-r,h=d-c+1,p=c<i,f=d<=i;if(!p)continue;let b=ba(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,i-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===h?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(he(this.sourceBuffer),Ct(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ct(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Ot.VIDEO_PIPELINE,message:"Safari 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",Al(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");he(this.sourceBuffer),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=ul(()=>(0,ey.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?nr(this.destroyAbortController.signal,async function*(){let o=kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ba(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Re(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ot.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ne(e)||this.sourceBuffer.updating)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:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=Al(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,un.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(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?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||Ne(e)?0:tt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)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){he(this.sourceBuffer);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=ul(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ot.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ne(this.sourceBuffer)||Ne(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 Sa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ty=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 ya,assertNever as iy,fromEvent as ay,merge as WM,now as Ta,Subscription as YM,ValueSubject as Rl,flattenObject as Xr}from"@vkontakte/videoplayer-shared/es2018";var ry=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var cn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Rl(void 0);this.lastConnectionReused$=new Rl(void 0);this.lastRequestFirstBytes$=new Rl(void 0);this.abortAllController=new ke;this.subscription=new YM;this.fetchManifest=ya(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Sa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=ry(r));let i=yield lt(r,{signal:this.abortAllController.signal}).catch(Ia);return i?(t.log("success",Xr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Xr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ya(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var _,k;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let w=new URL(l,location.href);w.searchParams.append("bytes",`${r.from}-${r.to}`),l=w.toString();break}default:iy(t)}this.requestQuic&&(l=Sa(l));let h=this.abortAllController.signal,p;if(n){let w=new ke;if(p=WM(ay(this.abortAllController.signal,"abort"),ay(n,"abort")).subscribe(()=>{try{w.abort()}catch(H){Ia(H)}}),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch(H){Ia(H)}h=w.signal}let f=Ta();d.log("startRequest",Xr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield lt(l,{priority:s,headers:c,signal:h}).catch(Ia),g=Ta();if(!b)return d.error("error",{message:"No response in request"}),d.end(),p==null||p.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(g-f),!b.ok||!b.body){p==null||p.unsubscribe();let w=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:w}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){p==null||p.unsubscribe();let w=Ta(),H={requestStartedAt:f,requestEndedAt:w,duration:w-f};return d.log("endRequest",Xr(H)),d.end(),b.arrayBuffer()}let[v,S]=b.body.tee(),y=v.getReader();o&&((k=this.throughputEstimator)==null||k.trackStream(S,u));let E=0,I=new Uint8Array(0),R=!1,C=w=>{p==null||p.unsubscribe(),R=!0,Ia(w)},G=ya(h,async function*({done:w,value:H}){if(E===0&&this.lastRequestFirstBytes$.next(Ta()-f),h.aborted){p==null||p.unsubscribe();return}if(!w&&H){let J=new Uint8Array(I.length+H.length);J.set(I),J.set(H,I.length),I=J,E+=H.byteLength,i==null||i(new DataView(I.buffer),E),yield y==null?void 0:y.read().then(G,C)}}.bind(this));yield y==null?void 0:y.read().then(G,C),p==null||p.unsubscribe();let $=Ta(),B={failed:R,requestStartedAt:f,requestEndedAt:$,duration:$-f};return R?(d.error("endRequest",Xr(B)),d.end(),null):(d.log("endRequest",Xr(B)),d.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=ya(this.abortAllController.signal,async function*(e,t,r){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 h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(v=e.indexRange)!=null?v:t.getIndexRange(p);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,p,f);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=ya(this.abortAllController.signal,async function*(e,t){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=>({...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}=ty(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:iy(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ia=a=>{if(!ga(a))throw a};var or=(a,e,t)=>t*e+(1-t)*a,$l=(a,e)=>a.reduce((t,r)=>t+r,0)/e,sy=(a,e,t,r)=>{let i=0,s=t,n=$l(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 zM,ValueSubject as ny}from"@vkontakte/videoplayer-shared/es2018";var Vt=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 ny(e.initial),this.debounced$=new ny(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new pe(`raw_${t}`),this.smoothedSeries$=new pe(`smoothed_${t}`),this.reportedSeries$=new pe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let 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)&&(zM(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var dn=class extends Vt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=or(this.slow,e,this.params.emaAlphaSlow),this.fast=or(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var pn=class extends Vt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=$l(this.pastMeasures,this.takenMeasures);this.emaSmoothed=or(this.emaSmoothed,e,this.params.emaAlpha);let r=sy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var hn=class extends Vt{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?or(this.smoothed,t,this.params.emaAlpha):t}};var ur=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new dn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new pn({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 hn({initial:e,label:"liveEdgeDelay",...t})}};var Ll=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as KM,ValueSubject as JM}from"@vkontakte/videoplayer-shared/es2018";var Ea=class a{constructor(e,t){this.currentRepresentation$=new JM(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(!KM(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,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&&Re(t.segmentReference))}};var sC=["timeupdate","progress","play","seeked","stalled","waiting"],nC=["timeupdate","progress","loadeddata","playing","seeked"];var mn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new cy;this.representationSubscription=new cy;this.state$=new L("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new ly;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.liveDuration$=new K(0);this.liveAvailabilityStartTime$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.isLowLatency$=new K(!1);this.isActiveLowLatency$=new K(!1);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new ly;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=Ml(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ce(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:Bt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ml(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Bt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=zS(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=jv(e))!=null?n:{id:"ManifestParsing",category:Bt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,h,p,f;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((f=(p=ct())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:f})=>r(u,p,f)),d=new Set(c.map(({codecs:p})=>p)),h=Iv(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);eC.isHDR&&p&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",Pa(s)),s}.bind(this));this.initRepresentations=Ml(this.destroyController.signal,async function*(e,t,r){var h;this.tracer.log("initRepresentationsStart",Pa({initialVideo:e,initialAudio:t,sourceHls:r})),lr(this.manifest),lr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(cr(p,"error").pipe(fn(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Bt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?sv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ys())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,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new va("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],uy(t)){let p=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new va("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ea.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ea(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(Dl(1e3).subscribe(p=>{var f;if((f=this.element)!=null&&f.paused){let b=Vs(this.manifestUrlString,2);this.manifestUrlString=ce(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(dr(...nC.map(p=>cr(this.element,p))).pipe(Aa(p=>this.element?tt(this.element.buffered,this.element.currentTime*1e3):0),Cl(),iC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(dr(cr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Cl()).subscribe(f=>Ll(this.element,1))),this.representationSubscription.add(xa({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(fn(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(xa({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(fn(({isLive:f})=>f),Aa(f=>({...f})),Cl((f,b)=>b.bufferLength<f.bufferLength),Aa(({rtt:f,bufferLength:b,segmentServerLatency:g})=>{let v=Vs(this.manifestUrlString,2);return(f/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(xa({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=f-g,E=1;Math.abs(y)>v&&(E=1+Math.sign(y)*S),Ll(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,v;let b=0;if(f){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var I,R;return(R=(I=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?R:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(xa({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(aC(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:b})=>{if(lr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Vs(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,R=isFinite(f)?f:b,C=this.isActiveLowLatency$.getValue(),G=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(C&&G);let $="none";if(C?$="active_low_latency":this.isLowLatency$.getValue()&&G?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),$="active_low_latency"):v!==0&&R<y?$="live_forward_buffering":R<y+I&&($="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let B=p-(y+E),_=this.normolizeLiveOffset(Math.trunc(v+B/g)),k=Math.abs(_-v),w;!f||k<=this.tuning.dashCmafLive.offsetCalculationError?w=v:_>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=_:w=0,this.manifestUrlString=ce(this.manifestUrlString,w,2)}$!=="none"&&$!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=dr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Aa(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=dr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Aa(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(dr(this.forceEnded$,xa({allBuffersFull:l,someBufferEnded:c}).pipe(fn(({allBuffersFull:p,someBufferEnded:f})=>p&&f))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Bt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(dr(...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 f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...(0,Ol.default)((0,Ol.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let f=[];return p.duration&&f.push(p.duration),Re(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&uy(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=Dl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Bt.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 cn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=ur.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;lr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ce(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){lr(this.element),this.state$.setState("running"),this.subscription.add(dr(...sC.map(e=>cr(this.element,e)),cr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Bt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(cr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(cr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ct(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,b,g,v,S,y,E,I,R;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=rC(),n=100,o=(f=(p=this.videoBufferManager)==null?void 0:p.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=(E=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?E:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&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;(I=this.videoBufferManager)==null||I.maintain(C),(R=this.audioBufferManager)==null||R.maintain(C),i.position=C}this.tracer.log("stallIntervalCallback",Pa(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Dl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Bt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u;lr(this.element),lr(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),Ct(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Pa({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>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=tC(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(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={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Pa(t)))}}};var bn=class{constructor(e,t){this.fov=e,this.orientation=t}};var gn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let 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={...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*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var dy=`attribute vec2 a_vertex;
70
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Al=B(Kr(),1);import{videoSizeToQuality as YM}from"@vkontakte/videoplayer-shared/es2018";var KS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ct(s):void 0)!=null?u:YM({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},JS=({id:a,bitrate:e})=>({id:a,bitrate:e}),XS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ZS=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),kl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Al.default)(r.split("."),0),isDefault:i}),Rl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Al.default)(i.split("."),0)}),$l=a=>"url"in a,he=a=>a.type==="template",xa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ty=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},ft=(a,e)=>{let t=a;t=(0,Ll.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,Ll.default)(t,n,(o,u)=>ey(s)?o:ey(u)?s:(0,iy.default)(s,parseInt(u,10),"0"))}return t},sy=(a,e)=>{var I,M,C,U,O,V,N,A,k,j,Z,w,T,$,R,te,Me,gt,Sr,F,ne,oe,Ce,vt,yr,St,jt,Tr,ui,uc,lc,cc,dc,pc,hc,fc,mc,bc,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,wc,Ac,kc,Rc,$c,Lc,Mc,Cc,Dc,Oc,Bc,Vc,_c;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 W,Gt;return(Gt=(W=qe.textContent)==null?void 0:W.trim())!=null?Gt:""}),o=(I=(0,ay.default)(n,0))!=null?I:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],f=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((qe,W)=>({...qe,[W.id]:W.children}),{}),v=b.reduce((qe,W)=>({...qe,[W.id]:W.getAttribute("duration")}),{});p?d=ty(p):(0,Ml.default)(v).filter(qe=>qe).length&&!u?d=(0,Ml.default)(v).reduce((qe,W)=>{var Gt;return qe+((Gt=ty(W))!=null?Gt:0)},0):f&&(d=parseInt(f,10));let S=0,y=(C=(M=s.getAttribute("profiles"))==null?void 0:M.split(","))!=null?C:[];for(let qe of b.map(W=>W.id))for(let W of g[qe]){let Gt=(U=W.getAttribute("id"))!=null?U:"id"+(S++).toString(10),li=(O=W.getAttribute("mimeType"))!=null?O:"",Fn=(V=W.getAttribute("codecs"))!=null?V:"",qn=(N=W.getAttribute("contentType"))!=null?N:li==null?void 0:li.split("/")[0],xT=(k=(A=W.getAttribute("profiles"))==null?void 0:A.split(","))!=null?k:[],Nc=(Z=zS((j=W.getAttribute("lang"))!=null?j:""))!=null?Z:{},PT=($=(T=(w=W.querySelector("Label"))==null?void 0:w.textContent)==null?void 0:T.trim())!=null?$:void 0,wT=W.querySelectorAll("Representation"),AT=W.querySelector("SegmentTemplate"),kT=(te=(R=W.querySelector("Role"))==null?void 0:R.getAttribute("value"))!=null?te:void 0,Ir=qn,K={id:Gt,language:Nc.language,isDefault:kT==="main",label:PT,codecs:Fn,hdr:Ir==="video"&&Pl(Fn),mime:li,representations:[]};for(let G of wT){let yt=(Me=G.getAttribute("lang"))!=null?Me:void 0,ci=(gt=G.getAttribute("label"))!=null?gt:void 0,Ka=(ne=(F=(Sr=G.querySelector("BaseURL"))==null?void 0:Sr.textContent)==null?void 0:F.trim())!=null?ne:"",Qt=new URL(Ka||o,e).toString(),Tt=(oe=G.getAttribute("mimeType"))!=null?oe:li,Ja=(vt=(Ce=G.getAttribute("codecs"))!=null?Ce:Fn)!=null?vt:"",Xa;if(qn==="text"){let It=G.getAttribute("id")||"",Za=((yr=Nc.privateuse)==null?void 0:yr.includes("x-auto"))||It.includes("_auto"),Wt=G.querySelector("SegmentTemplate");if(Wt){let di={representationId:(St=G.getAttribute("id"))!=null?St:void 0,bandwidth:(jt=G.getAttribute("bandwidth"))!=null?jt:void 0},es=parseInt((Tr=G.getAttribute("bandwidth"))!=null?Tr:"",10)/1e3,ts=(uc=parseInt((ui=Wt.getAttribute("startNumber"))!=null?ui:"",10))!=null?uc:1,Er=parseInt((lc=Wt.getAttribute("timescale"))!=null?lc:"",10),Un=(cc=Wt.querySelectorAll("SegmentTimeline S"))!=null?cc:[],xr=Wt.getAttribute("media");if(!xr)continue;let rs=[],is=0,as="",Pr=0,pi=ts,de=0;for(let Ue of Un){let Yt=parseInt((dc=Ue.getAttribute("d"))!=null?dc:"",10),De=parseInt((pc=Ue.getAttribute("r"))!=null?pc:"",10)||0,Et=parseInt((hc=Ue.getAttribute("t"))!=null?hc:"",10);de=Number.isFinite(Et)?Et:de;let zt=Yt/Er*1e3,xt=de/Er*1e3;for(let Je=0;Je<De+1;Je++){let Pt=ft(xr,{...di,segmentNumber:pi.toString(10),segmentTime:(de+Je*Yt).toString(10)}),wr=(xt!=null?xt:0)+Je*zt,fi=wr+zt;pi++,rs.push({time:{from:wr,to:fi},url:Pt})}de+=(De+1)*Yt,is+=(De+1)*zt}Pr=de/Er*1e3,as=ft(xr,{...di,segmentNumber:pi.toString(10),segmentTime:de.toString(10)});let hi={time:{from:Pr,to:1/0},url:as},st={type:"template",baseUrl:Qt,segmentTemplateUrl:xr,initUrl:"",totalSegmentsDurationMs:is,segments:rs,nextSegmentBeyondManifest:hi,timescale:Er};Xa={id:It,kind:"text",segmentReference:st,profiles:[],duration:d,bitrate:es,mime:"",codecs:"",width:0,height:0,isAuto:Za}}else Xa={id:It,isAuto:Za,kind:"text",url:Qt}}else{let It=(mc=(fc=G.getAttribute("contentType"))!=null?fc:Tt==null?void 0:Tt.split("/")[0])!=null?mc:qn,Za=(gc=(bc=W.getAttribute("profiles"))==null?void 0:bc.split(","))!=null?gc:[],Wt=parseInt((vc=G.getAttribute("width"))!=null?vc:"",10),di=parseInt((Sc=G.getAttribute("height"))!=null?Sc:"",10),es=parseInt((yc=G.getAttribute("bandwidth"))!=null?yc:"",10)/1e3,ts=(Tc=G.getAttribute("frameRate"))!=null?Tc:"",Er=(Ic=G.getAttribute("quality"))!=null?Ic:void 0,Un=ts?YS(ts):void 0,xr=(Ec=G.getAttribute("id"))!=null?Ec:"id"+(S++).toString(10),rs=It==="video"?`${di}p`:It==="audio"?`${es}Kbps`:Ja,is=`${xr}@${rs}`,as=[...y,...xT,...Za],Pr,pi=G.querySelector("SegmentBase"),de=(xc=G.querySelector("SegmentTemplate"))!=null?xc:AT;if(pi){let st=(wc=(Pc=G.querySelector("SegmentBase Initialization"))==null?void 0:Pc.getAttribute("range"))!=null?wc:"",[Ue,Yt]=st.split("-").map(Pt=>parseInt(Pt,10)),De={from:Ue,to:Yt},Et=(Ac=G.querySelector("SegmentBase"))==null?void 0:Ac.getAttribute("indexRange"),[zt,xt]=Et?Et.split("-").map(Pt=>parseInt(Pt,10)):[],Je=Et?{from:zt,to:xt}:void 0;Pr={type:"byteRange",url:Qt,initRange:De,indexRange:Je}}else if(de){let st={representationId:(kc=G.getAttribute("id"))!=null?kc:void 0,bandwidth:(Rc=G.getAttribute("bandwidth"))!=null?Rc:void 0},Ue=parseInt(($c=de.getAttribute("timescale"))!=null?$c:"",10),Yt=(Lc=de.getAttribute("initialization"))!=null?Lc:"",De=de.getAttribute("media"),Et=(Cc=parseInt((Mc=de.getAttribute("startNumber"))!=null?Mc:"",10))!=null?Cc:1,zt=ft(Yt,st);if(!De)throw new ReferenceError("No media attribute in SegmentTemplate");let xt=(Dc=de.querySelectorAll("SegmentTimeline S"))!=null?Dc:[],Je=[],Pt=0,wr="",fi=0;if(xt.length){let ss=Et,He=0;for(let Ar of xt){let Xe=parseInt((Oc=Ar.getAttribute("d"))!=null?Oc:"",10),Kt=parseInt((Bc=Ar.getAttribute("r"))!=null?Bc:"",10)||0,ns=parseInt((Vc=Ar.getAttribute("t"))!=null?Vc:"",10);He=Number.isFinite(ns)?ns:He;let Hn=Xe/Ue*1e3,jn=He/Ue*1e3;for(let os=0;os<Kt+1;os++){let $T=ft(De,{...st,segmentNumber:ss.toString(10),segmentTime:(He+os*Xe).toString(10)}),Fc=(jn!=null?jn:0)+os*Hn,LT=Fc+Hn;ss++,Je.push({time:{from:Fc,to:LT},url:$T})}He+=(Kt+1)*Xe,Pt+=(Kt+1)*Hn}fi=He/Ue*1e3,wr=ft(De,{...st,segmentNumber:ss.toString(10),segmentTime:He.toString(10)})}else if(zM(d)){let He=parseInt((_c=de.getAttribute("duration"))!=null?_c:"",10)/Ue*1e3,Ar=Math.ceil(d/He),Xe=0;for(let Kt=1;Kt<Ar;Kt++){let ns=ft(De,{...st,segmentNumber:Kt.toString(10),segmentTime:Xe.toString(10)});Je.push({time:{from:Xe,to:Xe+He},url:ns}),Xe+=He}fi=Xe,wr=ft(De,{...st,segmentNumber:Ar.toString(10),segmentTime:Xe.toString(10)})}let RT={time:{from:fi,to:1/0},url:wr};Pr={type:"template",baseUrl:Qt,segmentTemplateUrl:De,initUrl:zt,totalSegmentsDurationMs:Pt,segments:Je,nextSegmentBeyondManifest:RT,timescale:Ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!It||!Tt)continue;let hi={video:"video",audio:"audio",text:"text"}[It];if(!hi)continue;Ir||(Ir=hi),Xa={id:is,kind:hi,segmentReference:Pr,profiles:as,duration:d,bitrate:es,mime:Tt,codecs:Ja,width:Wt,height:di,fps:Un,quality:Er}}K.language||(K.language=yt),K.label||(K.label=ci),K.mime||(K.mime=Tt),K.codecs||(K.codecs=Ja),K.hdr||(K.hdr=Ir==="video"&&Pl(Ja)),K.representations.push(Xa)}if(Ir){let G=i[Ir].find(yt=>yt.id===K.id);if(G&&K.representations.every(yt=>he(yt.segmentReference)))for(let yt of G.representations){let ci=K.representations.find(Tt=>Tt.id===yt.id),Ka=ci==null?void 0:ci.segmentReference,Qt=yt.segmentReference;Qt.segments.push(...Ka.segments),Qt.nextSegmentBeyondManifest=Ka.nextSegmentBeyondManifest}else i[Ir].push(K)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var oy=B(We(),1);import{isNonNullable as ny}from"@vkontakte/videoplayer-shared/es2018";var Ee=(a,e)=>ny(a)&&ny(e)&&a.readyState==="open"&&(0,oy.default)([...a.activeSourceBuffers],e);var wa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new pr(0);this.currentLowLatencySegmentLength$=new pr(0);this.currentSegmentLength$=new pr(0);this.onLastSegment$=new pr(!1);this.fullyBuffered$=new pr(!1);this.playingRepresentation$=new pr(void 0);this.playingRepresentationInit$=new pr(void 0);this.error$=new XM;this.gaps=[];this.subscription=new ZM;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new $e;this.switchAbortController=new $e;this.destroyAbortController=new $e;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=dr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Fe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new iS(this.sourceBuffer),this.subscription.add(Dl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:_t.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:_t.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Dl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_t.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Ee(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,gl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=it(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);Fe(r,"No init buffer for starting representation"),Fe(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.switchToOld=dr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Fe(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Fe(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Ee(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();Pa(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=dr(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,mn.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||!he(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);Fe(i);let s=this.segments.get(r);Fe(s,"No segments for starting representation");let n=this.initData.get(r);if(Fe(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}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new $e,dr(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);Fe(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(xe(o)||xe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),Fe(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Ee(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();Pa(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(){!xe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new $e,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||!Ee(this.mediaSource,this.sourceBuffer)||Pa(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Fe(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);Pa(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=it(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)&&gl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=it(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,fn.default)(o,i))l="high";else{let c=(0,ii.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&&it(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ii.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;Pa(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,mn.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,mn.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||!he(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ii.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;Fe(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(!he(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=ft(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let 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&&ea&&ea(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ea&&ea(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&&Ee(this.mediaSource,this.sourceBuffer)&&!(Bt(this.sourceBuffer.buffered,p)&&Bt(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}async loadSegments(e,t,r="auto"){he(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){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&&(await dr(o,async function*(){let c=Ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=hn(),!c)return;let d=new DataView(c),p=Ea(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?await Promise.all(l):await 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]),xa(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())he(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await dr(n,async function*(){let u=Ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Dl(window,"online").pipe(JM()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=hn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),xa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(he(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ii.default)(e,0).byte.from,to:(0,ii.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=hn(),await 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:_t.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!he(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=hn();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:_t.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,fn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Ea(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){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)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,f=d<=i;if(!h)continue;let b=Ea(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var r;if(!(xe(this.sourceBuffer)||!Ee(this.mediaSource,this.sourceBuffer))){!this.isLive&&KM.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Bt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Bt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:_t.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",$l(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=fl(()=>(0,uy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?dr(this.destroyAbortController.signal,async function*(){let o=Ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ea(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&he(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:_t.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!Ee(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||xe(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({...u.time}),i=n(i);let l=$l(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,fn.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?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Ee(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||!Ee(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||!Ee(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||xe(e)?0:it(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Ee(this.mediaSource,this.sourceBuffer)))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||!Ee(this.mediaSource,this.sourceBuffer))){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=fl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:_t.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(xe(this.sourceBuffer)||!Ee(this.mediaSource,this.sourceBuffer)||xe(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 Aa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ly=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 ka,assertNever as dy,fromEvent as py,merge as e0,now as Ra,Subscription as t0,ValueSubject as Bl,flattenObject as ai}from"@vkontakte/videoplayer-shared/es2018";var cy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var bn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Bl(void 0);this.lastConnectionReused$=new Bl(void 0);this.lastRequestFirstBytes$=new Bl(void 0);this.abortAllController=new $e;this.subscription=new t0;this.fetchManifest=ka(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Aa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=cy(r));let i=yield dt(r,{signal:this.abortAllController.signal}).catch($a);return i?(t.log("success",ai({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ai({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ka(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var N,A;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let k=new URL(l,location.href);k.searchParams.append("bytes",`${r.from}-${r.to}`),l=k.toString();break}default:dy(t)}this.requestQuic&&(l=Aa(l));let p=this.abortAllController.signal,h;if(n){let k=new $e;if(h=e0(py(this.abortAllController.signal,"abort"),py(n,"abort")).subscribe(()=>{try{k.abort()}catch(j){$a(j)}}),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(j){$a(j)}p=k.signal}let f=Ra();d.log("startRequest",ai({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield dt(l,{priority:s,headers:c,signal:p}).catch($a),g=Ra();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((N=this.throughputEstimator)==null||N.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let k=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:k}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let k=Ra(),j={requestStartedAt:f,requestEndedAt:k,duration:k-f};return d.log("endRequest",ai(j)),d.end(),b.arrayBuffer()}let[v,S]=b.body.tee(),y=v.getReader();o&&((A=this.throughputEstimator)==null||A.trackStream(S,u));let x=0,I=new Uint8Array(0),M=!1,C=k=>{h==null||h.unsubscribe(),M=!0,$a(k)},U=ka(p,async function*({done:k,value:j}){if(x===0&&this.lastRequestFirstBytes$.next(Ra()-f),p.aborted){h==null||h.unsubscribe();return}if(!k&&j){let Z=new Uint8Array(I.length+j.length);Z.set(I),Z.set(j,I.length),I=Z,x+=j.byteLength,i==null||i(new DataView(I.buffer),x),yield y==null?void 0:y.read().then(U,C)}}.bind(this));yield y==null?void 0:y.read().then(U,C),h==null||h.unsubscribe();let O=Ra(),V={failed:M,requestStartedAt:f,requestEndedAt:O,duration:O-f};return M?(d.error("endRequest",ai(V)),d.end(),null):(d.log("endRequest",ai(V)),d.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=ka(this.abortAllController.signal,async function*(e,t,r){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=ka(this.abortAllController.signal,async function*(e,t){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=>({...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}=ly(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:dy(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},$a=a=>{if(!xa(a))throw a};var hr=(a,e,t)=>t*e+(1-t)*a,Vl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,hy=(a,e,t,r)=>{let i=0,s=t,n=Vl(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 r0,ValueSubject as fy}from"@vkontakte/videoplayer-shared/es2018";var Nt=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 fy(e.initial),this.debounced$=new fy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new pe(`raw_${t}`),this.smoothedSeries$=new pe(`smoothed_${t}`),this.reportedSeries$=new pe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let 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)&&(r0(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 gn=class extends Nt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=hr(this.slow,e,this.params.emaAlphaSlow),this.fast=hr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var vn=class extends Nt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Vl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=hr(this.emaSmoothed,e,this.params.emaAlpha);let r=hy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Sn=class extends Nt{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?hr(this.smoothed,t,this.params.emaAlpha):t}};var fr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new gn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new vn({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 Sn({initial:e,label:"liveEdgeDelay",...t})}};var _l=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as i0,ValueSubject as a0}from"@vkontakte/videoplayer-shared/es2018";var La=class a{constructor(e,t){this.currentRepresentation$=new a0(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(!i0(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,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&&he(t.segmentReference))}};var p0=["timeupdate","progress","play","seeked","stalled","waiting"],h0=["timeupdate","progress","loadeddata","playing","seeked"];var Tn=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 L("none");this.currentVideoRepresentation$=new X(void 0);this.currentVideoRepresentationInit$=new X(void 0);this.currentAudioRepresentation$=new X(void 0);this.currentVideoSegmentLength$=new X(0);this.currentAudioSegmentLength$=new X(0);this.error$=new gy;this.lastConnectionType$=new X(void 0);this.lastConnectionReused$=new X(void 0);this.lastRequestFirstBytes$=new X(void 0);this.currentLiveTextRepresentation$=new X(null);this.isLive$=new X(!1);this.liveDuration$=new X(0);this.liveAvailabilityStartTime$=new X(void 0);this.bufferLength$=new X(0);this.liveLatency$=new X(void 0);this.liveLoadBufferLength$=new X(0);this.livePositionFromPlayer$=new X(0);this.isLowLatency$=new X(!1);this.isActiveLowLatency$=new X(!1);this.currentStallDuration$=new X(0);this.videoLastDataObtainedTimestamp$=new X(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new gy;this.gapWatchdogActive=!1;this.destroyController=new $e;this.initManifest=Nl(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ce(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:Ft.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Nl(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ft.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=sy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Jv(e))!=null?n:{id:"ManifestParsing",category:Ft.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=pt())==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=Rv(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);o0.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",Ca(s)),s}.bind(this));this.initRepresentations=Nl(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",Ca({initialVideo:e,initialAudio:t,sourceHls:r})),mr(this.manifest),mr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(br(p,"error").pipe(Ma(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ft.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?pv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&tn())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 wa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],by(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new wa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}La.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new La(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(Fl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=Hs(this.manifestUrlString,2);this.manifestUrlString=ce(this.manifestUrlString,f+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(gr(...h0.map(p=>br(this.element,p))).pipe(Da(p=>this.element?it(this.element.buffered,this.element.currentTime*1e3):0),yn(),c0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(gr(br(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(yn()).subscribe(h=>_l(this.element,1))),this.representationSubscription.add(si({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Ma(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(si({isActiveLowLatency:this.isActiveLowLatency$.pipe(yn()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Ma(({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(si({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ma(({isLive:h})=>h),Da(h=>({...h})),yn((h,f)=>f.bufferLength<h.bufferLength),Da(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=Hs(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(si({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,y=1;Math.abs(S)>g&&(y=1+Math.sign(S)*v),_l(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,I;return(I=(x=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:x.to)!=null?I:v}))-v}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(si({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(d0(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(mr(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=Hs(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,I=isFinite(h)?h:f,M=this.isActiveLowLatency$.getValue(),C=v<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(M&&C);let U="none";if(M?U="active_low_latency":this.isLowLatency$.getValue()&&C?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(O=>O.proceedLowLatencyLive()),U="active_low_latency"):g!==0&&I<S?U="live_forward_buffering":I<S+x&&(U="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),U==="live_forward_buffering"||U==="live_with_target_offset"){let O=p-(S+y),V=this.normolizeLiveOffset(Math.trunc(g+O/b)),N=Math.abs(V-g),A;!h||N<=this.tuning.dashCmafLive.offsetCalculationError?A=g:V>0&&N>this.tuning.dashCmafLive.offsetCalculationError?A=V:A=0,this.manifestUrlString=ce(this.manifestUrlString,A,2)}U!=="none"&&U!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=gr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Da(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=gr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Da(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(gr(this.forceEnded$,si({allBuffersFull:l,someBufferEnded:c}).pipe(Ma(({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:Ft.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(gr(...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,ql.default)((0,ql.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),he(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&by(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=Fl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Ft.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 bn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=fr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;mr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ce(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){mr(this.element),this.state$.setState("running"),this.subscription.add(gr(...p0.map(e=>br(this.element,e)),br(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ft.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(br(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(br(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Bt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,v,S,y,x,I,M;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=l0(),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 C=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(C),(M=this.audioBufferManager)==null||M.maintain(C),i.position=C}this.tracer.log("stallIntervalCallback",Ca(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Fl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Ft.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}async seek(e,t){var i,s,n,o,u;mr(this.element),mr(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),Bt(this.element.buffered,r)||await 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",Ca({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=u0(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(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={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ca(t)))}}};var In=class{constructor(e,t){this.fov=e,this.orientation=t}};var En=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let 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={...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*(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 Sy=`attribute vec2 a_vertex;
70
71
  attribute vec2 a_texel;
71
72
 
72
73
  varying vec2 v_texel;
@@ -77,7 +78,7 @@ void main(void) {
77
78
  // save texel vector to pass to fragment shader
78
79
  v_texel = a_texel;
79
80
  }
80
- `;var py=`#ifdef GL_ES
81
+ `;var yy=`#ifdef GL_ES
81
82
  precision highp float;
82
83
  precision highp int;
83
84
  #else
@@ -120,5 +121,5 @@ void main(void) {
120
121
  // sample using new coordinates
121
122
  gl_FragColor = texture2D(u_texture, tc);
122
123
  }
123
- `;var vn=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 gn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(dy,this.gl.VERTEX_SHADER),r=this.createShader(py,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,h=t+i;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as lC,now as hy,Subscription as cC,filter as dC,combine as fy,ValueSubject as my,isNonNullable as pC}from"@vkontakte/videoplayer-shared/es2018";var Vl=class{constructor(){this.isSeeked$=new my(!1);this.isBuffering$=new my(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new cC}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(dC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(fy({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(lC(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=hy(),h=n&&this.currentStallsCount>=n,p=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(h||p||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,pC(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}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=hy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},by=Vl;import{combine as hC,map as fC,observeElementSize as mC,Subscription as bC,ValueSubject as Bl,noop as gC}from"@vkontakte/videoplayer-shared/es2018";var Sn=class{constructor(){this.subscription=new bC;this.pipSize$=new Bl(void 0);this.videoSize$=new Bl(void 0);this.elementSize$=new Bl(void 0);this.pictureInPictureWindowRemoveEventListener=gC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(mC(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(hC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(fC(({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 pr=class{constructor(e){this.subscription=new PC;this.videoState=new L("stopped");this.textTracksManager=new Oe;this.droppedFramesManager=new js;this.stallsManager=new by;this.elementSizeManager=new Sn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Oi;this.audioTrackSwitchHistory=new Oi;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.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}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 yC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new vn(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.params=e,this.video=be(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(ie(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=Se(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:_l.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(gy(c=>!!c.length),Sy()).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(Nl(c=>c.to.state!=="none"),ka());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ka()),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(gy(vy),Sy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Nl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ze(this.video,t.isLooped,i)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Be(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(TC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(xl(f));let b=[];for(let g of f.representations){let v=JS(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(Pl(p));let f=[];for(let b of p.representations){let g=KS({...b,streamId:p.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}this.params.output.availableVideoStreams$.next(h);for(let p of d.text)for(let f of p.representations){let b=XS(p,f);this.textTracksMap.set(b,{stream:p,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:_l.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(yn(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$,EC(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,yy.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,f]=h,b=[...this.videoTracksMap.keys()].find(v=>{var S;return((S=this.videoTracksMap.get(v))==null?void 0:S.representation.id)===p.id});vy(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(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.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(ka()).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[h,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Pl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ka()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(xl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.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(Nl(({to:c})=>c==="ready"),ka());this.subscription.add(yn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(yn(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=yn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xC(["init"])).pipe(IC(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var R,C,G,$,B,_,k,w,H,J,A,T,O;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(R=e.videoTrack.getState())==null?void 0:R.id,n=[...this.videoTracksMap.keys()].find(({id:M})=>M===i),o=t.currentVideoTrack$.getValue(),u=(($=(G=e.videoStream.getState())!=null?G:n&&((C=this.videoTracksMap.get(n))==null?void 0:C.stream))!=null?$:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:M})=>M===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=tt(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(B=e.audioStream.getState())!=null?B:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(_=[...this.audioStreamsMap.keys()].find(({id:M})=>M===(f==null?void 0:f.id)))!=null?_:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let M=Fs(n,c,(k=this.audioStreamsMap.get(b))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(w=M==null?void 0:M.bitrate)!=null?w:-1/0)}if(o){let M=Fs(o,c,(H=this.audioStreamsMap.get(b))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(J=M==null?void 0:M.bitrate)!=null?J:-1/0)}}let v=Mt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:p,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}),S=r?v!=null?v:n:n!=null?n:v,y=b&&Ig(S,c,(A=this.audioStreamsMap.get(b))!=null?A:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(T=this.videoTracksMap.get(S))==null?void 0:T.representation,I=y&&((O=this.audioTracksMap.get(y))==null?void 0:O.representation);if(E&&I)return[E,I];if(E&&!I&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(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:_l.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),ge(this.video),this.tracer.end()}};var Ra=class extends pr{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 Ty,interval as AC,map as Iy}from"@vkontakte/videoplayer-shared/es2018";var $a=class extends pr{constructor(e){super(e),this.liveOffset=new ot,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(Iy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Ty({interval:AC(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(Ty({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Iy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=ZS(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 xy=V(Os(),1);import{assertNever as La,assertNonNullable as Ey,debounce as wC,ErrorCategory as Tn,filter as kC,isNonNullable as RC,isNullable as $C,map as In,merge as LC,Observable as MC,observableFrom as CC,Subscription as DC,videoSizeToQuality as OC}from"@vkontakte/videoplayer-shared/es2018";var We={};var Zr=(a,e)=>new MC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ma=class{constructor(e){this.subscription=new DC;this.videoState=new L("initializing");this.textTracksManager=new Oe;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:La(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:La(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:La(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:La(e)}break;default:La(t)}};this.video=be(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(ie(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),ge(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Tn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,xy.default)(import("hls.js").then(i=>{e||(We.Hls=i.default,We.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Ey(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Ey(We.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Tn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Se(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(Ze(this.video,e.isLooped,r)),this.subscription.add(ve(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(De(this.video,e.playbackRate,i.playbackRateState$,r)),s(Be(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(In(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Zr(this.hls,We.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Tn.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(Zr(this.hls,We.Events.MANIFEST_PARSED).pipe(In(({levels:l})=>l.reduce((c,d)=>{var S,y;let h=d.name||d.height.toString(10),{width:p,height:f}=d,b=(y=$t((S=d.attrs.QUALITY)!=null?S:""))!=null?y:OC({width:p,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(Zr(this.hls,We.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",f=d.lang;c.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Zr(this.hls,We.Events.LEVEL_LOADING).pipe(In(({url:l})=>ie(l))),t.hostname$),s(Zr(this.hls,We.Events.FRAG_CHANGED),l=>{var h,p,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(wt(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=Zr(this.hls,We.Events.LEVEL_SWITCHED).pipe(In(({level:l})=>n(this.hls.levels[l])));o.pipe(kC(RC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(wt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if($C(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),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=LC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,CC(["init"])).pipe(wC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tn.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 Py="X-Playback-Duration",Fl=async a=>{var i;let e=await lt(a),t=await 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(Py)?parseInt(e.headers.get(Py),10):void 0};import{assertNever as qC,combine as UC,debounce as HC,ErrorCategory as xn,filter as jC,filterChanged as GC,isNonNullable as wy,isNullable as Pn,map as ky,merge as QC,observableFrom as WC,Subscription as YC,ValueSubject as Hl,VideoQuality as zC}from"@vkontakte/videoplayer-shared/es2018";var Ul=V(Wo(),1);import{videoSizeToQuality as VC,getExponentialDelay as BC}from"@vkontakte/videoplayer-shared/es2018";var _C=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=VC({width:t,height:r})}return e!=null?e:null},NC=(a,e)=>{var s,n;let t=a.split(`
124
- `),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,Ul.default)(l[1].split(",").map(S=>S.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=_C(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(E=>parseInt(E,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:v,bandwidth:f,size:g,fps:b})}if(c){let d=(0,Ul.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,f=d.NAME;h&&p&&i.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},FC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),ql=0,Ay=async(a,e=a,t)=>{let i=await(await lt(a)).text();ql+=1;try{let{qualityManifests:s,textTracks:n}=NC(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(ql<=t.manifestRetryMaxCount)return await FC(BC(ql-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ay(a,e,t)}return{qualityManifests:[],textTracks:[]}},En=Ay;var Ca=class{constructor(e){this.subscription=new YC;this.videoState=new L("stopped");this.textTracksManager=new Oe;this.manifests$=new Hl([]);this.liveOffset=new ot;this.manifestStartTime$=new Hl(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-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 qC(t)}};var t;this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:zC.INVARIANT,url:this.params.source.url},En(ce(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:xn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:xn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Hl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),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(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:xn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Se(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(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),s(Be(this.video),e.elementVisible$),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.subscription.add(this.maxSeekBackTime$.pipe(GC(),ky(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&&wy(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(ie(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},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(UC({startTime:this.manifestStartTime$.pipe(jC(wy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(ky(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=QC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,WC(["init"])).pipe(HC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Pn(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:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&i.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ce(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Fl(n).then(l=>{var c;if(!Pn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Pn(d)||!isFinite(d))try{lt(n).then(h=>h.text()).then(h=>{var f;let p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(p){let b=new URL(p,n).toString();Fl(b).then(g=>{Pn(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){ye(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:xn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as KC,debounce as JC,ErrorCategory as jl,fromEvent as Gl,isNonNullable as XC,isNullable as ZC,map as Ry,merge as $y,observableFrom as Ly,Subscription as e0,ValueSubject as t0,VideoQuality as r0,clientChecker as i0}from"@vkontakte/videoplayer-shared/es2018";var Da=class{constructor(e){this.subscription=new e0;this.videoState=new L("stopped");this.textTracksManager=new Oe;this.manifests$=new t0([]);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 KC(t)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r0.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(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),En(ce(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:jl.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(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:jl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Se(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(Ry(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ze(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(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 p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&XC(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(ie(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let 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(Ry(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!i0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add($y(Gl(o,"addtrack"),Gl(o,"removetrack"),Gl(o,"change"),Ly(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=$y(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ly(["init"])).pipe(JC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var s,n;let e=this.selectManifest();if(ZC(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(){ye(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:jl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Oy=V(Lr(),1),Oa=V(Li(),1);import{assertNever as a0,assertNonNullable as My,debounce as s0,ErrorCategory as Cy,isHigher as n0,isHigherOrEqual as o0,isInvariantQuality as Dy,isLowerOrEqual as u0,isNonNullable as l0,merge as c0,observableFrom as d0,Subscription as p0,map as h0}from"@vkontakte/videoplayer-shared/es2018";var Va=class{constructor(e){this.subscription=new p0;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Oe;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"),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.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"?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 a0(e)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Oy.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,Oa.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:Cy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Se(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(Ze(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),s(Be(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&&l0(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=c0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,d0(["init"])).pipe(s0(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),ge(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;My(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];My(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Sa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ie(t))}playIfAllowed(){ye(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:Cy.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,Oa.default)(this.trackUrls).find(d=>!Dy(d.track.quality)&&u0(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,Oa.default)(this.trackUrls).filter(p=>!Dy(p.track.quality)&&n0(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Oa.default)(this.trackUrls).map(l=>l.track);t=Mt(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 By,debounce as g0,merge as _y,observableFrom as v0,Subscription as S0,map as Ny,ValueSubject as y0,ErrorCategory as Wl,VideoQuality as T0}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as f0}from"@vkontakte/videoplayer-shared/es2018";var Vy=["stun:videostun.mycdn.me:80"],m0=1e3,b0=3,Ql=()=>null,An=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=Ql;this.externalStopCallback=Ql;this.externalErrorCallback=Ql;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Vy}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:f0.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),m0)}normalizeOptions(e={}){let t={stunServerList:Vy,maxRetryNumber:b0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ba=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new y0(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 By(e)}};this.subscription=new S0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=be(e.container,e.tuning),this.liveStreamClient=new An(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),ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Wl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};_y(this.videoState.stateChangeStarted$.pipe(Ny(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ny(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Se(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(Be(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(ve(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 By(n.to)}},r)).add(_y(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,v0(["init"])).pipe(g0(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(ie(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:T0.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:Wl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(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:Wl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var _a=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 Fa,assertNonNullable as _t,ErrorCategory as wn,filter as Gy,isNonNullable as Qy,isNullable as R0,map as $0,merge as L0,once as M0,Subject as Ee,Subscription as Wy,ValueSubject as D,flattenObject as Yy}from"@vkontakte/videoplayer-shared/es2018";import{Observable as I0,map as Fy,Subscription as E0,Subject as x0}from"@vkontakte/videoplayer-shared/es2018";var qy=a=>new I0(e=>{let t=new E0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(Fy(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(Fy(({type:l})=>l!==void 0)),n=new x0,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 P0,Subscription as A0,combine as w0,filter as Hy,once as jy}from"@vkontakte/videoplayer-shared/es2018";function Uy(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as k0}from"@vkontakte/videoplayer-shared/es2018";var Na=class Na{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ke;this.subscriptions=new A0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Hy(s=>!!s.type),jy()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){k0.isSafari&&e!=="MPEG"||this.subscriptions.add(w0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Hy(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),jy()).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}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=Uy();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await 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:Na.errorId,category:P0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Na.errorId} exception`,thrown:e})}};Na.errorId="VolumeMultiplierManager";var ei=Na;var C0={chunkDuration:5e3,maxParallelRequests:5},qa=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;this.providerOutput={position$:new D(0),duration$:new D(1/0),volume$:new D({muted:!1,volume:1}),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableVideoTracks$:new D([]),currentVideoTrack$:new D(void 0),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0),isAudioAvailable$:new D(!0),autoVideoTrackLimitingAvailable$:new D(!1),autoVideoTrackLimits$:new D(void 0),currentBuffer$:new D(void 0),isBuffering$:new D(!0),error$:new Ee,warning$:new Ee,willSeekEvent$:new Ee,soundProhibitedEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new D(void 0),isLowLatency$:new D(!1),canChangePlaybackSpeed$:new D(!0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),inPiP$:new D(!1),inFullscreen$:new D(!1),element$:new D(void 0),elementVisible$:new D(!0),availableSources$:new D(void 0),is3DVideo$:new D(!1),playbackState$:new D("")};this.subscription=new Wy;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=Sv([...Tv(this.params.tuning),...yv(this.params.tuning)],this.params.tuning).filter(l=>Qy(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Yl.default)(i,l)),...t.filter(l=>(0,Yl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Yy(s)),this.screenFormatsIterator=new _a(s);let n=[...il(!0),...il(!1)];this.chromecastFormatsIterator=new _a(n.filter(l=>Qy(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ei.isSupported()&&(this.volumeMultiplierManager=new ei(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(R0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:wn.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 Fa(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 _t(o),new Ra({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return _t(o),new $a({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return _t(o),Wr||!this.params.tuning.useHlsJs?new Da({...n,source:o}):new Ma({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return _t(o),new Ca({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return _t(o),new Va({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return _t(o),new Bg({...n,source:o,config:{...C0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return _t(o),new Ba({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 Fa(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 _t(o),new $i({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 Fa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Fa(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 Fa(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{...e,url:r(e.url)}}return(0,Ky.default)((0,zy.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new Wy,t=!1,r=0;return e.add(L0(this.providerOutput.error$.pipe(Gy(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),qy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe($0(i=>({id:`ProviderHangup:${i}`,category:wn.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(Gy(({to:s})=>s==="playing"),M0()).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===wn.NETWORK,u=i.category===wn.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={...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",Yy(n))})),e}};import{fromEvent as kn,once as D0,combine as O0,Subscription as Jy,ValueSubject as zl,map as V0,filter as B0,isNonNullable as Rn,now as $e,safeStorage as Kl}from"@vkontakte/videoplayer-shared/es2018";var _0=5e3,Xy="one_video_throughput",Zy="one_video_rtt",ht=window.navigator.connection,eT=()=>{let a=ht==null?void 0:ht.downlink;if(Rn(a)&&a!==10)return a*1e3},tT=()=>{let a=ht==null?void 0:ht.rtt;if(Rn(a)&&a!==3e3)return a},rT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Jl=class a{constructor(e){this.subscription=new Jy;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(Xy)||(e.useBrowserEstimation?eT():void 0)||_0,r=(s=(i=a.load(Zy))!=null?i:e.useBrowserEstimation?tT():void 0)!=null?s:0;if(this.throughput$=new zl(t),this.rtt$=new zl(r),this.rttAdjustedThroughput$=new zl(rT(t,r,e.rttPenaltyRequestSize)),this.throughput=ur.getSmoothedValue(t,-1,e),this.rtt=ur.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=eT();u&&this.throughput.next(u);let l=tT();Rn(l)&&this.rtt.next(l)};ht&&"onchange"in ht&&this.subscription.add(kn(ht,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Kl.set(Xy,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Kl.set(Zy,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(O0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(V0(({throughput:n,rtt:o})=>rT(n,o,e.rttPenaltyRequestSize)),B0(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 Jy;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(kn(e,"progress").pipe(D0()).subscribe(s=>{t=s.loaded,r=$e()}));break;case 1:case 0:i.add(kn(e,"loadstart").subscribe(()=>{t=0,r=$e()}));break}i.add(kn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=$e(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=$e(),n=0,o=$e(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({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 f=o-s;f&&this.addRawSpeed(n,f,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());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,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=Kl.get(e);if(Rn(t))return(r=parseInt(t,10))!=null?r:void 0}},iT=Jl;import{fillWithDefault as N0,VideoQuality as aT}from"@vkontakte/videoplayer-shared/es2018";var sT={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:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:aT.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:aT.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:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,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,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,exposeInternalsToGlobal:!1},nT=a=>{var e;return{...N0(a,sT),configName:[...(e=a.configName)!=null?e:[],...sT.configName]}};import{assertNonNullable as $n,combine as ft,ErrorCategory as Ln,filter as fe,filterChanged as q,fromEvent as Zl,isNonNullable as Q0,isNullable as W0,Logger as Y0,map as N,mapTo as cT,merge as Nt,now as Mn,once as rt,Subject as j,Subscription as dT,tap as pT,ValueSubject as P,isHigher as z0,isInvariantQuality as hT,flattenObject as Ft,throttle as ec,getTraceSubscriptionMethod as fT,Tracer as K0,InternalsExposure as J0}from"@vkontakte/videoplayer-shared/es2018";import{merge as F0,map as q0,filter as oT,isNonNullable as U0}from"@vkontakte/videoplayer-shared/es2018";var Xl=({seekState:a,position$:e})=>F0(a.stateChangeEnded$.pipe(q0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),oT(U0)),e.pipe(oT(()=>a.getState().state==="none")));import{assertNonNullable as H0}from"@vkontakte/videoplayer-shared/es2018";var uT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return H0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as j0,once as G0}from"@vkontakte/videoplayer-shared/es2018";var lT=(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(j0(i=>i.length>0),G0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Cn=class{constructor(e={configName:[]},t=K0.createRootTracer(!1)){this.subscription=new dT;this.logger=new Y0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),isLowLatency:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,autoplaySoundProhibited$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:pg};if(this.initLogs(),this.tuning=nT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new os({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new iT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new J0("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(h=>JSON.stringify(h,(p,f)=>{let b=typeof f;return(0,mT.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:Ln.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Ft(r)),this.domContainer=uT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new qa({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],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(),(o=this.internalsExposure)==null||o.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&&!Fi()?(this.tracer.log("request play from hidden tab"),Zl(document,"visibilitychange").pipe(rt()).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-.1),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){$n(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(fe(r=>r.length>0),rt()).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",Ft(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;$n(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",Ft(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return lT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),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(W0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return Q0(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(Nt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(fe(({from:e})=>e==="stopped"),rt()).subscribe(()=>{this.initedAt=Mn(),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",Ft(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ln.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(rt()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Ft(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(N(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(N(n=>n.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ft({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(N(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>hT(u)?1:hT(l)?-1:z0(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(N(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(ft({hasLiveOffsetByPaused:Nt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(n=>n.to),q(),N(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(ft({atLiveEdge:ft({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Xl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(N(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),q(),pT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(N(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ft({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(N(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),pT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(N(n=>n.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(N(n=>n.volume),q()).subscribe(this.info.volume$)).add(Xl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Nt(e.providerOutput.endedEvent$.pipe(cT(!0)),e.providerOutput.seekedEvent$.pipe(cT(!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(N(n=>({id:n?`No${n}`:"NoProviders",category:Ln.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(rt(),N(n=>n!=null?n:Mn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(rt(),N(()=>Mn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(rt(),N(()=>Mn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(fe(({to:n})=>n==="playing"),rt()).subscribe(()=>r.next(!1)));let i=0,s=Nt(e.providerOutput.isBuffering$,t,r).pipe(N(()=>{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(Nt(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(Nt(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(N(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new dT;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(fe(r=>r.length>0),rt()).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=Mt(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(Nt(this.desiredState.videoTrack.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(N(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;$n(this.providerContainer),$n(e),dg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>cg(r)),this.providerContainer.current$.subscribe(({type:r})=>Di("provider",r)),e.duration$.subscribe(r=>Di("duration",r)),e.availableVideoTracks$.pipe(fe(r=>!!r.length),rt()).subscribe(r=>Di("tracks",r)),this.events.fatalError$.subscribe(new pe("fatalError")),this.events.managedError$.subscribe(new pe("managedError")),e.position$.subscribe(new pe("position")),e.currentVideoTrack$.pipe(N(r=>r==null?void 0:r.quality)).subscribe(new pe("quality")),this.info.currentBuffer$.subscribe(new pe("buffer")),e.isBuffering$.subscribe(new pe("isBuffering"))].forEach(r=>this.subscription.add(r)),Di("codecs",vv())}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(ft({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(fe(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(fe(r=>r>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(fe(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(ft({currentBuffer:this.info.currentBuffer$.pipe(fe(r=>r.end>0),q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(q())}).pipe(ec(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(ft({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(fe(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),ec(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),fe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),fe(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(),fe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ft({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(fe(({throughputEstimation:r,rtt:i})=>!!r&&!!i),ec(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),fe(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=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ln.DOM,message:String(i)})})};this.subscription.add(Nt(Zl(document,"visibilitychange"),Zl(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",Ft({quality:t,availableTracks:Ft(e),track:Ft(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 hz,Observable as fz,Subject as mz,ValueSubject as bz,VideoQuality as gz}from"@vkontakte/videoplayer-shared/es2018";var vz=`@vkontakte/videoplayer-core@${Oc}`;export{ts as ChromecastState,Nn as HttpConnectionType,fz as Observable,me as PlaybackState,Cn as Player,vz as SDK_VERSION,mz as Subject,hz as Subscription,Fn as Surface,Oc as VERSION,bz as ValueSubject,Et as VideoFormat,gz as VideoQuality};
124
+ `;var xn=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 In(this.params.fov,this.params.orientation),this.cameraRotationManager=new En(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(Sy,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 b0,now as Ty,Subscription as g0,filter as v0,combine as Iy,ValueSubject as Ey,isNonNullable as S0}from"@vkontakte/videoplayer-shared/es2018";var Ul=class{constructor(){this.isSeeked$=new Ey(!1);this.isBuffering$=new Ey(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new g0}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(Iy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(v0(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Iy({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(b0(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=Ty(),p=n&&this.currentStallsCount>=n,h=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||h||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,S0(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}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=Ty(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},xy=Ul;import{combine as y0,map as T0,observeElementSize as I0,Subscription as E0,ValueSubject as Hl,noop as x0}from"@vkontakte/videoplayer-shared/es2018";var Pn=class{constructor(){this.subscription=new E0;this.pipSize$=new Hl(void 0);this.videoSize$=new Hl(void 0);this.elementSize$=new Hl(void 0);this.pictureInPictureWindowRemoveEventListener=x0}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(I0(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(y0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(T0(({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 vr=class{constructor(e){this.subscription=new L0;this.videoState=new L("stopped");this.textTracksManager=new Be;this.droppedFramesManager=new Js;this.stallsManager=new xy;this.elementSizeManager=new Pn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ui;this.audioTrackSwitchHistory=new Ui;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"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(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"&&E(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"&&E(this.params.desiredState.playbackState,"paused");return;default:return A0(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new xn(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.params=e,this.video=be(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(ae(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 Tn({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=Se(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:jl.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(Py(c=>!!c.length),Ay()).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(Gl(c=>c.to.state!=="none"),Ba());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ba()),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(Py(wy),Ay()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Gl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Oe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(_e(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(k0(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(kl(f));let b=[];for(let g of f.representations){let v=JS(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(Rl(h));let f=[];for(let b of h.representations){let g=KS({...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=XS(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:jl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(wn(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$,$0(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,ky.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});wy(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(Ba()).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(Rl(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ba()).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(kl(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(Gl(({to:c})=>c==="ready"),Ba());this.subscription.add(wn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ql(["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(wn(u,this.player.state$.stateChangeEnded$,Ql(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=wn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ql(["init"])).pipe(R0(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var M,C,U,O,V,N,A,k,j,Z,w,T,$;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(M=e.videoTrack.getState())==null?void 0:M.id,n=[...this.videoTracksMap.keys()].find(({id:R})=>R===i),o=t.currentVideoTrack$.getValue(),u=((O=(U=e.videoStream.getState())!=null?U:n&&((C=this.videoTracksMap.get(n))==null?void 0:C.stream))!=null?O:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=it(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(V=e.audioStream.getState())!=null?V:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(N=[...this.audioStreamsMap.keys()].find(({id:R})=>R===(f==null?void 0:f.id)))!=null?N:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let R=Ws(n,c,(A=this.audioStreamsMap.get(b))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(k=R==null?void 0:R.bitrate)!=null?k:-1/0)}if(o){let R=Ws(o,c,(j=this.audioStreamsMap.get(b))!=null?j:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(Z=R==null?void 0:R.bitrate)!=null?Z:-1/0)}}let v=Ot(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,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}),S=r?v!=null?v:n:n!=null?n:v,y=b&&Rg(S,c,(w=this.audioStreamsMap.get(b))!=null?w:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),x=(T=this.videoTracksMap.get(S))==null?void 0:T.representation,I=y&&(($=this.audioTracksMap.get(y))==null?void 0:$.representation);if(x&&I)return[x,I];if(x&&!I&&this.audioTracksMap.size===0)return[x,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jl.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),ge(this.video),this.tracer.end()}};var Va=class extends vr{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 Ry,interval as M0,map as $y}from"@vkontakte/videoplayer-shared/es2018";var _a=class extends vr{constructor(e){super(e),this.liveOffset=new lt,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($y(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Ry({interval:M0(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(Ry({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe($y(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=ZS(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 My=B(Us(),1);import{assertNever as Na,assertNonNullable as Ly,debounce as C0,ErrorCategory as An,filter as D0,isNonNullable as O0,isNullable as B0,map as kn,merge as V0,Observable as _0,observableFrom as N0,Subscription as F0,videoSizeToQuality as q0}from"@vkontakte/videoplayer-shared/es2018";var Ke={};var ni=(a,e)=>new _0(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Fa=class{constructor(e){this.subscription=new F0;this.videoState=new L("initializing");this.textTracksManager=new Be;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:Na(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Na(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Na(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Na(e)}break;default:Na(t)}};this.video=be(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(ae(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),ge(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:An.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,My.default)(import("hls.js").then(i=>{e||(Ke.Hls=i.default,Ke.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Ly(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Ly(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:An.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Se(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(tt(this.video,e.isLooped,r)),this.subscription.add(ve(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Oe(this.video,e.playbackRate,i.playbackRateState$,r)),s(_e(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(kn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ni(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:An.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"),E(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(ni(this.hls,Ke.Events.MANIFEST_PARSED).pipe(kn(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(y=Ct((S=d.attrs.QUALITY)!=null?S:""))!=null?y:q0({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(ni(this.hls,Ke.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(ni(this.hls,Ke.Events.LEVEL_LOADING).pipe(kn(({url:l})=>ae(l))),t.hostname$),s(ni(this.hls,Ke.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($t(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=ni(this.hls,Ke.Events.LEVEL_SWITCHED).pipe(kn(({level:l})=>n(this.hls.levels[l])));o.pipe(D0(O0)).subscribe(t.currentVideoTrack$,r),this.subscription.add($t(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(B0(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=V0(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,N0(["init"])).pipe(C0(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:An.DOM,thrown:t}))||(this.videoState.setState("paused"),E(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"),E(this.params.desiredState.playbackState,"stopped",!0)}};var Cy="X-Playback-Duration",Wl=async a=>{var i;let e=await dt(a),t=await 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(Cy)?parseInt(e.headers.get(Cy),10):void 0};import{assertNever as W0,combine as Y0,debounce as z0,ErrorCategory as $n,filter as K0,filterChanged as J0,isNonNullable as Oy,isNullable as Ln,map as By,merge as X0,observableFrom as Z0,Subscription as eC,ValueSubject as Kl,VideoQuality as tC}from"@vkontakte/videoplayer-shared/es2018";var zl=B(Zo(),1);import{videoSizeToQuality as U0,getExponentialDelay as H0}from"@vkontakte/videoplayer-shared/es2018";var j0=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=U0({width:t,height:r})}return e!=null?e:null},G0=(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,zl.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=j0(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,zl.default)(c[1].split(",").map(b=>b.split("=")).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}},Q0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Yl=0,Dy=async(a,e=a,t)=>{let i=await(await dt(a)).text();Yl+=1;try{let{qualityManifests:s,textTracks:n}=G0(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(Yl<=t.manifestRetryMaxCount)return await Q0(H0(Yl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Dy(a,e,t)}return{qualityManifests:[],textTracks:[]}},Rn=Dy;var qa=class{constructor(e){this.subscription=new eC;this.videoState=new L("stopped");this.textTracksManager=new Be;this.manifests$=new Kl([]);this.liveOffset=new lt;this.manifestStartTime$=new Kl(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"),E(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-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(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"&&E(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"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return W0(t)}};var t;this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:tC.INVARIANT,url:this.params.source.url},Rn(ce(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:$n.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:$n.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ae(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Kl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),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:$n.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Se(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(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,r)),s(_e(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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.subscription.add(this.maxSeekBackTime$.pipe(J0(),By(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&&Oy(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(ae(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(Y0({startTime:this.manifestStartTime$.pipe(K0(Oy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(By(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=X0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Z0(["init"])).pipe(z0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Ln(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:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ce(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Wl(n).then(l=>{var c;if(!Ln(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Ln(d)||!isFinite(d))try{dt(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();Wl(b).then(g=>{Ln(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$n.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as rC,debounce as iC,ErrorCategory as Jl,fromEvent as Xl,isNonNullable as aC,isNullable as sC,map as Vy,merge as _y,observableFrom as Ny,Subscription as nC,ValueSubject as oC,VideoQuality as uC,clientChecker as lC}from"@vkontakte/videoplayer-shared/es2018";var Ua=class{constructor(e){this.subscription=new nC;this.videoState=new L("stopped");this.textTracksManager=new Be;this.manifests$=new oC([]);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"),E(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"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return rC(t)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:uC.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(ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Rn(ce(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:Jl.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:Jl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Se(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(Vy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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&&aC(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(ae(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(Vy(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)),!lC.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(_y(Xl(o,"addtrack"),Xl(o,"removetrack"),Xl(o,"change"),Ny(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=_y(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ny(["init"])).pipe(iC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var s,n;let e=this.selectManifest();if(sC(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(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Jl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Hy=B(Vr(),1),Ha=B(Yr(),1);import{assertNever as cC,assertNonNullable as Fy,debounce as dC,ErrorCategory as qy,isHigher as pC,isHigherOrEqual as hC,isInvariantQuality as Uy,isLowerOrEqual as fC,isNonNullable as mC,merge as bC,observableFrom as gC,Subscription as vC,map as SC}from"@vkontakte/videoplayer-shared/es2018";var ja=class{constructor(e){this.subscription=new vC;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Be;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"),E(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"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return cC(e)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Hy.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,Ha.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:qy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Se(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(SC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,r)),s(_e(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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&&mC(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=bC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,gC(["init"])).pipe(dC(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),ge(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Fy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Fy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Aa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ae(t))}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:qy.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,Ha.default)(this.trackUrls).find(d=>!Uy(d.track.quality)&&fC(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&&hC(c.quality,u.quality)&&(t=u),!t){let d=(0,Ha.default)(this.trackUrls).filter(h=>!Uy(h.track.quality)&&pC(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Ha.default)(this.trackUrls).map(l=>l.track);t=Ot(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 Gy,debounce as EC,merge as Qy,observableFrom as xC,Subscription as PC,map as Wy,ValueSubject as wC,ErrorCategory as ec,VideoQuality as AC}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as yC}from"@vkontakte/videoplayer-shared/es2018";var jy=["stun:videostun.mycdn.me:80"],TC=1e3,IC=3,Zl=()=>null,Mn=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=Zl;this.externalStopCallback=Zl;this.externalErrorCallback=Zl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:jy}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:yC.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),TC)}normalizeOptions(e={}){let t={stunServerList:jy,maxRetryNumber:IC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ga=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new wC(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"),E(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"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return Gy(e)}};this.subscription=new PC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=be(e.container,e.tuning),this.liveStreamClient=new Mn(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),ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ec.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Qy(this.videoState.stateChangeStarted$.pipe(Wy(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Wy(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Se(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(_e(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(ve(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 Gy(n.to)}},r)).add(Qy(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,xC(["init"])).pipe(EC(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(ae(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:AC.INVARIANT}),this.video.srcObject=e,E(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:ec.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ec.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ya,assertNonNullable as qt,ErrorCategory as Cn,filter as Zy,isNonNullable as eT,isNullable as OC,map as BC,merge as VC,once as _C,Subject as Pe,Subscription as tT,ValueSubject as D,flattenObject as rT}from"@vkontakte/videoplayer-shared/es2018";import{Observable as kC,map as Yy,Subscription as RC,Subject as $C}from"@vkontakte/videoplayer-shared/es2018";var zy=a=>new kC(e=>{let t=new RC,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(Yy(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(Yy(({type:l})=>l!==void 0)),n=new $C,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 LC,Subscription as MC,combine as CC,filter as Jy,once as Xy}from"@vkontakte/videoplayer-shared/es2018";function Ky(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as DC}from"@vkontakte/videoplayer-shared/es2018";var Wa=class Wa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new $e;this.subscriptions=new MC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Jy(s=>!!s.type),Xy()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){DC.isSafari&&e!=="MPEG"||this.subscriptions.add(CC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Jy(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),Xy()).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}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=Ky();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await 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:Wa.errorId,category:LC.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Wa.errorId} exception`,thrown:e})}};Wa.errorId="VolumeMultiplierManager";var oi=Wa;var NC={chunkDuration:5e3,maxParallelRequests:5},za=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new Pe;this.noAvailableProvidersError$=new Pe;this.volumeMultiplierError$=new Pe;this.providerOutput={position$:new D(0),duration$:new D(1/0),volume$:new D({muted:!1,volume:1}),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableVideoTracks$:new D([]),currentVideoTrack$:new D(void 0),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0),isAudioAvailable$:new D(!0),autoVideoTrackLimitingAvailable$:new D(!1),autoVideoTrackLimits$:new D(void 0),currentBuffer$:new D(void 0),isBuffering$:new D(!0),error$:new Pe,warning$:new Pe,willSeekEvent$:new Pe,soundProhibitedEvent$:new Pe,seekedEvent$:new Pe,loopedEvent$:new Pe,endedEvent$:new Pe,firstBytesEvent$:new Pe,loadedMetadataEvent$:new Pe,firstFrameEvent$:new Pe,canplay$:new Pe,isLive$:new D(void 0),isLowLatency$:new D(!1),canChangePlaybackSpeed$:new D(!0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),inPiP$:new D(!1),inFullscreen$:new D(!1),element$:new D(void 0),elementVisible$:new D(!0),availableSources$:new D(void 0),is3DVideo$:new D(!1),playbackState$:new D("")};this.subscription=new tT;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=wv([...kv(this.params.tuning),...Av(this.params.tuning)],this.params.tuning).filter(l=>eT(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 Qa(s);let n=[...ll(!0),...ll(!1)];this.chromecastFormatsIterator=new Qa(n.filter(l=>eT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&oi.isSupported()&&(this.volumeMultiplierManager=new oi(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(OC(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Cn.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 Ya(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qt(o),new Va({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return qt(o),new _a({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return qt(o),ei||!this.params.tuning.useHlsJs?new Ua({...n,source:o}):new Fa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return qt(o),new qa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return qt(o),new ja({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return qt(o),new jg({...n,source:o,config:{...NC,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return qt(o),new Ga({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 Ya(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return qt(o),new _i({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 Ya(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ya(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 Ya(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{...e,url:r(e.url)}}return(0,aT.default)((0,iT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new tT,t=!1,r=0;return e.add(VC(this.providerOutput.error$.pipe(Zy(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),zy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(BC(i=>({id:`ProviderHangup:${i}`,category:Cn.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(Zy(({to:s})=>s==="playing"),_C()).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===Cn.NETWORK,u=i.category===Cn.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={...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 Dn,once as FC,combine as qC,Subscription as sT,ValueSubject as rc,map as UC,filter as HC,isNonNullable as On,now as Le,safeStorage as ic}from"@vkontakte/videoplayer-shared/es2018";var jC=5e3,nT="one_video_throughput",oT="one_video_rtt",mt=window.navigator.connection,uT=()=>{let a=mt==null?void 0:mt.downlink;if(On(a)&&a!==10)return a*1e3},lT=()=>{let a=mt==null?void 0:mt.rtt;if(On(a)&&a!==3e3)return a},cT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},ac=class a{constructor(e){this.subscription=new sT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(nT)||(e.useBrowserEstimation?uT():void 0)||jC,r=(s=(i=a.load(oT))!=null?i:e.useBrowserEstimation?lT():void 0)!=null?s:0;if(this.throughput$=new rc(t),this.rtt$=new rc(r),this.rttAdjustedThroughput$=new rc(cT(t,r,e.rttPenaltyRequestSize)),this.throughput=fr.getSmoothedValue(t,-1,e),this.rtt=fr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=uT();u&&this.throughput.next(u);let l=lT();On(l)&&this.rtt.next(l)};mt&&"onchange"in mt&&this.subscription.add(Dn(mt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ic.set(nT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ic.set(oT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(qC({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(UC(({throughput:n,rtt:o})=>cT(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=Le(),i=new sT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Dn(e,"progress").pipe(FC()).subscribe(s=>{t=s.loaded,r=Le()}));break;case 1:case 0:i.add(Dn(e,"loadstart").subscribe(()=>{t=0,r=Le()}));break}i.add(Dn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Le(),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=Le(),n=0,o=Le(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,Le()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Le();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=Le()}else n+=d.byteLength;o=Le()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Le()-o,this.concurrentDownloads.size),n=0,o=Le());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,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=ic.get(e);if(On(t))return(r=parseInt(t,10))!=null?r:void 0}},dT=ac;import{fillWithDefault as GC,VideoQuality as pT}from"@vkontakte/videoplayer-shared/es2018";var hT={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:pT.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:pT.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:{stallDurationBeforeQualityDecrease:0,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,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,exposeInternalsToGlobal:!1},fT=a=>{var e;return{...GC(a,hT),configName:[...(e=a.configName)!=null?e:[],...hT.configName]}};import{assertNonNullable as Bn,combine as bt,ErrorCategory as Vn,filter as fe,filterChanged as q,fromEvent as nc,isNonNullable as XC,isNullable as ZC,Logger as eD,map as _,mapTo as vT,merge as Ut,now as _n,once as at,Subject as Q,Subscription as ST,tap as yT,ValueSubject as P,isHigher as tD,isInvariantQuality as TT,flattenObject as Ht,throttle as oc,getTraceSubscriptionMethod as IT,Tracer as rD,InternalsExposure as iD}from"@vkontakte/videoplayer-shared/es2018";import{merge as QC,map as WC,filter as mT,isNonNullable as YC}from"@vkontakte/videoplayer-shared/es2018";var sc=({seekState:a,position$:e})=>QC(a.stateChangeEnded$.pipe(WC(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),mT(YC)),e.pipe(mT(()=>a.getState().state==="none")));import{assertNonNullable as zC}from"@vkontakte/videoplayer-shared/es2018";var bT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return zC(e,`Wrong container or containerId {${a.container}}`),e};import{filter as KC,once as JC}from"@vkontakte/videoplayer-shared/es2018";var gT=(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(KC(i=>i.length>0),JC()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Nn=class{constructor(e={configName:[]},t=rD.createRootTracer(!1)){this.subscription=new ST;this.logger=new eD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),isLowLatency:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Sg};if(this.initLogs(),this.tuning=fT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new fs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new dT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new iD("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,ET.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:Vn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Ht(r)),this.domContainer=bT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new za({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],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(),(o=this.internalsExposure)==null||o.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&&!Wi()?(this.tracer.log("request play from hidden tab"),nc(document,"visibilitychange").pipe(at()).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-.1),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){Bn(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(fe(r=>r.length>0),at()).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",Ht(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Bn(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",Ht(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return gT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),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(ZC(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return XC(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(Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(fe(({from:e})=>e==="stopped"),at()).subscribe(()=>{this.initedAt=_n(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Ht(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Vn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(at()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Ht(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(bt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(_(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>TT(u)?1:TT(l)?-1:tD(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(_(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(bt({hasLiveOffsetByPaused:Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(n=>n.to),q(),_(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(bt({atLiveEdge:bt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),q(),yT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(_(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(bt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(_(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),yT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),q()).subscribe(this.info.volume$)).add(sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ut(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(_(n=>({id:n?`No${n}`:"NoProviders",category:Vn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(at(),_(n=>n!=null?n:_n()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(at(),_(()=>_n()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(at(),_(()=>_n()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(fe(({to:n})=>n==="playing"),at()).subscribe(()=>r.next(!1)));let i=0,s=Ut(e.providerOutput.isBuffering$,t,r).pipe(_(()=>{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(Ut(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ut(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(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 ST;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(fe(r=>r.length>0),at()).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=Ot(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(Ut(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(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;Bn(this.providerContainer),Bn(e),vg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>gg(r)),this.providerContainer.current$.subscribe(({type:r})=>qi("provider",r)),e.duration$.subscribe(r=>qi("duration",r)),e.availableVideoTracks$.pipe(fe(r=>!!r.length),at()).subscribe(r=>qi("tracks",r)),this.events.fatalError$.subscribe(new pe("fatalError")),this.events.managedError$.subscribe(new pe("managedError")),e.position$.subscribe(new pe("position")),e.currentVideoTrack$.pipe(_(r=>r==null?void 0:r.quality)).subscribe(new pe("quality")),this.info.currentBuffer$.subscribe(new pe("buffer")),e.isBuffering$.subscribe(new pe("isBuffering"))].forEach(r=>this.subscription.add(r)),qi("codecs",Pv())}initTracerSubscription(){let e=IT(this.tracer.log.bind(this.tracer)),t=IT(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(bt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(fe(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(fe(r=>r>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(fe(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(bt({currentBuffer:this.info.currentBuffer$.pipe(fe(r=>r.end>0),q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(q())}).pipe(oc(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(bt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(fe(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),oc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),fe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),fe(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(),fe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(bt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(fe(({throughputEstimation:r,rtt:i})=>!!r&&!!i),oc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),fe(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=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Vn.DOM,message:String(i)})})};this.subscription.add(Ut(nc(document,"visibilitychange"),nc(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",Ht({quality:t,availableTracks:Ht(e),track:Ht(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 wz,Observable as Az,Subject as kz,ValueSubject as Rz,VideoQuality as $z}from"@vkontakte/videoplayer-shared/es2018";var Lz=`@vkontakte/videoplayer-core@${Uc}`;export{us as ChromecastState,Gn as HttpConnectionType,Az as Observable,me as PlaybackState,Nn as Player,Lz as SDK_VERSION,kz as Subject,wz as Subscription,Qn as Surface,Uc as VERSION,Rz as ValueSubject,wt as VideoFormat,$z as VideoQuality};