@vkontakte/videoplayer-core 2.0.123-dev.499ebc9f.0 → 2.0.123-dev.8ba72ee5.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,51 +1,51 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.123-dev.499ebc9f.0
3
- * Tue, 17 Dec 2024 07:44:34 GMT
2
+ * @vkontakte/videoplayer-core v2.0.123-dev.8ba72ee5.0
3
+ * Wed, 18 Dec 2024 15:16:11 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-123/doc/
5
5
  */
6
- var RT=Object.create;var Bc=Object.defineProperty;var $T=Object.getOwnPropertyDescriptor;var LT=Object.getOwnPropertyNames;var MT=Object.getPrototypeOf,CT=Object.prototype.hasOwnProperty;var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var DT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of LT(e))!CT.call(a,i)&&i!==t&&Bc(a,i,{get:()=>e[i],enumerable:!(r=$T(e,i))||r.enumerable});return a};var C=(a,e,t)=>(t=a!=null?RT(MT(a)):{},DT(e||!a||!a.__esModule?Bc(t,"default",{value:a,enumerable:!0}):t,a));var z=f((jn,Nc)=>{"use strict";var ui=function(a){return a&&a.Math===Math&&a};Nc.exports=ui(typeof globalThis=="object"&&globalThis)||ui(typeof window=="object"&&window)||ui(typeof self=="object"&&self)||ui(typeof global=="object"&&global)||ui(typeof jn=="object"&&jn)||function(){return this}()||Function("return this")()});var ne=f((aD,Fc)=>{"use strict";Fc.exports=function(a){try{return!!a()}catch(e){return!0}}});var li=f((sD,qc)=>{"use strict";var OT=ne();qc.exports=!OT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Qn=f((nD,Qc)=>{"use strict";var VT=li(),jc=Function.prototype,Uc=jc.apply,Hc=jc.call;Qc.exports=typeof Reflect=="object"&&Reflect.apply||(VT?Hc.bind(Uc):function(){return Hc.apply(Uc,arguments)})});var te=f((oD,Yc)=>{"use strict";var Gc=li(),Wc=Function.prototype,Gn=Wc.call,BT=Gc&&Wc.bind.bind(Gn,Gn);Yc.exports=Gc?BT:function(a){return function(){return Gn.apply(a,arguments)}}});var Gt=f((uD,Kc)=>{"use strict";var zc=te(),_T=zc({}.toString),NT=zc("".slice);Kc.exports=function(a){return NT(_T(a),8,-1)}});var Wn=f((lD,Jc)=>{"use strict";var FT=Gt(),qT=te();Jc.exports=function(a){if(FT(a)==="Function")return qT(a)}});var Y=f((cD,Xc)=>{"use strict";var Yn=typeof document=="object"&&document.all;Xc.exports=typeof Yn=="undefined"&&Yn!==void 0?function(a){return typeof a=="function"||a===Yn}:function(a){return typeof a=="function"}});var xe=f((dD,Zc)=>{"use strict";var UT=ne();Zc.exports=!UT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Pe=f((pD,ed)=>{"use strict";var HT=li(),is=Function.prototype.call;ed.exports=HT?is.bind(is):function(){return is.apply(is,arguments)}});var zn=f(id=>{"use strict";var td={}.propertyIsEnumerable,rd=Object.getOwnPropertyDescriptor,jT=rd&&!td.call({1:2},1);id.f=jT?function(e){var t=rd(this,e);return!!t&&t.enumerable}:td});var ci=f((mD,ad)=>{"use strict";ad.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var nd=f((fD,sd)=>{"use strict";var QT=te(),GT=ne(),WT=Gt(),Kn=Object,YT=QT("".split);sd.exports=GT(function(){return!Kn("z").propertyIsEnumerable(0)})?function(a){return WT(a)==="String"?YT(a,""):Kn(a)}:Kn});var Tr=f((bD,od)=>{"use strict";od.exports=function(a){return a==null}});var Et=f((gD,ud)=>{"use strict";var zT=Tr(),KT=TypeError;ud.exports=function(a){if(zT(a))throw new KT("Can't call method on "+a);return a}});var Wt=f((vD,ld)=>{"use strict";var JT=nd(),XT=Et();ld.exports=function(a){return JT(XT(a))}});var Ae=f((SD,cd)=>{"use strict";var ZT=Y();cd.exports=function(a){return typeof a=="object"?a!==null:ZT(a)}});var Ir=f((yD,dd)=>{"use strict";dd.exports={}});var at=f((TD,hd)=>{"use strict";var Jn=Ir(),Xn=z(),eI=Y(),pd=function(a){return eI(a)?a:void 0};hd.exports=function(a,e){return arguments.length<2?pd(Jn[a])||pd(Xn[a]):Jn[a]&&Jn[a][e]||Xn[a]&&Xn[a][e]}});var di=f((ID,md)=>{"use strict";var tI=te();md.exports=tI({}.isPrototypeOf)});var Yt=f((ED,gd)=>{"use strict";var rI=z(),fd=rI.navigator,bd=fd&&fd.userAgent;gd.exports=bd?String(bd):""});var eo=f((xD,Ed)=>{"use strict";var Id=z(),Zn=Yt(),vd=Id.process,Sd=Id.Deno,yd=vd&&vd.versions||Sd&&Sd.version,Td=yd&&yd.v8,qe,as;Td&&(qe=Td.split("."),as=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!as&&Zn&&(qe=Zn.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=Zn.match(/Chrome\/(\d+)/),qe&&(as=+qe[1])));Ed.exports=as});var to=f((PD,Pd)=>{"use strict";var xd=eo(),iI=ne(),aI=z(),sI=aI.String;Pd.exports=!!Object.getOwnPropertySymbols&&!iI(function(){var a=Symbol("symbol detection");return!sI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&xd&&xd<41})});var ro=f((AD,Ad)=>{"use strict";var nI=to();Ad.exports=nI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var io=f((wD,wd)=>{"use strict";var oI=at(),uI=Y(),lI=di(),cI=ro(),dI=Object;wd.exports=cI?function(a){return typeof a=="symbol"}:function(a){var e=oI("Symbol");return uI(e)&&lI(e.prototype,dI(a))}});var pi=f((kD,kd)=>{"use strict";var pI=String;kd.exports=function(a){try{return pI(a)}catch(e){return"Object"}}});var Ke=f((RD,Rd)=>{"use strict";var hI=Y(),mI=pi(),fI=TypeError;Rd.exports=function(a){if(hI(a))return a;throw new fI(mI(a)+" is not a function")}});var hi=f(($D,$d)=>{"use strict";var bI=Ke(),gI=Tr();$d.exports=function(a,e){var t=a[e];return gI(t)?void 0:bI(t)}});var Md=f((LD,Ld)=>{"use strict";var ao=Pe(),so=Y(),no=Ae(),vI=TypeError;Ld.exports=function(a,e){var t,r;if(e==="string"&&so(t=a.toString)&&!no(r=ao(t,a))||so(t=a.valueOf)&&!no(r=ao(t,a))||e!=="string"&&so(t=a.toString)&&!no(r=ao(t,a)))return r;throw new vI("Can't convert object to primitive value")}});var Ue=f((MD,Cd)=>{"use strict";Cd.exports=!0});var Vd=f((CD,Od)=>{"use strict";var Dd=z(),SI=Object.defineProperty;Od.exports=function(a,e){try{SI(Dd,a,{value:e,configurable:!0,writable:!0})}catch(t){Dd[a]=e}return e}});var mi=f((DD,Nd)=>{"use strict";var yI=Ue(),TI=z(),II=Vd(),Bd="__core-js_shared__",_d=Nd.exports=TI[Bd]||II(Bd,{});(_d.versions||(_d.versions=[])).push({version:"3.38.0",mode:yI?"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 oo=f((OD,qd)=>{"use strict";var Fd=mi();qd.exports=function(a,e){return Fd[a]||(Fd[a]=e||{})}});var Er=f((VD,Ud)=>{"use strict";var EI=Et(),xI=Object;Ud.exports=function(a){return xI(EI(a))}});var He=f((BD,Hd)=>{"use strict";var PI=te(),AI=Er(),wI=PI({}.hasOwnProperty);Hd.exports=Object.hasOwn||function(e,t){return wI(AI(e),t)}});var uo=f((_D,jd)=>{"use strict";var kI=te(),RI=0,$I=Math.random(),LI=kI(1 .toString);jd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+LI(++RI+$I,36)}});var oe=f((ND,Gd)=>{"use strict";var MI=z(),CI=oo(),Qd=He(),DI=uo(),OI=to(),VI=ro(),xr=MI.Symbol,lo=CI("wks"),BI=VI?xr.for||xr:xr&&xr.withoutSetter||DI;Gd.exports=function(a){return Qd(lo,a)||(lo[a]=OI&&Qd(xr,a)?xr[a]:BI("Symbol."+a)),lo[a]}});var Kd=f((FD,zd)=>{"use strict";var _I=Pe(),Wd=Ae(),Yd=io(),NI=hi(),FI=Md(),qI=oe(),UI=TypeError,HI=qI("toPrimitive");zd.exports=function(a,e){if(!Wd(a)||Yd(a))return a;var t=NI(a,HI),r;if(t){if(e===void 0&&(e="default"),r=_I(t,a,e),!Wd(r)||Yd(r))return r;throw new UI("Can't convert object to primitive value")}return e===void 0&&(e="number"),FI(a,e)}});var co=f((qD,Jd)=>{"use strict";var jI=Kd(),QI=io();Jd.exports=function(a){var e=jI(a,"string");return QI(e)?e:e+""}});var ss=f((UD,Zd)=>{"use strict";var GI=z(),Xd=Ae(),po=GI.document,WI=Xd(po)&&Xd(po.createElement);Zd.exports=function(a){return WI?po.createElement(a):{}}});var ho=f((HD,ep)=>{"use strict";var YI=xe(),zI=ne(),KI=ss();ep.exports=!YI&&!zI(function(){return Object.defineProperty(KI("div"),"a",{get:function(){return 7}}).a!==7})});var ip=f(rp=>{"use strict";var JI=xe(),XI=Pe(),ZI=zn(),eE=ci(),tE=Wt(),rE=co(),iE=He(),aE=ho(),tp=Object.getOwnPropertyDescriptor;rp.f=JI?tp:function(e,t){if(e=tE(e),t=rE(t),aE)try{return tp(e,t)}catch(r){}if(iE(e,t))return eE(!XI(ZI.f,e,t),e[t])}});var mo=f((QD,ap)=>{"use strict";var sE=ne(),nE=Y(),oE=/#|\.prototype\./,fi=function(a,e){var t=lE[uE(a)];return t===dE?!0:t===cE?!1:nE(e)?sE(e):!!e},uE=fi.normalize=function(a){return String(a).replace(oE,".").toLowerCase()},lE=fi.data={},cE=fi.NATIVE="N",dE=fi.POLYFILL="P";ap.exports=fi});var Pr=f((GD,np)=>{"use strict";var sp=Wn(),pE=Ke(),hE=li(),mE=sp(sp.bind);np.exports=function(a,e){return pE(a),e===void 0?a:hE?mE(a,e):function(){return a.apply(e,arguments)}}});var fo=f((WD,op)=>{"use strict";var fE=xe(),bE=ne();op.exports=fE&&bE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Je=f((YD,up)=>{"use strict";var gE=Ae(),vE=String,SE=TypeError;up.exports=function(a){if(gE(a))return a;throw new SE(vE(a)+" is not an object")}});var zt=f(cp=>{"use strict";var yE=xe(),TE=ho(),IE=fo(),ns=Je(),lp=co(),EE=TypeError,bo=Object.defineProperty,xE=Object.getOwnPropertyDescriptor,go="enumerable",vo="configurable",So="writable";cp.f=yE?IE?function(e,t,r){if(ns(e),t=lp(t),ns(r),typeof e=="function"&&t==="prototype"&&"value"in r&&So in r&&!r[So]){var i=xE(e,t);i&&i[So]&&(e[t]=r.value,r={configurable:vo in r?r[vo]:i[vo],enumerable:go in r?r[go]:i[go],writable:!1})}return bo(e,t,r)}:bo:function(e,t,r){if(ns(e),t=lp(t),ns(r),TE)try{return bo(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new EE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Ar=f((KD,dp)=>{"use strict";var PE=xe(),AE=zt(),wE=ci();dp.exports=PE?function(a,e,t){return AE.f(a,e,wE(1,t))}:function(a,e,t){return a[e]=t,a}});var X=f((JD,hp)=>{"use strict";var bi=z(),kE=Qn(),RE=Wn(),$E=Y(),LE=ip().f,ME=mo(),wr=Ir(),CE=Pr(),kr=Ar(),pp=He();mi();var DE=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return kE(a,this,arguments)};return e.prototype=a.prototype,e};hp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?bi:i?bi[t]:bi[t]&&bi[t].prototype,o=r?wr:wr[t]||kr(wr,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,v;for(h in e)l=ME(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&pp(n,h),m=o[h],c&&(a.dontCallGetSet?(v=LE(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?g=CE(p,bi):a.wrap&&c?g=DE(p):s&&$E(p)?g=RE(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&kr(g,"sham",!0),kr(o,h,g),s&&(d=t+"Prototype",pp(wr,d)||kr(wr,d,{}),kr(wr[d],h,p),a.real&&u&&(l||!u[h])&&kr(u,h,p)))}});var fp=f((XD,mp)=>{"use strict";var OE=Math.ceil,VE=Math.floor;mp.exports=Math.trunc||function(e){var t=+e;return(t>0?VE:OE)(t)}});var gi=f((ZD,bp)=>{"use strict";var BE=fp();bp.exports=function(a){var e=+a;return e!==e||e===0?0:BE(e)}});var vp=f((eO,gp)=>{"use strict";var _E=gi(),NE=Math.max,FE=Math.min;gp.exports=function(a,e){var t=_E(a);return t<0?NE(t+e,0):FE(t,e)}});var yo=f((tO,Sp)=>{"use strict";var qE=gi(),UE=Math.min;Sp.exports=function(a){var e=qE(a);return e>0?UE(e,9007199254740991):0}});var Rr=f((rO,yp)=>{"use strict";var HE=yo();yp.exports=function(a){return HE(a.length)}});var To=f((iO,Ip)=>{"use strict";var jE=Wt(),QE=vp(),GE=Rr(),Tp=function(a){return function(e,t,r){var i=jE(e),s=GE(i);if(s===0)return!a&&-1;var n=QE(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}};Ip.exports={includes:Tp(!0),indexOf:Tp(!1)}});var vi=f((aO,Ep)=>{"use strict";Ep.exports=function(){}});var xp=f(()=>{"use strict";var WE=X(),YE=To().includes,zE=ne(),KE=vi(),JE=zE(function(){return!Array(1).includes()});WE({target:"Array",proto:!0,forced:JE},{includes:function(e){return YE(this,e,arguments.length>1?arguments[1]:void 0)}});KE("includes")});var xt=f((oO,Pp)=>{"use strict";var XE=at();Pp.exports=XE});var wp=f((uO,Ap)=>{"use strict";xp();var ZE=xt();Ap.exports=ZE("Array","includes")});var Rp=f((lO,kp)=>{"use strict";var ex=wp();kp.exports=ex});var Xe=f((cO,$p)=>{"use strict";var tx=Rp();$p.exports=tx});var ls=f((IO,_p)=>{"use strict";var lx=oo(),cx=uo(),Bp=lx("keys");_p.exports=function(a){return Bp[a]||(Bp[a]=cx(a))}});var Fp=f((EO,Np)=>{"use strict";var dx=ne();Np.exports=!dx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var cs=f((xO,Up)=>{"use strict";var px=He(),hx=Y(),mx=Er(),fx=ls(),bx=Fp(),qp=fx("IE_PROTO"),xo=Object,gx=xo.prototype;Up.exports=bx?xo.getPrototypeOf:function(a){var e=mx(a);if(px(e,qp))return e[qp];var t=e.constructor;return hx(t)&&e instanceof t?t.prototype:e instanceof xo?gx:null}});var ds=f((PO,Hp)=>{"use strict";Hp.exports={}});var Gp=f((AO,Qp)=>{"use strict";var vx=te(),Po=He(),Sx=Wt(),yx=To().indexOf,Tx=ds(),jp=vx([].push);Qp.exports=function(a,e){var t=Sx(a),r=0,i=[],s;for(s in t)!Po(Tx,s)&&Po(t,s)&&jp(i,s);for(;e.length>r;)Po(t,s=e[r++])&&(~yx(i,s)||jp(i,s));return i}});var Ao=f((wO,Wp)=>{"use strict";Wp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var wo=f((kO,Yp)=>{"use strict";var Ix=Gp(),Ex=Ao();Yp.exports=Object.keys||function(e){return Ix(e,Ex)}});var ko=f((RO,Zp)=>{"use strict";var Kp=xe(),xx=ne(),Jp=te(),Px=cs(),Ax=wo(),wx=Wt(),kx=zn().f,Xp=Jp(kx),Rx=Jp([].push),$x=Kp&&xx(function(){var a=Object.create(null);return a[2]=2,!Xp(a,2)}),zp=function(a){return function(e){for(var t=wx(e),r=Ax(t),i=$x&&Px(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Kp||(i?u in t:Xp(t,u)))&&Rx(o,a?[u,t[u]]:t[u]);return o}};Zp.exports={entries:zp(!0),values:zp(!1)}});var eh=f(()=>{"use strict";var Lx=X(),Mx=ko().entries;Lx({target:"Object",stat:!0},{entries:function(e){return Mx(e)}})});var rh=f((MO,th)=>{"use strict";eh();var Cx=Ir();th.exports=Cx.Object.entries});var ah=f((CO,ih)=>{"use strict";var Dx=rh();ih.exports=Dx});var $r=f((DO,sh)=>{"use strict";var Ox=ah();sh.exports=Ox});var Kt=f((OO,nh)=>{"use strict";nh.exports={}});var lh=f((VO,uh)=>{"use strict";var Vx=z(),Bx=Y(),oh=Vx.WeakMap;uh.exports=Bx(oh)&&/native code/.test(String(oh))});var Mo=f((BO,ph)=>{"use strict";var _x=lh(),dh=z(),Nx=Ae(),Fx=Ar(),Ro=He(),$o=mi(),qx=ls(),Ux=ds(),ch="Object already initialized",Lo=dh.TypeError,Hx=dh.WeakMap,ps,Si,hs,jx=function(a){return hs(a)?Si(a):ps(a,{})},Qx=function(a){return function(e){var t;if(!Nx(e)||(t=Si(e)).type!==a)throw new Lo("Incompatible receiver, "+a+" required");return t}};_x||$o.state?(je=$o.state||($o.state=new Hx),je.get=je.get,je.has=je.has,je.set=je.set,ps=function(a,e){if(je.has(a))throw new Lo(ch);return e.facade=a,je.set(a,e),e},Si=function(a){return je.get(a)||{}},hs=function(a){return je.has(a)}):(Jt=qx("state"),Ux[Jt]=!0,ps=function(a,e){if(Ro(a,Jt))throw new Lo(ch);return e.facade=a,Fx(a,Jt,e),e},Si=function(a){return Ro(a,Jt)?a[Jt]:{}},hs=function(a){return Ro(a,Jt)});var je,Jt;ph.exports={set:ps,get:Si,has:hs,enforce:jx,getterFor:Qx}});var Oo=f((_O,mh)=>{"use strict";var Co=xe(),Gx=He(),hh=Function.prototype,Wx=Co&&Object.getOwnPropertyDescriptor,Do=Gx(hh,"name"),Yx=Do&&function(){}.name==="something",zx=Do&&(!Co||Co&&Wx(hh,"name").configurable);mh.exports={EXISTS:Do,PROPER:Yx,CONFIGURABLE:zx}});var bh=f(fh=>{"use strict";var Kx=xe(),Jx=fo(),Xx=zt(),Zx=Je(),eP=Wt(),tP=wo();fh.f=Kx&&!Jx?Object.defineProperties:function(e,t){Zx(e);for(var r=eP(t),i=tP(t),s=i.length,n=0,o;s>n;)Xx.f(e,o=i[n++],r[o]);return e}});var Vo=f((FO,gh)=>{"use strict";var rP=at();gh.exports=rP("document","documentElement")});var Fo=f((qO,xh)=>{"use strict";var iP=Je(),aP=bh(),vh=Ao(),sP=ds(),nP=Vo(),oP=ss(),uP=ls(),Sh=">",yh="<",_o="prototype",No="script",Ih=uP("IE_PROTO"),Bo=function(){},Eh=function(a){return yh+No+Sh+a+yh+"/"+No+Sh},Th=function(a){a.write(Eh("")),a.close();var e=a.parentWindow.Object;return a=null,e},lP=function(){var a=oP("iframe"),e="java"+No+":",t;return a.style.display="none",nP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Eh("document.F=Object")),t.close(),t.F},ms,fs=function(){try{ms=new ActiveXObject("htmlfile")}catch(e){}fs=typeof document!="undefined"?document.domain&&ms?Th(ms):lP():Th(ms);for(var a=vh.length;a--;)delete fs[_o][vh[a]];return fs()};sP[Ih]=!0;xh.exports=Object.create||function(e,t){var r;return e!==null?(Bo[_o]=iP(e),r=new Bo,Bo[_o]=null,r[Ih]=e):r=fs(),t===void 0?r:aP.f(r,t)}});var Lr=f((UO,Ph)=>{"use strict";var cP=Ar();Ph.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:cP(a,e,t),a}});var jo=f((HO,kh)=>{"use strict";var dP=ne(),pP=Y(),hP=Ae(),mP=Fo(),Ah=cs(),fP=Lr(),bP=oe(),gP=Ue(),Ho=bP("iterator"),wh=!1,st,qo,Uo;[].keys&&(Uo=[].keys(),"next"in Uo?(qo=Ah(Ah(Uo)),qo!==Object.prototype&&(st=qo)):wh=!0);var vP=!hP(st)||dP(function(){var a={};return st[Ho].call(a)!==a});vP?st={}:gP&&(st=mP(st));pP(st[Ho])||fP(st,Ho,function(){return this});kh.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:wh}});var bs=f((jO,$h)=>{"use strict";var SP=oe(),yP=SP("toStringTag"),Rh={};Rh[yP]="z";$h.exports=String(Rh)==="[object z]"});var yi=f((QO,Lh)=>{"use strict";var TP=bs(),IP=Y(),gs=Gt(),EP=oe(),xP=EP("toStringTag"),PP=Object,AP=gs(function(){return arguments}())==="Arguments",wP=function(a,e){try{return a[e]}catch(t){}};Lh.exports=TP?gs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=wP(e=PP(a),xP))=="string"?t:AP?gs(e):(r=gs(e))==="Object"&&IP(e.callee)?"Arguments":r}});var Ch=f((GO,Mh)=>{"use strict";var kP=bs(),RP=yi();Mh.exports=kP?{}.toString:function(){return"[object "+RP(this)+"]"}});var Ti=f((WO,Oh)=>{"use strict";var $P=bs(),LP=zt().f,MP=Ar(),CP=He(),DP=Ch(),OP=oe(),Dh=OP("toStringTag");Oh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(CP(i,Dh)||LP(i,Dh,{configurable:!0,value:e}),r&&!$P&&MP(i,"toString",DP))}});var Bh=f((YO,Vh)=>{"use strict";var VP=jo().IteratorPrototype,BP=Fo(),_P=ci(),NP=Ti(),FP=Kt(),qP=function(){return this};Vh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=BP(VP,{next:_P(+!r,t)}),NP(a,i,!1,!0),FP[i]=qP,a}});var Nh=f((zO,_h)=>{"use strict";var UP=te(),HP=Ke();_h.exports=function(a,e,t){try{return UP(HP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var qh=f((KO,Fh)=>{"use strict";var jP=Ae();Fh.exports=function(a){return jP(a)||a===null}});var Hh=f((JO,Uh)=>{"use strict";var QP=qh(),GP=String,WP=TypeError;Uh.exports=function(a){if(QP(a))return a;throw new WP("Can't set "+GP(a)+" as a prototype")}});var Qo=f((XO,jh)=>{"use strict";var YP=Nh(),zP=Ae(),KP=Et(),JP=Hh();jh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=YP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return KP(i),JP(s),zP(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var tm=f((ZO,em)=>{"use strict";var XP=X(),ZP=Pe(),vs=Ue(),Xh=Oo(),eA=Y(),tA=Bh(),Qh=cs(),Gh=Qo(),rA=Ti(),iA=Ar(),Go=Lr(),aA=oe(),Wh=Kt(),Zh=jo(),sA=Xh.PROPER,nA=Xh.CONFIGURABLE,Yh=Zh.IteratorPrototype,Ss=Zh.BUGGY_SAFARI_ITERATORS,Ii=aA("iterator"),zh="keys",Ei="values",Kh="entries",Jh=function(){return this};em.exports=function(a,e,t,r,i,s,n){tA(t,e,r);var o=function(v){if(v===i&&h)return h;if(!Ss&&v&&v in c)return c[v];switch(v){case zh:return function(){return new t(this,v)};case Ei:return function(){return new t(this,v)};case Kh:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Ii]||c["@@iterator"]||i&&c[i],h=!Ss&&d||o(i),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=Qh(p.call(new a)),m!==Object.prototype&&m.next&&(!vs&&Qh(m)!==Yh&&(Gh?Gh(m,Yh):eA(m[Ii])||Go(m,Ii,Jh)),rA(m,u,!0,!0),vs&&(Wh[u]=Jh))),sA&&i===Ei&&d&&d.name!==Ei&&(!vs&&nA?iA(c,"name",Ei):(l=!0,h=function(){return ZP(d,this)})),i)if(b={values:o(Ei),keys:s?h:o(zh),entries:o(Kh)},n)for(g in b)(Ss||l||!(g in c))&&Go(c,g,b[g]);else XP({target:e,proto:!0,forced:Ss||l},b);return(!vs||n)&&c[Ii]!==h&&Go(c,Ii,h,{name:i}),Wh[e]=h,b}});var im=f((eV,rm)=>{"use strict";rm.exports=function(a,e){return{value:a,done:e}}});var Yo=f((tV,um)=>{"use strict";var oA=Wt(),Wo=vi(),am=Kt(),nm=Mo(),uA=zt().f,lA=tm(),ys=im(),cA=Ue(),dA=xe(),om="Array Iterator",pA=nm.set,hA=nm.getterFor(om);um.exports=lA(Array,"Array",function(a,e){pA(this,{type:om,target:oA(a),index:0,kind:e})},function(){var a=hA(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ys(void 0,!0);switch(a.kind){case"keys":return ys(t,!1);case"values":return ys(e[t],!1)}return ys([t,e[t]],!1)},"values");var sm=am.Arguments=am.Array;Wo("keys");Wo("values");Wo("entries");if(!cA&&dA&&sm.name!=="values")try{uA(sm,"name",{value:"values"})}catch(a){}});var cm=f((rV,lm)=>{"use strict";var mA=oe(),fA=Kt(),bA=mA("iterator"),gA=Array.prototype;lm.exports=function(a){return a!==void 0&&(fA.Array===a||gA[bA]===a)}});var zo=f((iV,pm)=>{"use strict";var vA=yi(),dm=hi(),SA=Tr(),yA=Kt(),TA=oe(),IA=TA("iterator");pm.exports=function(a){if(!SA(a))return dm(a,IA)||dm(a,"@@iterator")||yA[vA(a)]}});var mm=f((aV,hm)=>{"use strict";var EA=Pe(),xA=Ke(),PA=Je(),AA=pi(),wA=zo(),kA=TypeError;hm.exports=function(a,e){var t=arguments.length<2?wA(a):e;if(xA(t))return PA(EA(t,a));throw new kA(AA(a)+" is not iterable")}});var gm=f((sV,bm)=>{"use strict";var RA=Pe(),fm=Je(),$A=hi();bm.exports=function(a,e,t){var r,i;fm(a);try{if(r=$A(a,"return"),!r){if(e==="throw")throw t;return t}r=RA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return fm(r),t}});var Is=f((nV,Tm)=>{"use strict";var LA=Pr(),MA=Pe(),CA=Je(),DA=pi(),OA=cm(),VA=Rr(),vm=di(),BA=mm(),_A=zo(),Sm=gm(),NA=TypeError,Ts=function(a,e){this.stopped=a,this.result=e},ym=Ts.prototype;Tm.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=LA(e,r),l,c,d,h,p,m,b,g=function(T){return l&&Sm(l,"normal",T),new Ts(!0,T)},v=function(T){return i?(CA(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)l=a.iterator;else if(n)l=a;else{if(c=_A(a),!c)throw new NA(DA(a)+" is not iterable");if(OA(c)){for(d=0,h=VA(a);h>d;d++)if(p=v(a[d]),p&&vm(ym,p))return p;return new Ts(!1)}l=BA(a,c)}for(m=s?a.next:l.next;!(b=MA(m,l)).done;){try{p=v(b.value)}catch(T){Sm(l,"throw",T)}if(typeof p=="object"&&p&&vm(ym,p))return p}return new Ts(!1)}});var Em=f((oV,Im)=>{"use strict";var FA=xe(),qA=zt(),UA=ci();Im.exports=function(a,e,t){FA?qA.f(a,e,UA(0,t)):a[e]=t}});var xm=f(()=>{"use strict";var HA=X(),jA=Is(),QA=Em();HA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return jA(e,function(r,i){QA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Am=f((cV,Pm)=>{"use strict";Yo();xm();var GA=Ir();Pm.exports=GA.Object.fromEntries});var km=f((dV,wm)=>{"use strict";wm.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 $m=f(()=>{"use strict";Yo();var WA=km(),YA=z(),zA=Ti(),Rm=Kt();for(Es in WA)zA(YA[Es],Es),Rm[Es]=Rm.Array;var Es});var Mm=f((mV,Lm)=>{"use strict";var KA=Am();$m();Lm.exports=KA});var Ko=f((fV,Cm)=>{"use strict";var JA=Mm();Cm.exports=JA});var Dm=f(()=>{"use strict"});var Jo=f((vV,Om)=>{"use strict";var xi=z(),XA=Yt(),ZA=Gt(),xs=function(a){return XA.slice(0,a.length)===a};Om.exports=function(){return xs("Bun/")?"BUN":xs("Cloudflare-Workers")?"CLOUDFLARE":xs("Deno/")?"DENO":xs("Node.js/")?"NODE":xi.Bun&&typeof Bun.version=="string"?"BUN":xi.Deno&&typeof Deno.version=="object"?"DENO":ZA(xi.process)==="process"?"NODE":xi.window&&xi.document?"BROWSER":"REST"}()});var Ps=f((SV,Vm)=>{"use strict";var ew=Jo();Vm.exports=ew==="NODE"});var _m=f((yV,Bm)=>{"use strict";var tw=zt();Bm.exports=function(a,e,t){return tw.f(a,e,t)}});var qm=f((TV,Fm)=>{"use strict";var rw=at(),iw=_m(),aw=oe(),sw=xe(),Nm=aw("species");Fm.exports=function(a){var e=rw(a);sw&&e&&!e[Nm]&&iw(e,Nm,{configurable:!0,get:function(){return this}})}});var Hm=f((IV,Um)=>{"use strict";var nw=di(),ow=TypeError;Um.exports=function(a,e){if(nw(e,a))return a;throw new ow("Incorrect invocation")}});var Zo=f((EV,jm)=>{"use strict";var uw=te(),lw=Y(),Xo=mi(),cw=uw(Function.toString);lw(Xo.inspectSource)||(Xo.inspectSource=function(a){return cw(a)});jm.exports=Xo.inspectSource});var tu=f((xV,zm)=>{"use strict";var dw=te(),pw=ne(),Qm=Y(),hw=yi(),mw=at(),fw=Zo(),Gm=function(){},Wm=mw("Reflect","construct"),eu=/^\s*(?:class|function)\b/,bw=dw(eu.exec),gw=!eu.test(Gm),Pi=function(e){if(!Qm(e))return!1;try{return Wm(Gm,[],e),!0}catch(t){return!1}},Ym=function(e){if(!Qm(e))return!1;switch(hw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return gw||!!bw(eu,fw(e))}catch(t){return!0}};Ym.sham=!0;zm.exports=!Wm||pw(function(){var a;return Pi(Pi.call)||!Pi(Object)||!Pi(function(){a=!0})||a})?Ym:Pi});var Jm=f((PV,Km)=>{"use strict";var vw=tu(),Sw=pi(),yw=TypeError;Km.exports=function(a){if(vw(a))return a;throw new yw(Sw(a)+" is not a constructor")}});var ru=f((AV,Zm)=>{"use strict";var Xm=Je(),Tw=Jm(),Iw=Tr(),Ew=oe(),xw=Ew("species");Zm.exports=function(a,e){var t=Xm(a).constructor,r;return t===void 0||Iw(r=Xm(t)[xw])?e:Tw(r)}});var tf=f((wV,ef)=>{"use strict";var Pw=te();ef.exports=Pw([].slice)});var af=f((kV,rf)=>{"use strict";var Aw=TypeError;rf.exports=function(a,e){if(a<e)throw new Aw("Not enough arguments");return a}});var iu=f((RV,sf)=>{"use strict";var ww=Yt();sf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ww)});var pu=f(($V,mf)=>{"use strict";var we=z(),kw=Qn(),Rw=Pr(),nf=Y(),$w=He(),hf=ne(),of=Vo(),Lw=tf(),uf=ss(),Mw=af(),Cw=iu(),Dw=Ps(),lu=we.setImmediate,cu=we.clearImmediate,Ow=we.process,au=we.Dispatch,Vw=we.Function,lf=we.MessageChannel,Bw=we.String,su=0,Ai={},cf="onreadystatechange",wi,Xt,nu,ou;hf(function(){wi=we.location});var du=function(a){if($w(Ai,a)){var e=Ai[a];delete Ai[a],e()}},uu=function(a){return function(){du(a)}},df=function(a){du(a.data)},pf=function(a){we.postMessage(Bw(a),wi.protocol+"//"+wi.host)};(!lu||!cu)&&(lu=function(e){Mw(arguments.length,1);var t=nf(e)?e:Vw(e),r=Lw(arguments,1);return Ai[++su]=function(){kw(t,void 0,r)},Xt(su),su},cu=function(e){delete Ai[e]},Dw?Xt=function(a){Ow.nextTick(uu(a))}:au&&au.now?Xt=function(a){au.now(uu(a))}:lf&&!Cw?(nu=new lf,ou=nu.port2,nu.port1.onmessage=df,Xt=Rw(ou.postMessage,ou)):we.addEventListener&&nf(we.postMessage)&&!we.importScripts&&wi&&wi.protocol!=="file:"&&!hf(pf)?(Xt=pf,we.addEventListener("message",df,!1)):cf in uf("script")?Xt=function(a){of.appendChild(uf("script"))[cf]=function(){of.removeChild(this),du(a)}}:Xt=function(a){setTimeout(uu(a),0)});mf.exports={set:lu,clear:cu}});var gf=f((LV,bf)=>{"use strict";var ff=z(),_w=xe(),Nw=Object.getOwnPropertyDescriptor;bf.exports=function(a){if(!_w)return ff[a];var e=Nw(ff,a);return e&&e.value}});var hu=f((MV,Sf)=>{"use strict";var vf=function(){this.head=null,this.tail=null};vf.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}}};Sf.exports=vf});var Tf=f((CV,yf)=>{"use strict";var Fw=Yt();yf.exports=/ipad|iphone|ipod/i.test(Fw)&&typeof Pebble!="undefined"});var Ef=f((DV,If)=>{"use strict";var qw=Yt();If.exports=/web0s(?!.*chrome)/i.test(qw)});var $f=f((OV,Rf)=>{"use strict";var Cr=z(),Uw=gf(),xf=Pr(),mu=pu().set,Hw=hu(),jw=iu(),Qw=Tf(),Gw=Ef(),fu=Ps(),Pf=Cr.MutationObserver||Cr.WebKitMutationObserver,Af=Cr.document,wf=Cr.process,As=Cr.Promise,vu=Uw("queueMicrotask"),Mr,bu,gu,ws,kf;vu||(ki=new Hw,Ri=function(){var a,e;for(fu&&(a=wf.domain)&&a.exit();e=ki.get();)try{e()}catch(t){throw ki.head&&Mr(),t}a&&a.enter()},!jw&&!fu&&!Gw&&Pf&&Af?(bu=!0,gu=Af.createTextNode(""),new Pf(Ri).observe(gu,{characterData:!0}),Mr=function(){gu.data=bu=!bu}):!Qw&&As&&As.resolve?(ws=As.resolve(void 0),ws.constructor=As,kf=xf(ws.then,ws),Mr=function(){kf(Ri)}):fu?Mr=function(){wf.nextTick(Ri)}:(mu=xf(mu,Cr),Mr=function(){mu(Ri)}),vu=function(a){ki.head||Mr(),ki.add(a)});var ki,Ri;Rf.exports=vu});var Mf=f((VV,Lf)=>{"use strict";Lf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ks=f((BV,Cf)=>{"use strict";Cf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Zt=f((_V,Df)=>{"use strict";var Ww=z();Df.exports=Ww.Promise});var Dr=f((NV,_f)=>{"use strict";var Yw=z(),$i=Zt(),zw=Y(),Kw=mo(),Jw=Zo(),Xw=oe(),Of=Jo(),Zw=Ue(),Su=eo(),Vf=$i&&$i.prototype,ek=Xw("species"),yu=!1,Bf=zw(Yw.PromiseRejectionEvent),tk=Kw("Promise",function(){var a=Jw($i),e=a!==String($i);if(!e&&Su===66||Zw&&!(Vf.catch&&Vf.finally))return!0;if(!Su||Su<51||!/native code/.test(a)){var t=new $i(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[ek]=r,yu=t.then(function(){})instanceof r,!yu)return!0}return!e&&(Of==="BROWSER"||Of==="DENO")&&!Bf});_f.exports={CONSTRUCTOR:tk,REJECTION_EVENT:Bf,SUBCLASSING:yu}});var Or=f((FV,Ff)=>{"use strict";var Nf=Ke(),rk=TypeError,ik=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new rk("Bad Promise constructor");e=r,t=i}),this.resolve=Nf(e),this.reject=Nf(t)};Ff.exports.f=function(a){return new ik(a)}});var sb=f(()=>{"use strict";var ak=X(),sk=Ue(),Ms=Ps(),Pt=z(),Nr=Pe(),qf=Lr(),Uf=Qo(),nk=Ti(),ok=qm(),uk=Ke(),Ls=Y(),lk=Ae(),ck=Hm(),dk=ru(),Wf=pu().set,Pu=$f(),pk=Mf(),hk=ks(),mk=hu(),Yf=Mo(),Cs=Zt(),Au=Dr(),zf=Or(),Ds="Promise",Kf=Au.CONSTRUCTOR,fk=Au.REJECTION_EVENT,bk=Au.SUBCLASSING,Tu=Yf.getterFor(Ds),gk=Yf.set,Vr=Cs&&Cs.prototype,er=Cs,Rs=Vr,Jf=Pt.TypeError,Iu=Pt.document,wu=Pt.process,Eu=zf.f,vk=Eu,Sk=!!(Iu&&Iu.createEvent&&Pt.dispatchEvent),Xf="unhandledrejection",yk="rejectionhandled",Hf=0,Zf=1,Tk=2,ku=1,eb=2,$s,jf,Ik,Qf,tb=function(a){var e;return lk(a)&&Ls(e=a.then)?e:!1},rb=function(a,e){var t=e.value,r=e.state===Zf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===eb&&xk(e),e.rejection=ku),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Jf("Promise-chain cycle")):(l=tb(u))?Nr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},ib=function(a,e){a.notified||(a.notified=!0,Pu(function(){for(var t=a.reactions,r;r=t.get();)rb(r,a);a.notified=!1,e&&!a.rejection&&Ek(a)}))},ab=function(a,e,t){var r,i;Sk?(r=Iu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Pt.dispatchEvent(r)):r={promise:e,reason:t},!fk&&(i=Pt["on"+a])?i(r):a===Xf&&pk("Unhandled promise rejection",t)},Ek=function(a){Nr(Wf,Pt,function(){var e=a.facade,t=a.value,r=Gf(a),i;if(r&&(i=hk(function(){Ms?wu.emit("unhandledRejection",t,e):ab(Xf,e,t)}),a.rejection=Ms||Gf(a)?eb:ku,i.error))throw i.value})},Gf=function(a){return a.rejection!==ku&&!a.parent},xk=function(a){Nr(Wf,Pt,function(){var e=a.facade;Ms?wu.emit("rejectionHandled",e):ab(yk,e,a.value)})},Br=function(a,e,t){return function(r){a(e,r,t)}},_r=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Tk,ib(a,!0))},xu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Jf("Promise can't be resolved itself");var r=tb(e);r?Pu(function(){var i={done:!1};try{Nr(r,e,Br(xu,i,a),Br(_r,i,a))}catch(s){_r(i,s,a)}}):(a.value=e,a.state=Zf,ib(a,!1))}catch(i){_r({done:!1},i,a)}}};if(Kf&&(er=function(e){ck(this,Rs),uk(e),Nr($s,this);var t=Tu(this);try{e(Br(xu,t),Br(_r,t))}catch(r){_r(t,r)}},Rs=er.prototype,$s=function(e){gk(this,{type:Ds,done:!1,notified:!1,parent:!1,reactions:new mk,rejection:!1,state:Hf,value:void 0})},$s.prototype=qf(Rs,"then",function(e,t){var r=Tu(this),i=Eu(dk(this,er));return r.parent=!0,i.ok=Ls(e)?e:!0,i.fail=Ls(t)&&t,i.domain=Ms?wu.domain:void 0,r.state===Hf?r.reactions.add(i):Pu(function(){rb(i,r)}),i.promise}),jf=function(){var a=new $s,e=Tu(a);this.promise=a,this.resolve=Br(xu,e),this.reject=Br(_r,e)},zf.f=Eu=function(a){return a===er||a===Ik?new jf(a):vk(a)},!sk&&Ls(Cs)&&Vr!==Object.prototype)){Qf=Vr.then,bk||qf(Vr,"then",function(e,t){var r=this;return new er(function(i,s){Nr(Qf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Vr.constructor}catch(a){}Uf&&Uf(Vr,Rs)}ak({global:!0,constructor:!0,wrap:!0,forced:Kf},{Promise:er});nk(er,Ds,!1,!0);ok(Ds)});var cb=f((HV,lb)=>{"use strict";var Pk=oe(),ob=Pk("iterator"),ub=!1;try{nb=0,Ru={next:function(){return{done:!!nb++}},return:function(){ub=!0}},Ru[ob]=function(){return this},Array.from(Ru,function(){throw 2})}catch(a){}var nb,Ru;lb.exports=function(a,e){try{if(!e&&!ub)return!1}catch(i){return!1}var t=!1;try{var r={};r[ob]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var $u=f((jV,db)=>{"use strict";var Ak=Zt(),wk=cb(),kk=Dr().CONSTRUCTOR;db.exports=kk||!wk(function(a){Ak.all(a).then(void 0,function(){})})});var pb=f(()=>{"use strict";var Rk=X(),$k=Pe(),Lk=Ke(),Mk=Or(),Ck=ks(),Dk=Is(),Ok=$u();Rk({target:"Promise",stat:!0,forced:Ok},{all:function(e){var t=this,r=Mk.f(t),i=r.resolve,s=r.reject,n=Ck(function(){var o=Lk(t.resolve),u=[],l=0,c=1;Dk(e,function(d){var h=l++,p=!1;c++,$k(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var mb=f(()=>{"use strict";var Vk=X(),Bk=Ue(),_k=Dr().CONSTRUCTOR,Mu=Zt(),Nk=at(),Fk=Y(),qk=Lr(),hb=Mu&&Mu.prototype;Vk({target:"Promise",proto:!0,forced:_k,real:!0},{catch:function(a){return this.then(void 0,a)}});!Bk&&Fk(Mu)&&(Lu=Nk("Promise").prototype.catch,hb.catch!==Lu&&qk(hb,"catch",Lu,{unsafe:!0}));var Lu});var fb=f(()=>{"use strict";var Uk=X(),Hk=Pe(),jk=Ke(),Qk=Or(),Gk=ks(),Wk=Is(),Yk=$u();Uk({target:"Promise",stat:!0,forced:Yk},{race:function(e){var t=this,r=Qk.f(t),i=r.reject,s=Gk(function(){var n=jk(t.resolve);Wk(e,function(o){Hk(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var bb=f(()=>{"use strict";var zk=X(),Kk=Or(),Jk=Dr().CONSTRUCTOR;zk({target:"Promise",stat:!0,forced:Jk},{reject:function(e){var t=Kk.f(this),r=t.reject;return r(e),t.promise}})});var Cu=f((ZV,gb)=>{"use strict";var Xk=Je(),Zk=Ae(),eR=Or();gb.exports=function(a,e){if(Xk(a),Zk(e)&&e.constructor===a)return e;var t=eR.f(a),r=t.resolve;return r(e),t.promise}});var yb=f(()=>{"use strict";var tR=X(),rR=at(),vb=Ue(),iR=Zt(),Sb=Dr().CONSTRUCTOR,aR=Cu(),sR=rR("Promise"),nR=vb&&!Sb;tR({target:"Promise",stat:!0,forced:vb||Sb},{resolve:function(e){return aR(nR&&this===sR?iR:this,e)}})});var Tb=f(()=>{"use strict";sb();pb();mb();fb();bb();yb()});var Pb=f(()=>{"use strict";var oR=X(),uR=Ue(),Os=Zt(),lR=ne(),Eb=at(),xb=Y(),cR=ru(),Ib=Cu(),dR=Lr(),Ou=Os&&Os.prototype,pR=!!Os&&lR(function(){Ou.finally.call({then:function(){}},function(){})});oR({target:"Promise",proto:!0,real:!0,forced:pR},{finally:function(a){var e=cR(this,Eb("Promise")),t=xb(a);return this.then(t?function(r){return Ib(e,a()).then(function(){return r})}:a,t?function(r){return Ib(e,a()).then(function(){throw r})}:a)}});!uR&&xb(Os)&&(Du=Eb("Promise").prototype.finally,Ou.finally!==Du&&dR(Ou,"finally",Du,{unsafe:!0}));var Du});var wb=f((nB,Ab)=>{"use strict";Dm();Tb();Pb();var hR=xt();Ab.exports=hR("Promise","finally")});var Rb=f((oB,kb)=>{"use strict";var mR=wb();kb.exports=mR});var Vs=f((uB,$b)=>{"use strict";var fR=Rb();$b.exports=fR});var Hb=f(()=>{"use strict";var RR=X(),$R=ko().values;RR({target:"Object",stat:!0},{values:function(e){return $R(e)}})});var Qb=f((GB,jb)=>{"use strict";Hb();var LR=Ir();jb.exports=LR.Object.values});var Wb=f((WB,Gb)=>{"use strict";var MR=Qb();Gb.exports=MR});var Mi=f((YB,Yb)=>{"use strict";var CR=Wb();Yb.exports=CR});var og=f(()=>{"use strict";var zR=X(),KR=Er(),JR=Rr(),XR=gi(),ZR=vi();zR({target:"Array",proto:!0},{at:function(e){var t=KR(this),r=JR(t),i=XR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});ZR("at")});var lg=f((I_,ug)=>{"use strict";og();var e$=xt();ug.exports=e$("Array","at")});var dg=f((E_,cg)=>{"use strict";var t$=lg();cg.exports=t$});var Ur=f((x_,pg)=>{"use strict";var r$=dg();pg.exports=r$});var al=f((iF,Ug)=>{"use strict";var _$=Gt();Ug.exports=Array.isArray||function(e){return _$(e)==="Array"}});var jg=f((aF,Hg)=>{"use strict";var N$=TypeError,F$=9007199254740991;Hg.exports=function(a){if(a>F$)throw N$("Maximum allowed index exceeded");return a}});var Wg=f((sF,Gg)=>{"use strict";var q$=al(),U$=Rr(),H$=jg(),j$=Pr(),Qg=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?j$(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&q$(d)?(h=U$(d),u=Qg(a,e,d,h,u,s-1)-1):(H$(u+1),a[u]=d),u++),l++;return u};Gg.exports=Qg});var Jg=f((nF,Kg)=>{"use strict";var Yg=al(),Q$=tu(),G$=Ae(),W$=oe(),Y$=W$("species"),zg=Array;Kg.exports=function(a){var e;return Yg(a)&&(e=a.constructor,Q$(e)&&(e===zg||Yg(e.prototype))?e=void 0:G$(e)&&(e=e[Y$],e===null&&(e=void 0))),e===void 0?zg:e}});var Zg=f((oF,Xg)=>{"use strict";var z$=Jg();Xg.exports=function(a,e){return new(z$(a))(e===0?0:e)}});var ev=f(()=>{"use strict";var K$=X(),J$=Wg(),X$=Ke(),Z$=Er(),eL=Rr(),tL=Zg();K$({target:"Array",proto:!0},{flatMap:function(e){var t=Z$(this),r=eL(t),i;return X$(e),i=tL(t,0),i.length=J$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var tv=f(()=>{"use strict";var rL=vi();rL("flatMap")});var iv=f((pF,rv)=>{"use strict";ev();tv();var iL=xt();rv.exports=iL("Array","flatMap")});var sv=f((hF,av)=>{"use strict";var aL=iv();av.exports=aL});var sl=f((mF,nv)=>{"use strict";var sL=sv();nv.exports=sL});var Gi=f((xF,Av)=>{"use strict";var hL=yi(),mL=String;Av.exports=function(a){if(hL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return mL(a)}});var ol=f((PF,wv)=>{"use strict";wv.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 $v=f((AF,Rv)=>{"use strict";var fL=te(),bL=Et(),gL=Gi(),ll=ol(),kv=fL("".replace),vL=RegExp("^["+ll+"]+"),SL=RegExp("(^|[^"+ll+"])["+ll+"]+$"),ul=function(a){return function(e){var t=gL(bL(e));return a&1&&(t=kv(t,vL,"")),a&2&&(t=kv(t,SL,"$1")),t}};Rv.exports={start:ul(1),end:ul(2),trim:ul(3)}});var Dv=f((wF,Cv)=>{"use strict";var yL=Oo().PROPER,TL=ne(),Lv=ol(),Mv="\u200B\x85\u180E";Cv.exports=function(a){return TL(function(){return!!Lv[a]()||Mv[a]()!==Mv||yL&&Lv[a].name!==a})}});var cl=f((kF,Ov)=>{"use strict";var IL=$v().start,EL=Dv();Ov.exports=EL("trimStart")?function(){return IL(this)}:"".trimStart});var Bv=f(()=>{"use strict";var xL=X(),Vv=cl();xL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Vv},{trimLeft:Vv})});var Nv=f(()=>{"use strict";Bv();var PL=X(),_v=cl();PL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==_v},{trimStart:_v})});var qv=f((CF,Fv)=>{"use strict";Nv();var AL=xt();Fv.exports=AL("String","trimLeft")});var Hv=f((DF,Uv)=>{"use strict";var wL=qv();Uv.exports=wL});var Qv=f((OF,jv)=>{"use strict";var kL=Hv();jv.exports=kL});var oS=f(()=>{"use strict"});var uS=f(()=>{"use strict"});var cS=f((s1,lS)=>{"use strict";var JL=Ae(),XL=Gt(),ZL=oe(),eM=ZL("match");lS.exports=function(a){var e;return JL(a)&&((e=a[eM])!==void 0?!!e:XL(a)==="RegExp")}});var pS=f((n1,dS)=>{"use strict";var tM=Je();dS.exports=function(){var a=tM(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 fS=f((o1,mS)=>{"use strict";var rM=Pe(),iM=He(),aM=di(),sM=pS(),hS=RegExp.prototype;mS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in hS)&&!iM(a,"flags")&&aM(hS,a)?rM(sM,a):e}});var gS=f((u1,bS)=>{"use strict";var Sl=te(),nM=Er(),oM=Math.floor,gl=Sl("".charAt),uM=Sl("".replace),vl=Sl("".slice),lM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,cM=/\$([$&'`]|\d{1,2})/g;bS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=cM;return i!==void 0&&(i=nM(i),u=lM),uM(s,u,function(l,c){var d;switch(gl(c,0)){case"$":return"$";case"&":return a;case"`":return vl(e,0,t);case"'":return vl(e,n);case"<":d=i[vl(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=oM(h/10);return p===0?l:p<=o?r[p-1]===void 0?gl(c,1):r[p-1]+gl(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var yS=f(()=>{"use strict";var dM=X(),pM=Pe(),Tl=te(),vS=Et(),hM=Y(),mM=Tr(),fM=cS(),Yr=Gi(),bM=hi(),gM=fS(),vM=gS(),SM=oe(),yM=Ue(),TM=SM("replace"),IM=TypeError,yl=Tl("".indexOf),EM=Tl("".replace),SS=Tl("".slice),xM=Math.max;dM({target:"String",proto:!0},{replaceAll:function(e,t){var r=vS(this),i,s,n,o,u,l,c,d,h,p,m=0,b="";if(!mM(e)){if(i=fM(e),i&&(s=Yr(vS(gM(e))),!~yl(s,"g")))throw new IM("`.replaceAll` does not allow non-global regexes");if(n=bM(e,TM),n)return pM(n,e,r,t);if(yM&&i)return EM(Yr(r),e,t)}for(o=Yr(r),u=Yr(e),l=hM(t),l||(t=Yr(t)),c=u.length,d=xM(1,c),h=yl(o,u);h!==-1;)p=l?Yr(t(u,h,o)):vM(u,o,h,[],void 0,t),b+=SS(o,m,h)+p,m=h+c,h=h+d>o.length?-1:yl(o,u,h+d);return m<o.length&&(b+=SS(o,m)),b}})});var IS=f((d1,TS)=>{"use strict";oS();uS();yS();var PM=xt();TS.exports=PM("String","replaceAll")});var xS=f((p1,ES)=>{"use strict";var AM=IS();ES.exports=AM});var AS=f((h1,PS)=>{"use strict";var wM=xS();PS.exports=wM});var kS=f((m1,wS)=>{"use strict";var kM=gi(),RM=Gi(),$M=Et(),LM=RangeError;wS.exports=function(e){var t=RM($M(this)),r="",i=kM(e);if(i<0||i===1/0)throw new LM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var CS=f((f1,MS)=>{"use strict";var LS=te(),MM=yo(),RS=Gi(),CM=kS(),DM=Et(),OM=LS(CM),VM=LS("".slice),BM=Math.ceil,$S=function(a){return function(e,t,r){var i=RS(DM(e)),s=MM(t),n=i.length,o=r===void 0?" ":RS(r),u,l;return s<=n||o===""?i:(u=s-n,l=OM(o,BM(u/o.length)),l.length>u&&(l=VM(l,0,u)),a?i+l:l+i)}};MS.exports={start:$S(!1),end:$S(!0)}});var OS=f((b1,DS)=>{"use strict";var _M=Yt();DS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(_M)});var VS=f(()=>{"use strict";var NM=X(),FM=CS().start,qM=OS();NM({target:"String",proto:!0,forced:qM},{padStart:function(e){return FM(this,e,arguments.length>1?arguments[1]:void 0)}})});var _S=f((S1,BS)=>{"use strict";VS();var UM=xt();BS.exports=UM("String","padStart")});var FS=f((y1,NS)=>{"use strict";var HM=_S();NS.exports=HM});var US=f((T1,qS)=>{"use strict";var jM=FS();qS.exports=jM});var _c="2.0.123-dev.499ebc9f.0";var me=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(me||{}),It=(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))(It||{});var rs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(rs||{}),Un=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Un||{});var Hn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Hn||{}),oi=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(oi||{});var gT=C(Xe(),1);import{assertNever as Vp,assertNonNullable as rx,isNonNullable as os,ValueSubject as Io,Subject as ix,Subscription as ax,merge as sx,observableFrom as nx,fromEvent as Mp,map as Cp,tap as Dp,filterChanged as ox,isNullable as Eo,ErrorCategory as Op}from"@vkontakte/videoplayer-shared/es2018";var Lp=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var us=class{constructor(e){this.connection$=new Io(void 0);this.castState$=new Io("NOT_AVAILABLE");this.errorEvent$=new ix;this.realCastState$=new Io("NOT_AVAILABLE");this.subscription=new ax;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=os((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Lp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Op.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(){os(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Eo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Eo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Mp(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 Vp(i.sessionState)}})).add(sx(Mp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Dp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Cp(i=>i.castState)),nx([r.getCastState()])).pipe(ox(),Cp(ux),Dp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=os(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();rx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Eo(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"?os(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:Op.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},ux=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 Vp(a)}};var Jl=C(Xe(),1),Xy=C($r(),1),Zy=C(Ko(),1);var Fb=C(Vs(),1);import{assertNever as Lb}from"@vkontakte/videoplayer-shared/es2018";var ue=(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:Lb(t)}return a},Bs=(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:Lb(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as bR,Subject as _s,merge as Mb}from"@vkontakte/videoplayer-shared/es2018";var $=class{constructor(e){this.transitionStarted$=new _s;this.transitionEnded$=new _s;this.transitionUpdated$=new _s;this.forceChanged$=new _s;this.stateChangeStarted$=Mb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Mb(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||bR(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 gR}from"@vkontakte/videoplayer-shared/es2018";var Cb=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 gR(a)}};import{assertNever as Fr,assertNonNullable as tr,debounce as Db,ErrorCategory as Ob,fromEvent as rr,isNonNullable as Vb,map as Bb,merge as _b,observableFrom as vR,Subject as SR,Subscription as Vu,timeout as yR,getHighestQuality as TR}from"@vkontakte/videoplayer-shared/es2018";var IR=5,ER=5,xR=500,Nb=7e3,Li=class{constructor(e){this.subscription=new Vu;this.loadMediaTimeoutSubscription=new Vu;this.videoState=new $("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:Fr(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:Fr(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:Fr(e)}break}default:Fr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Cb(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 Vu;this.subscription.add(e),this.subscription.add(_b(this.videoState.stateChangeStarted$.pipe(Bb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Bb(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 SR;e.add(i.pipe(Db(xR)).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)>IR)&&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<ER&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Fr(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=_b(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,vR(["init"])).pipe(Db(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=TR(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=ue(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:Ob.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Fr(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 Vb(o)&&(n.metadata.title=o),Vb(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(yR(Nb).subscribe(()=>s(`timeout(${Nb})`)))});(0,Fb.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:Ob.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var rl=C(Xe(),1);import{clearVideoElement as Ub}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as PR}from"@vkontakte/videoplayer-shared/es2018";var qb=a=>{try{a.pause(),a.playbackRate=0,PR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as AR,Subscription as wR}from"@vkontakte/videoplayer-shared/es2018";var Bu=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)}},_u=window.WeakMap?new WeakMap:new Bu,Nu=window.WeakMap?new WeakMap:new Map,kR=(a,e=20)=>{let t=0;return AR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},fe=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Ub(t):(t=document.createElement("video"),a.appendChild(t)),_u.set(t,r);let i=new wR;return i.add(kR(t,e)),Nu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},be=a=>{let e=Nu.get(a);e==null||e.unsubscribe(),Nu.delete(a);let t=_u.get(a);_u.delete(a),t?Ub(a):qb(a)};var qu=C(Mi(),1);import{assertNonNullable as Ci,isNonNullable as et,isNullable as VR,fromEvent as qr,merge as zb,observableFrom as Kb,filterChanged as Jb,map as Di,Subject as Xb,Subscription as BR,ValueSubject as _R,ErrorCategory as NR}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Fu,isNullable as DR,Subscription as OR}from"@vkontakte/videoplayer-shared/es2018";var Ns=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=DR(i),l=new OR;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)=>Ns(e,()=>a.loop,r=>{Fu(r)&&(a.loop=r)},{onError:t}),ge=(a,e,t,r)=>Ns(e,()=>({muted:a.muted,volume:a.volume}),i=>{Fu(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}),Ce=(a,e,t,r)=>Ns(e,()=>a.playbackRate,i=>{Fu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),At=Ns;var FR=a=>["__",a.language,a.label].join("|"),qR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Uu=class a{constructor(){this.available$=new Xb;this.current$=new _R(void 0);this.error$=new Xb;this.subscription=new BR;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:NR.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(At(t.internalTextTracks,()=>(0,qu.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(Di(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(At(t.externalTextTracks,()=>(0,qu.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(Di(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(At(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(At(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ci(this.video);let{textTracks:e}=this.video;this.subscription.add(qr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(zb(qr(e,"addtrack"),qr(e,"removetrack"),Kb(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Jb((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(zb(qr(e,"change"),Kb(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Di(r=>r&&this.htmlTextTrackToITextTrack(r).id),Jb()).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(qr(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(qr(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){Ci(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:FR(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){Ci(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(VR(e)||!qR(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){Ci(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){Ci(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)}},De=Uu;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 Zb=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},Hu=a=>{let e=Zb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},eg=a=>{let e=Zb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Oe,map as wt,merge as rg,filterChanged as HR,isNonNullable as ig,Subject as jR,filter as ag,mapTo as sg,combine as QR,once as GR,ErrorCategory as WR,ValueSubject as ng,clientChecker as YR}from"@vkontakte/videoplayer-shared/es2018";var UR=3,tg=(a,e,t=UR)=>{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 ve=a=>{let e=y=>Oe(a,y).pipe(sg(void 0)),r=rg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Oe(a,y))).pipe(wt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),HR()),i=rg(Oe(a,"progress"),Oe(a,"timeupdate")).pipe(wt(()=>tg(a.buffered,a.currentTime))),s=YR.isSafari?QR({play:e("play").pipe(GR()),playing:e("playing")}).pipe(sg(void 0)):e("playing"),n=Oe(a,"volumechange").pipe(wt(()=>({muted:a.muted,volume:a.volume}))),o=Oe(a,"ratechange").pipe(wt(()=>a.playbackRate)),u=Oe(a,"error").pipe(ag(()=>!!(a.error||a.played.length)),wt(()=>{var E;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:WR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=Oe(a,"timeupdate").pipe(wt(()=>a.currentTime)),c=new jR,d=.3,h;l.subscribe(y=>{a.loop&&ig(h)&&ig(y)&&h>=a.duration-d&&y<=d&&c.next(h),h=y});let p=e("pause").pipe(ag(()=>!a.error&&h!==a.duration)),m=Oe(a,"enterpictureinpicture"),b=Oe(a,"leavepictureinpicture"),g=new ng(eg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new ng(Hu(a));return Oe(a,"fullscreenchange").pipe(wt(()=>Hu(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$:Oe(a,"durationchange").pipe(wt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as kt}from"@vkontakte/videoplayer-shared/es2018";var Rt=a=>{switch(a){case"mobile":return kt.Q_144P;case"lowest":return kt.Q_240P;case"low":return kt.Q_360P;case"sd":case"medium":return kt.Q_480P;case"hd":case"high":return kt.Q_720P;case"fullhd":case"full":return kt.Q_1080P;case"quadhd":case"quad":return kt.Q_1440P;case"ultrahd":case"ultra":return kt.Q_2160P}};var $t=C(Ur(),1),Sg=C(Xe(),1),qs=C($r(),1);import{isNonNullable as re,isNullable as Qu,now as yg,isHigher as Gu,isHigherOrEqual as Wu,isInvariantQuality as bg,isLower as gg,isLowerOrEqual as Yu,videoSizeToQuality as i$,assertNotEmptyArray as Tg,assertNonNullable as a$}from"@vkontakte/videoplayer-shared/es2018";var ju=!1,ut={},hg=a=>{ju=a},mg=()=>{ut={}},fg=a=>{a(ut)},Oi=(a,e)=>{var t;ju&&(ut.meta=(t=ut.meta)!=null?t:{},ut.meta[a]=e)},de=class{constructor(e){this.name=e}next(e){var r,i;if(!ju)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}};function Fs({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}var s$=new de("best_bitrate"),Ig=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var zu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Vi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=yg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Eg='Assertion "ABR Tracks is empty array" failed',Us=(a,e,t,r)=>{var u;let i=[...e].sort(zu(1)),s=[...t].sort(zu(1)),n=s.filter(l=>re(l.bitrate)&&re(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,$t.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,$t.default)(s,-1);return o&&(0,Sg.default)(n,o)?o:n.length?(0,$t.default)(n,-1):(0,$t.default)(s,0)},vg=a=>"quality"in a,xg=(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]&&yg()-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=vg(o)?"video":"audio",l=vg(o)?o.quality:o.bitrate;return e({message:`
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:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return r==null||r.recordSwitch(t),t},n$=(a,e)=>Math.log(e)/Math.log(a),o$=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&window.devicePixelRatio){let n=window.devicePixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(n-1)+1;else{let o=a.pixelRatioLogBase,[u=0,l=0,c=0]=a.pixelRatioLogCoefficients,d=n$(o,u*n+l)+c;Number.isFinite(d)&&(r*=d)}}let{highQualityLimit:i,trafficSavingLimit:s}=a;return t&&Fs({limits:t,highQualityLimit:i,trafficSavingLimit:s})==="high_quality"&&(r*=2),a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0},Lt=(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:m})=>{var q,O,k,w,H,J;Tg(a,Eg);let b=o$({container:e,tuning:r,limits:i}),g=r.considerPlaybackRate&&re(o)?o:1,v=a.filter(S=>!bg(S.quality)).sort((S,R)=>Gu(S.quality,R.quality)?-1:1),T=(q=(0,$t.default)(v,-1))==null?void 0:q.quality,y=(O=(0,$t.default)(v,0))==null?void 0:O.quality,E=Qu(i)||re(i.min)&&re(i.max)&&gg(i.max,i.min)||re(i.min)&&y&&Gu(i.min,y)||re(i.max)&&T&&gg(i.max,T),I=g*Ig(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),A={},D=v.filter(S=>{let R=!0;if(b)if(S.size)R=S.size.width<=b.width&&S.size.height<=b.height;else{let Z=b&&i$(b);R=Z?Yu(S.quality,Z):!0}if(!R)return A[S.quality]="FitsContainer",!1;let j=p||t;if(!(re(j)&&isFinite(j)&&re(S.bitrate)?j-s>=S.bitrate*I:!0))return A[S.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&re(r.minBufferToSwitchUp)&&u&&!bg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Gu(S.quality,u.quality))return A[S.quality]="Buffer",!1;if(!!d&&Wu(S.quality,d))return A[S.quality]="DroppedFramesLimit",!1;if(!!h&&Wu(S.quality,h))return A[S.quality]="StallsLimit",!1;let Ft=E||(Qu(i.max)||Yu(S.quality,i.max))&&(Qu(i.min)||Wu(S.quality,i.min)),_=re(c)&&!c?Yu(S.quality,r.backgroundVideoQualityLimit):!0;return!Ft||!_?(A[S.quality]="FitsQualityLimits",!1):!0})[0];D&&D.bitrate&&s$.next(D.bitrate);let L=(k=D!=null?D:(0,$t.default)(v,-1))!=null?k:a[0];return L.quality!==((w=l==null?void 0:l.last)==null?void 0:w.quality)&&m({message:`
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:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(S=>`{ id: ${S.id}, quality: ${S.quality}, bitrate: ${S.bitrate} }`).join(`
12
+ ${a.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate} }`).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,qs.default)(r!=null?r:{}).map(([S,R])=>`${S}: ${R}`).join(`
16
+ ${(0,Ns.default)(r!=null?r:{}).map(([T,O])=>`${T}: ${O}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
- containerSizeLimit: ${(H=b==null?void 0:b.width)!=null?H:0} x ${(J=b==null?void 0:b.width)!=null?J:0},
20
+ containerSizeLimit: ${(J=g==null?void 0:g.width)!=null?J:0} x ${(A=g==null?void 0:g.width)!=null?A:0},
21
21
  estimatedThroughput: ${t},
22
22
  stallsPredictedThroughput: ${p},
23
23
  reserve: ${s},
24
24
  playbackRate: ${o},
25
- playbackRateFactor: ${g},
25
+ playbackRateFactor: ${v},
26
26
  forwardBufferHealth: ${n},
27
- bitrateFactor: ${I},
27
+ bitrateFactor: ${R},
28
28
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
29
29
  droppedVideoMaxQualityLimit: ${d},
30
30
  stallsVideoMaxQualityLimit: ${h},
31
- limitsAreInvalid: ${E},
31
+ limitsAreInvalid: ${I},
32
32
  maxQualityLimit: ${i==null?void 0:i.max},
33
33
  minQualityLimit: ${i==null?void 0:i.min},
34
34
 
35
35
  [limited video tracks]
36
- ${(0,qs.default)(A).map(([S,R])=>`${S}: ${R}`).join(`
36
+ ${(0,Ns.default)(C).map(([T,O])=>`${T}: ${O}`).join(`
37
37
  `)||"All tracks are available"}
38
38
 
39
- [best video track] ${D==null?void 0:D.quality}
40
- [selected video track] ${L==null?void 0:L.quality}
41
- `}),xg(r,m,L,l)},Pg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Tg(t,Eg);let c=i.considerPlaybackRate&&re(s)?s:1,d=[...t].sort(zu(-1)),h=a.bitrate;a$(h);let p=c*Ig(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,b=Us(a,e,t,i.minVideoAudioRatio),g=l||r;return re(g)&&isFinite(g)&&(m=d.find(T=>re(T.bitrate)&&re(b==null?void 0:b.bitrate)?g-h>=T.bitrate*p&&T.bitrate>=b.bitrate:!1)),m||(m=b),(m==null?void 0:m.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
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:`
42
42
  [AUDIO TRACKS ABR]
43
43
  [available audio tracks]
44
- ${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
44
+ ${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
45
45
  `)}
46
46
 
47
47
  [tuning]
48
- ${(0,qs.default)(i!=null?i:{}).map(([T,y])=>`${T}: ${y}`).join(`
48
+ ${(0,Ns.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
49
49
  `)}
50
50
 
51
51
  [limit params]
@@ -58,15 +58,15 @@ var RT=Object.create;var Bc=Object.defineProperty;var $T=Object.getOwnPropertyDe
58
58
  bitrateFactor: ${p},
59
59
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
60
60
 
61
- [selected audio track] ${m==null?void 0:m.id}
62
- `}),m&&xg(i,u,m,o)};var ie=a=>new URL(a).hostname;import{assertNever as Og,assertNonNullable as Vg,combine as k$,debounce as R$,ErrorCategory as Bg,filter as _g,filterChanged as $$,isNonNullable as el,map as Ws,merge as Ng,observableFrom as L$,once as M$,Subscription as C$,ValueSubject as tl,videoQualityToHeight as D$,videoSizeToQuality as O$}from"@vkontakte/videoplayer-shared/es2018";var wg=C(Xe(),1),Ag=a=>{if(a instanceof DOMException&&(0,wg.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"))},Se=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!Ag(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return Ag(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as js,isNullable as c$,assertNonNullable as Ni}from"@vkontakte/videoplayer-shared/es2018";var Rg=C(Mi(),1);import{isNonNullable as kg,assertNonNullable as Hs,now as u$}from"@vkontakte/videoplayer-shared/es2018";function ae(){return u$()}function Ku(a){return ae()-a}function Ju(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 $g(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Hr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;Hs(c);let k=Ku(c),w;if(k<b){w=b-k,setTimeout(g,w);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,A()},v=k=>(s=k,O),T=k=>(d=k,O),y=()=>(p="json",O),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=k=>(h=k,O),A=()=>{c=ae(),n=new i,n.open("get",a);let k=0,w,H=0,J=()=>(Hs(c),Math.max(c,Math.max(w||0,H||0)));if(s&&n.addEventListener("progress",S=>{let R=ae();s.updateChunk&&S.loaded>k&&(s.updateChunk(J(),S.loaded-k),k=S.loaded,w=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;Hs(n);let S=n.status;if(S>=200&&S<300){if(n.response.byteLength&&s){let R=n.response.byteLength-k;R&&s.updateChunk&&s.updateChunk(J(),R)}n.responseType==="json"&&!(0,Rg.default)(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),h){let S=()=>{Hs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(H=ae(),n.removeEventListener("readystatechange",S))};n.addEventListener("readystatechange",S)}return n.responseType=p,n.send(),O},O={withBitrateReporting:v,withParallel:I,withJSONResponse:y,withRetryCount:k=>(l=k,O),withRetryInterval:(k,w)=>(kg(k)&&(b=k),kg(w)&&(m=w),O),withTimeout:k=>(o=k,O),withFinally:T,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return O}var Bi=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 Lg=C(Mi(),1);var _i=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=Hr(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,Lg.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 d$}from"@vkontakte/videoplayer-shared/es2018";var Qs=1e4,Xu=3;var p$=6e4,h$=10,m$=1,f$=500,Fi=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 d$,this.chunkRateEstimator=new Bi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ju(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=Ju(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||js(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=()=>{$g(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 _i(Xu,Qs,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,A)=>{u&&u.abort(),u=Hr(this.urlResolver.resolve(E,!1),I,A,()=>this._retryCallback()).withTimeout(Qs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Xu).withFinally(()=>{u=null}).send()},p=(E,I,A)=>{Ni(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let I=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),r.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let A=ae()-1e4,F=0;for(let L=0;L<this.bufferStates.length;L++){let q=this.bufferStates[L];E=Math.min(E,q.buf),q.ts<A&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${E} drop=${F} jitter=${this.sourceJitter}`);let D=E-m$;this.sourceJitter>=0?D-=this.sourceJitter/2:this.sourceJitter-=1,D>3?m(1.15):D>1?m(1.1):D>.3?m(1.05):m(1)}},v=E=>{let I,A=()=>I&&I.start?I.start.length:0,F=S=>I.start[S]/1e3,D=S=>I.dur[S]/1e3,L=S=>I.fragIndex+S,q=(S,R)=>({chunkIdx:L(S),startTS:F(S),dur:D(S),discontinuity:R}),O=()=>{let S=0;if(I&&I.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,j=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,V=R;this.sourceJitter>1&&(V+=this.sourceJitter-1);let le=I.dur.length-1;for(;le>=0&&(V-=I.dur[le],!(V<=0));--le);S=Math.min(le,I.dur.length-1-j),S=Math.max(S,0)}return q(S,!0)},k=S=>{let R=A();if(!(R<=0)){if(js(S)){for(let j=0;j<R;j++)if(F(j)>S)return q(j)}return O()}},w=S=>{let R=A(),j=S?S.chunkIdx+1:0,V=j-I.fragIndex;if(!(R<=0)){if(!S||V<0||V-R>h$)return t(`Resync: offset=${V} bChunks=${R} chunk=`+JSON.stringify(S)),O();if(!(V>=R))return q(j-I.fragIndex,!1)}},H=(S,R,j)=>{l&&l.abort(),l=Hr(this.urlResolver.resolve(S,!0,this.lowLatency),R,j,()=>this._retryCallback()).withTimeout(Qs).withRetryCount(Xu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(S,R)=>{H(E,j=>{if(!d())return;I=j;let V=!!I.lowLatency;V!==this.lowLatency&&b(V);let le=0;for(let We=0;We<I.dur.length;++We)le+=I.dur[We];le>0&&(Ni(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(le/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,S(k(R))},()=>this._handleNetworkError())},nextChunk:w}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ni(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:I,logger:A}=this.params,F=v(e.jidxUrl),D,L,q,O,k=0,w,H,J,S=()=>{w&&(clearTimeout(w),w=void 0);let _=Math.max(f$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Z=k+_,Ee=ae(),Le=Math.min(1e4,Z-Ee);k=Ee;let ft=()=>{l||d()&&F.seek(()=>{d()&&(k=ae(),R(),S())})};Le>0?w=window.setTimeout(()=>{this.paused?S():ft()},Le):ft()},R=()=>{let _;for(;_=F.nextChunk(O);)O=_,ei(_);let Z=F.nextChunk(q);if(Z){if(q&&Z.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?S():(T(),this._initPlayerWith(e));return}We(Z)}else S()},j=(_,Z)=>{if(!d()||!this.sourceBuffer)return;let Ee,Le,ft,hr=bt=>{window.setTimeout(()=>{d()&&j(_,Z)},bt)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),hr(100);else{let bt=ae(),qt=I.currentTime;!this.paused&&I.buffered.length>1&&H===qt&&bt-J>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),H!==qt&&(H=qt,J=bt);let mr=this._getBufferSizeSec();if(mr>30)A(`Buffered ${mr} seconds; delaying appendBuffer`),hr(2e3);else try{this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(this.bufferStates.push({ts:bt,buf:mr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Z&&Z()}catch(ti){if(ti.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),ft=this.sourceBuffer.buffered.length,ft!==0&&(Ee=this.sourceBuffer.buffered.start(0),Le=qt,Le-Ee>4&&this.sourceBuffer.remove(Ee,Le-3)),hr(1e3);else throw ti}}},V=()=>{L&&D&&(A([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(q)]),j(L,function(){L=null,R()}))},le=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),We=_=>{d()&&p(le(_),(Z,Ee)=>{if(d()){if(Ee/=1e3,L=Z,q=_,n=_.startTS,Ee){let Le=Math.min(10,_.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Le:Le}V()}},()=>this._handleNetworkError())},ei=_=>{d()&&(Ni(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(le(_),!1)))},Ft=_=>{d()&&(e.cachedHeader=_,j(_,()=>{D=!0,V()}))};s=!0,F.seek(_=>{if(d()){if(k=ae(),!_){S();return}O=_,!c$(E)||_.startTS>E?We(_):(q=_,R())}},E),e.cachedHeader?Ft(e.cachedHeader):h(e.headerUrl,Ft,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),js(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,Ni(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return js(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=ae();if(this.chunkRateEstimator.addInterval(h,m,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Ku(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=Hr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Qs).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;Se(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))},p$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Dg=C($r(),1);import{debounce as b$,filter as Mg,fromEvent as g$,interval as v$,isHigher as S$,isInvariantQuality as y$,isLower as T$,merge as I$,Subject as Cg,Subscription as E$}from"@vkontakte/videoplayer-shared/es2018";var Zu=class{constructor(){this.onDroopedVideoFramesLimit$=new Cg;this.subscription=new E$;this.playing=!1;this.tracks=[];this.forceChecker$=new Cg;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&&!y$(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&&S$(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(g$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=v$(this.droppedFramesChecker.checkTime).pipe(Mg(()=>this.playing),Mg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(b$(this.droppedFramesChecker.checkTime)),r=I$(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,Dg.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>T$(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}},Gs=Zu;import{map as x$,Observable as P$}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as A$}from"@vkontakte/videoplayer-shared/es2018";var qi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var w$=(a,e)=>new P$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||qi()))},{...r,...e});i.observe(a);let s=A$(document,"visibilitychange").pipe(x$(n=>!document.hidden||qi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ve=w$;var V$=["paused","playing","ready"],B$=["paused","playing","ready"],Ui=class{constructor(e){this.subscription=new C$;this.videoState=new $("stopped");this.representations$=new tl([]);this.textTracksManager=new De;this.droppedFramesManager=new Gs;this.maxSeekBackTime$=new tl(1/0);this.zeroTime$=new tl(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:Bg.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=Rt(u.name))!=null?r:O$(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),el(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,rl.default)(B$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,rl.default)(V$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ue(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(ue(this.params.source.url,u))}return;default:return Og(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Bg.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Ng(this.videoState.stateChangeStarted$.pipe(Ws(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ws(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=fe(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=ve(this.video);this.subscription.add(this.representations$.pipe(Ws(i=>i.map(({track:s})=>s)),_g(i=>!!i.length),M$()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe($$(),Ws(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(k$({zeroTime:this.zeroTime$.pipe(_g(el)),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(ge(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ce(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(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&D$(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 Og(i.to)}},t)).add(Ng(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,L$(["init"])).pipe(R$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),be(this.video)}createLiveDashPlayer(){let e=new Fi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&el(t)?t:Lt(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=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;Vg(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;Vg(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(ue(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Fg=Ui;var Ey=C(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 EC,assertNonNullable as xC,debounce as PC,ErrorCategory as ql,filter as yy,filterChanged as Ra,fromEvent as AC,isNonNullable as Ty,map as Ul,merge as In,observableFrom as wC,once as Iy,Subscription as kC}from"@vkontakte/videoplayer-shared/es2018";var Ys=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}},jr=class extends Ys{constructor(){super(),this.listeners||Ys.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)}},Hi=class{constructor(){Object.defineProperty(this,"signal",{value:new jr,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&&(Hi.prototype[Symbol.toStringTag]="AbortController",jr.prototype[Symbol.toStringTag]="AbortSignal");function zs(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 il(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!zs({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,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var ji=zs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),qg=ji?il({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ji?qg.fetch:window.fetch,eF=ji?qg.Request:window.Request,ke=ji?Hi:window.AbortController,tF=ji?jr:window.AbortSignal;var _l=C(sl(),1);var sn=C(Ur(),1);var ct=()=>window.ManagedMediaSource||window.MediaSource,Ks=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},ov=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},uv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as on,clientChecker as nn}from"@vkontakte/videoplayer-shared/es2018";var Be=document.createElement("video"),uL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',lL='video/mp4; codecs="hev1.1.6.L93.B0"',Sv='video/webm; codecs="vp09.00.10.08"',yv='video/webm; codecs="av01.0.00M.08"',cL='audio/mp4; codecs="mp4a.40.2"',dL='audio/webm; codecs="opus"',lv,cv,Qi={mms:Ks(),mse:ov(),hls:!!((lv=Be.canPlayType)!=null&&lv.call(Be,"application/x-mpegurl")||(cv=Be.canPlayType)!=null&&cv.call(Be,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},dv,pv,ye={mp4:!!((dv=Be.canPlayType)!=null&&dv.call(Be,"video/mp4")),webm:!!((pv=Be.canPlayType)!=null&&pv.call(Be,"video/webm")),cmaf:!0},Xs,hv,Zs,mv,en,fv,tn,bv,rn,gv,an,vv,Te={h264:!!((hv=(Xs=ct())==null?void 0:Xs.isTypeSupported)!=null&&hv.call(Xs,uL)),h265:!!((mv=(Zs=ct())==null?void 0:Zs.isTypeSupported)!=null&&mv.call(Zs,lL)),vp9:!!((fv=(en=ct())==null?void 0:en.isTypeSupported)!=null&&fv.call(en,Sv)),av1:!!((bv=(tn=ct())==null?void 0:tn.isTypeSupported)!=null&&bv.call(tn,yv)),aac:!!((gv=(rn=ct())==null?void 0:rn.isTypeSupported)!=null&&gv.call(rn,cL)),opus:!!((vv=(an=ct())==null?void 0:an.isTypeSupported)!=null&&vv.call(an,dL))},Qr=(Te.h264||Te.h265)&&Te.aac,ir,pL=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:yv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Sv}})]);ir={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{pL()}catch(a){console.error(a)}var Gr=Qi.hls&&ye.mp4,Tv=()=>Object.keys(Te).filter(a=>Te[a]),Iv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Qi.mse&&(!r||!!window.MediaStreamTrack)||Qi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&ye.mp4&&Qr;case"DASH_WEBM":return i&&ye.webm&&Te.vp9&&Te.opus;case"DASH_WEBM_AV1":return i&&ye.webm&&Te.av1&&Te.opus;case"DASH_STREAMS":return i&&(ye.mp4&&Qr||ye.webm&&(Te.vp9||Te.av1)&&(Te.opus||Te.aac));case"DASH_LIVE":return i&&ye.mp4&&Qr;case"DASH_LIVE_CMAF":return i&&ye.mp4&&Qr&&ye.cmaf;case"DASH_ONDEMAND":return i&&ye.mp4&&Qr;case"HLS":case"HLS_ONDEMAND":return Gr||e&&i&&ye.mp4&&Qr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Gr;case"MPEG":return ye.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Qi.webrtc&&Qi.ws&&Te.h264&&(ye.mp4||ye.webm);default:return on(s)}})},Js=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:on(a)}return[e,t]},Ev=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Js(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(nn.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",...Js(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Js(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Js(a),...i,"HLS","HLS_ONDEMAND"];default:on(e)}return Gr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},xv=({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=nn.isMac&&nn.isSafari;if(nn.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:on(a)}else Gr&&!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"]},nl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Pv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,sn.default)(t.value.split("."),0)}for(let t of a){let r=(0,sn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,sn.default)(e.value.split("."),0)};var Gv=C(Qv(),1);import{ErrorCategory as Wi}from"@vkontakte/videoplayer-shared/es2018";var Wv=a=>{if(!a)return{id:"EmptyResponse",category:Wi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Wi.NETWORK,message:`UV Error ${a}`};let e=(0,Gv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Wi.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:Wi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Wi.PARSER,message:"Response is valid XML, but parser failed"}};var Mt=(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 Ol,assertNonNullable as lr,clientChecker as iC,combine as Pa,ErrorCategory as Vt,filter as bn,filterChanged as Vl,flattenObject as Aa,fromEvent as cr,getTraceSubscriptionMethod as aC,interval as Bl,isNonNullable as dy,map as wa,merge as dr,now as sC,Subject as py,Subscription as hy,tap as nC,throttle as oC,ValueSubject as K}from"@vkontakte/videoplayer-shared/es2018";var cn=C(Xe(),1),Kr=C(Ur(),1),dn=C(sl(),1);var RL=(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)},$L=a=>window.clearTimeout(a),Yv=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),zv=!Yv(window.requestIdleCallback)||!Yv(window.cancelIdleCallback),dl=zv?RL:window.requestIdleCallback,Yi=zv?$L:window.cancelIdleCallback;var iy=C(Vs(),1);import{assertNever as LL,ErrorCategory as Kv,clientChecker as pl,Subject as Jv}from"@vkontakte/videoplayer-shared/es2018";var ML=18,Xv=!1;try{Xv=pl.isSafari&&!!pl.macVersion&&pl.macVersion<=ML}catch(a){console.error(a)}var hl=class{constructor(e){this.bufferFull$=new Jv;this.error$=new Jv;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:Kv.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;Xv&&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:Kv.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:LL(t)}}},Zv=hl;var ml=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 pe,ErrorCategory as Dt,fromEvent as $l,getExponentialDelay as Ll,isNonNullable as un,isNullable as _e,now as ln,once as WM,Subject as YM,Subscription as zM,ValueSubject as zr}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 Wr=class extends U{};var zi=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 Ki=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 Ji=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 Xi=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 Zi=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=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 ta=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=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 aa=class extends W{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var sa=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 na=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=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 ua=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var la=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ca=class extends W{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var da=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pa=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 ha=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 ma=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 DL={ftyp:Ki,moov:Ji,mvhd:Xi,moof:Zi,mdat:ea,sidx:ar,trak:ta,mdia:na,mfhd:ca,tkhd:oa,traf:da,tfhd:pa,tfdt:ha,trun:ma,minf:ua,sv3d:ra,st3d:ia,prhd:aa,proj:la,equi:sa,uuid:zi,unknown:Wr},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=DL[e];return r?new r(t,new a):new Wr(t,new a)}};var Ct=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 VL=new TextDecoder("ascii"),BL=a=>VL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",_L=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})},NL=(a,e)=>{let r=new dt().parse(a),i=new Ct(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)},FL=a=>{let t=new dt().parse(a),r=new Ct(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},qL=a=>{var i;let t=new dt().parse(a);return(i=new Ct(t).find("sidx"))==null?void 0:i.timescale},UL=(a,e)=>{let r=new dt().parse(a),s=new Ct(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},HL=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 Ct(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},eS={validateData:BL,parseInit:HL,getIndexRange:()=>{},parseSegments:_L,parseFeedableSegmentChunk:NL,getChunkEndTime:UL,getServerLatencyTimestamps:FL,getTimescaleFromIndex:qL};var ba=C(Xe(),1);import{assertNonNullable as bl,isNonNullable as aS,isNullable as QL}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as jL}from"@vkontakte/videoplayer-shared/es2018";var tS={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"}},rS=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 tS,s=i?tS[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:jL(e)}},sr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=rS(r);if(!e(i))return;i.type==="master"&&sr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},iS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=rS(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 sS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],GL=[231,22612,22743,167,171,163,160,175],WL=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:m,valueSize:b})=>{if(h===21419){let g=Qe(m,p);l=fa(g)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Qe(m,p):h===17545?i=Qe(m,p):h===21420&&l===475249515?u=Qe(m,p):h===374648427?sr(m,({tag:g,type:v,value:T})=>g===30321?(c=Qe(T,v)===1,!1):!0):s&&n&&(0,ba.default)(sS,h)&&(o=!0),!o}),bl(e,"Failed to parse webm Segment start"),bl(t,"Failed to parse webm Segment end"),bl(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}}}},YL=a=>{if(QL(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zL=(a,e)=>{let t=!1,r=!1,i=o=>aS(o.time)&&aS(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,ba.default)(sS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},KL=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,ba.default)(GL,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ba.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},nS={validateData:iS,parseInit:WL,getIndexRange:YL,parseSegments:zL,parseFeedableSegmentChunk:KL};var ga=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return nS;case"mp4":return eS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var El=C(AS(),1),zS=C($r(),1),KS=C(US(),1),JS=C(Ur(),1);var HS=C(Xe(),1),Il=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,HS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as GS,isNullable as WS}from"@vkontakte/videoplayer-shared/es2018";var jS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var QS=a=>{var e;try{let t=QM(),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 QM(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
61
+ [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
63
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
64
64
  (-(?<script>[a-z]{4}))?
65
65
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
66
66
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
67
67
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
68
68
  (?:-(?<privateuse>(?:${e})))?
69
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var YS=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,El.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,zS.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,El.default)(t,n,(o,u)=>WS(s)?o:WS(u)?s:(0,KS.default)(s,parseInt(u,10),"0"))}return t},XS=(a,e)=>{var I,A,F,D,L,q,O,k,w,H,J,S,R,j,V,le,We,ei,Ft,_,Z,Ee,Le,ft,hr,bt,qt,mr,ti,ac,sc,nc,oc,uc,lc,cc,dc,pc,hc,mc,fc,bc,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc,Cc,Dc;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(se=>{var Ha,gt;return(gt=(Ha=se.textContent)==null?void 0:Ha.trim())!=null?gt:""}),u=(I=(0,JS.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,m=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(m)p=YS(m);else if(b){let se=YS(b);GS(se)&&(p=se)}else v&&(p=parseInt(v,10));let T=0,y=(F=(A=s.getAttribute("profiles"))==null?void 0:A.split(","))!=null?F:[];for(let se of l){let Ha=(D=se.getAttribute("id"))!=null?D:"id"+(T++).toString(10),gt=(L=se.getAttribute("mimeType"))!=null?L:"",Bn=(q=se.getAttribute("codecs"))!=null?q:"",_n=(O=se.getAttribute("contentType"))!=null?O:gt==null?void 0:gt.split("/")[0],vT=(w=(k=se.getAttribute("profiles"))==null?void 0:k.split(","))!=null?w:[],Oc=(J=QS((H=se.getAttribute("lang"))!=null?H:""))!=null?J:{},ST=(j=(R=(S=se.querySelector("Label"))==null?void 0:S.textContent)==null?void 0:R.trim())!=null?j:void 0,yT=se.querySelectorAll("Representation"),TT=se.querySelector("SegmentTemplate"),IT=(le=(V=se.querySelector("Role"))==null?void 0:V.getAttribute("value"))!=null?le:void 0,ri=_n,ee={id:Ha,language:Oc.language,isDefault:IT==="main",label:ST,codecs:Bn,hdr:ri==="video"&&Il(Bn),mime:gt,representations:[]};for(let G of yT){let ET=(We=G.getAttribute("lang"))!=null?We:void 0,xT=(ei=G.getAttribute("label"))!=null?ei:void 0,PT=(Z=(_=(Ft=G.querySelector("BaseURL"))==null?void 0:Ft.textContent)==null?void 0:_.trim())!=null?Z:"",ja=new URL(PT||u,e).toString(),fr=(Ee=G.getAttribute("mimeType"))!=null?Ee:gt,Qa=(ft=(Le=G.getAttribute("codecs"))!=null?Le:Bn)!=null?ft:"",Ga;if(_n==="text"){let vt=G.getAttribute("id")||"",Wa=((hr=Oc.privateuse)==null?void 0:hr.includes("x-auto"))||vt.includes("_auto"),Ut=G.querySelector("SegmentTemplate");if(Ut){let ii={representationId:(bt=G.getAttribute("id"))!=null?bt:void 0,bandwidth:(qt=G.getAttribute("bandwidth"))!=null?qt:void 0},Ya=parseInt((mr=G.getAttribute("bandwidth"))!=null?mr:"",10)/1e3,za=(ac=parseInt((ti=Ut.getAttribute("startNumber"))!=null?ti:"",10))!=null?ac:1,br=parseInt((sc=Ut.getAttribute("timescale"))!=null?sc:"",10),Nn=(nc=Ut.querySelectorAll("SegmentTimeline S"))!=null?nc:[],gr=Ut.getAttribute("media");if(!gr)continue;let Ka=[],Ja=0,Xa="",vr=0,ai=za,ce=0;for(let Ne of Nn){let Ht=parseInt((oc=Ne.getAttribute("d"))!=null?oc:"",10),Me=parseInt((uc=Ne.getAttribute("r"))!=null?uc:"",10)||0,St=parseInt((lc=Ne.getAttribute("t"))!=null?lc:"",10);ce=Number.isFinite(St)?St:ce;let jt=Ht/br*1e3,yt=ce/br*1e3;for(let Ye=0;Ye<Me+1;Ye++){let Tt=pt(gr,{...ii,segmentNumber:ai.toString(10),segmentTime:(ce+Ye*Ht).toString(10)}),Sr=(yt!=null?yt:0)+Ye*jt,ni=Sr+jt;ai++,Ka.push({time:{from:Sr,to:ni},url:Tt})}ce+=(Me+1)*Ht,Ja+=(Me+1)*jt}vr=ce/br*1e3,Xa=pt(gr,{...ii,segmentNumber:ai.toString(10),segmentTime:ce.toString(10)});let si={time:{from:vr,to:1/0},url:Xa},it={type:"template",baseUrl:ja,segmentTemplateUrl:gr,initUrl:"",totalSegmentsDurationMs:Ja,segments:Ka,nextSegmentBeyondManifest:si,timescale:br};Ga={id:vt,kind:"text",segmentReference:it,profiles:[],duration:p,bitrate:Ya,mime:"",codecs:"",width:0,height:0,isAuto:Wa}}else Ga={id:vt,isAuto:Wa,kind:"text",url:ja}}else{let vt=(dc=(cc=G.getAttribute("contentType"))!=null?cc:fr==null?void 0:fr.split("/")[0])!=null?dc:_n,Wa=(hc=(pc=se.getAttribute("profiles"))==null?void 0:pc.split(","))!=null?hc:[],Ut=parseInt((mc=G.getAttribute("width"))!=null?mc:"",10),ii=parseInt((fc=G.getAttribute("height"))!=null?fc:"",10),Ya=parseInt((bc=G.getAttribute("bandwidth"))!=null?bc:"",10)/1e3,za=(gc=G.getAttribute("frameRate"))!=null?gc:"",br=(vc=G.getAttribute("quality"))!=null?vc:void 0,Nn=za?jS(za):void 0,gr=(Sc=G.getAttribute("id"))!=null?Sc:"id"+(T++).toString(10),Ka=vt==="video"?`${ii}p`:vt==="audio"?`${Ya}Kbps`:Qa,Ja=`${gr}@${Ka}`,Xa=[...y,...vT,...Wa],vr,ai=G.querySelector("SegmentBase"),ce=(yc=G.querySelector("SegmentTemplate"))!=null?yc:TT;if(ai){let it=(Ic=(Tc=G.querySelector("SegmentBase Initialization"))==null?void 0:Tc.getAttribute("range"))!=null?Ic:"",[Ne,Ht]=it.split("-").map(Tt=>parseInt(Tt,10)),Me={from:Ne,to:Ht},St=(Ec=G.querySelector("SegmentBase"))==null?void 0:Ec.getAttribute("indexRange"),[jt,yt]=St?St.split("-").map(Tt=>parseInt(Tt,10)):[],Ye=St?{from:jt,to:yt}:void 0;vr={type:"byteRange",url:ja,initRange:Me,indexRange:Ye}}else if(ce){let it={representationId:(xc=G.getAttribute("id"))!=null?xc:void 0,bandwidth:(Pc=G.getAttribute("bandwidth"))!=null?Pc:void 0},Ne=parseInt((Ac=ce.getAttribute("timescale"))!=null?Ac:"",10),Ht=(wc=ce.getAttribute("initialization"))!=null?wc:"",Me=ce.getAttribute("media"),St=(Rc=parseInt((kc=ce.getAttribute("startNumber"))!=null?kc:"",10))!=null?Rc:1,jt=pt(Ht,it);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let yt=($c=ce.querySelectorAll("SegmentTimeline S"))!=null?$c:[],Ye=[],Tt=0,Sr="",ni=0;if(yt.length){let Za=St,Fe=0;for(let yr of yt){let ze=parseInt((Lc=yr.getAttribute("d"))!=null?Lc:"",10),Qt=parseInt((Mc=yr.getAttribute("r"))!=null?Mc:"",10)||0,es=parseInt((Cc=yr.getAttribute("t"))!=null?Cc:"",10);Fe=Number.isFinite(es)?es:Fe;let Fn=ze/Ne*1e3,qn=Fe/Ne*1e3;for(let ts=0;ts<Qt+1;ts++){let wT=pt(Me,{...it,segmentNumber:Za.toString(10),segmentTime:(Fe+ts*ze).toString(10)}),Vc=(qn!=null?qn:0)+ts*Fn,kT=Vc+Fn;Za++,Ye.push({time:{from:Vc,to:kT},url:wT})}Fe+=(Qt+1)*ze,Tt+=(Qt+1)*Fn}ni=Fe/Ne*1e3,Sr=pt(Me,{...it,segmentNumber:Za.toString(10),segmentTime:Fe.toString(10)})}else if(GS(p)){let Fe=parseInt((Dc=ce.getAttribute("duration"))!=null?Dc:"",10)/Ne*1e3,yr=Math.ceil(p/Fe),ze=0;for(let Qt=1;Qt<yr;Qt++){let es=pt(Me,{...it,segmentNumber:Qt.toString(10),segmentTime:ze.toString(10)});Ye.push({time:{from:ze,to:ze+Fe},url:es}),ze+=Fe}ni=ze,Sr=pt(Me,{...it,segmentNumber:yr.toString(10),segmentTime:ze.toString(10)})}let AT={time:{from:ni,to:1/0},url:Sr};vr={type:"template",baseUrl:ja,segmentTemplateUrl:Me,initUrl:jt,totalSegmentsDurationMs:Tt,segments:Ye,nextSegmentBeyondManifest:AT,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!vt||!fr)continue;let si={video:"video",audio:"audio",text:"text"}[vt];if(!si)continue;ri||(ri=si),Ga={id:Ja,kind:si,segmentReference:vr,profiles:Xa,duration:p,bitrate:Ya,mime:fr,codecs:Qa,width:Ut,height:ii,fps:Nn,quality:br}}ee.language||(ee.language=ET),ee.label||(ee.label=xT),ee.mime||(ee.mime=fr),ee.codecs||(ee.codecs=Qa),ee.hdr||(ee.hdr=ri==="video"&&Il(Qa)),ee.representations.push(Ga)}ri&&i[ri].push(ee)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var Al=C(Ur(),1);import{videoSizeToQuality as GM}from"@vkontakte/videoplayer-shared/es2018";var ZS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Rt(s):void 0)!=null?u:GM({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},ey=({id:a,bitrate:e})=>({id:a,bitrate:e}),ty=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ry=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),wl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Al.default)(r.split("."),0),isDefault:i}),kl=({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)}),Rl=a=>"url"in a,Re=a=>a.type==="template",va=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Sa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new zr(0);this.currentSegmentLength$=new zr(0);this.onLastSegment$=new zr(!1);this.fullyBuffered$=new zr(!1);this.playingRepresentation$=new zr(void 0);this.playingRepresentationInit$=new zr(void 0);this.error$=new YM;this.gaps=[];this.subscription=new zM;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);pe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Zv(this.sourceBuffer),this.subscription.add($l(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add($l(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Dt.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,ml(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);pe(r,"No init buffer for starting representation"),pe(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);pe(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(_e(s)||_e(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),pe(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();un(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,dn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!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);pe(i);let s=this.segments.get(r);pe(s,"No segments for starting representation");let n=this.initData.get(r);if(pe(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);pe(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(_e(o)||_e(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),pe(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();un(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(_e(e)||_e(this.downloadingRepresentationId)||_e(this.playingRepresentationId)||_e(this.sourceBuffer)||un(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(pe(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)&&ml(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,cn.default)(o,i))d="high";else{let h=(0,Kr.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,Kr.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;un(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,dn.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,dn.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,Kr.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;pe(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&&Yi&&Yi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yi&&Yi(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}},m)=>{let b=h<=r&&p>=r,g=h>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=r+v||p<=r+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&!(Mt(this.sourceBuffer.buffered,h)&&Mt(this.sourceBuffer.buffered,p)))&&g&&T});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=Ll(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=ln(),!c)return;let d=new DataView(c),h=ga(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:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),va(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())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=Ll(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),$l(window,"online").pipe(WM()).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=ln(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),va(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,Kr.default)(e,0).byte.from,to:(0,Kr.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=ln(),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:Dt.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=ln();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:Dt.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,cn.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=ga(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,m=d<=i;if(!p)continue;let b=ga(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):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&&(pe(this.sourceBuffer),Mt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Mt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Dt.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",Rl(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");pe(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=dl(()=>(0,iy.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=Ll(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ga(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:Dt.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||_e(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=Rl(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,cn.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||_e(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){pe(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=dl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Dt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(_e(this.sourceBuffer)||_e(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 ya=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ay=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ta,assertNever as ny,fromEvent as oy,merge as KM,now as Ia,Subscription as JM,ValueSubject as Ml,flattenObject as Jr}from"@vkontakte/videoplayer-shared/es2018";var sy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var pn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Ml(void 0);this.lastConnectionReused$=new Ml(void 0);this.lastRequestFirstBytes$=new Ml(void 0);this.abortAllController=new ke;this.subscription=new JM;this.fetchManifest=Ta(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ya(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=sy(r));let i=yield lt(r,{signal:this.abortAllController.signal}).catch(Ea);return i?(t.log("success",Jr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Jr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ta(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 O,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:ny(t)}this.requestQuic&&(l=ya(l));let h=this.abortAllController.signal,p;if(n){let w=new ke;if(p=KM(oy(this.abortAllController.signal,"abort"),oy(n,"abort")).subscribe(()=>{try{w.abort()}catch(H){Ea(H)}}),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch(H){Ea(H)}h=w.signal}let m=Ia();d.log("startRequest",Jr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:m}));let b=yield lt(l,{priority:s,headers:c,signal:h}).catch(Ea),g=Ia();if(!b)return d.error("error",{message:"No response in request"}),d.end(),p==null||p.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-m),!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=Ia(),H={requestStartedAt:m,requestEndedAt:w,duration:w-m};return d.log("endRequest",Jr(H)),d.end(),b.arrayBuffer()}let[v,T]=b.body.tee(),y=v.getReader();o&&((k=this.throughputEstimator)==null||k.trackStream(T,u));let E=0,I=new Uint8Array(0),A=!1,F=w=>{p==null||p.unsubscribe(),A=!0,Ea(w)},D=Ta(h,async function*({done:w,value:H}){if(E===0&&this.lastRequestFirstBytes$.next(Ia()-m),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(D,F)}}.bind(this));yield y==null?void 0:y.read().then(D,F),p==null||p.unsubscribe();let L=Ia(),q={failed:A,requestStartedAt:m,requestEndedAt:L,duration:L-m};return A?(d.error("endRequest",Jr(q)),d.end(),null):(d.log("endRequest",Jr(q)),d.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ta(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),m=(v=e.indexRange)!=null?v:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!T)return null;b=new DataView(T)}let g=t.parseSegments(b,p,m);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ta(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}=ay(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:ny(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ea=a=>{if(!va(a))throw a};var or=(a,e,t)=>t*e+(1-t)*a,Cl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,uy=(a,e,t,r)=>{let i=0,s=t,n=Cl(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 XM,ValueSubject as ly}from"@vkontakte/videoplayer-shared/es2018";var Ot=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 ly(e.initial),this.debounced$=new ly(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new de(`raw_${t}`),this.smoothedSeries$=new de(`smoothed_${t}`),this.reportedSeries$=new de(`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)&&(XM(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 hn=class extends Ot{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 mn=class extends Ot{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Cl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=or(this.emaSmoothed,e,this.params.emaAlpha);let r=uy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var fn=class extends Ot{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 hn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new mn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new fn({initial:e,label:"liveEdgeDelay",...t})}};var Dl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as ZM,ValueSubject as eC}from"@vkontakte/videoplayer-shared/es2018";var xa=class a{constructor(e,t){this.currentRepresentation$=new eC(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(!ZM(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 uC=["timeupdate","progress","play","seeked","stalled","waiting"],lC=["timeupdate","progress","loadeddata","playing","seeked"];var gn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new hy;this.representationSubscription=new hy;this.state$=new $("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 py;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 py;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=Ol(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ue(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:Vt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ol(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:Vt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=XS(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Wv(e))!=null?n:{id:"ManifestParsing",category:Vt.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,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=ct())==null?void 0:p.isTypeSupported)!=null&&m.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:m})=>r(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Pv(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);iC.isHDR&&p&&m?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",Aa(s)),s}.bind(this));this.initRepresentations=Ol(this.destroyController.signal,async function*(e,t,r){var h;this.tracer.log("initRepresentationsStart",Aa({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(bn(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:Vt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?uv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ks())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,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new Sa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],dy(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new Sa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}xa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new xa(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(Bl(1e3).subscribe(p=>{var m;if((m=this.element)!=null&&m.paused){let b=Bs(this.manifestUrlString,2);this.manifestUrlString=ue(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(dr(...lC.map(p=>cr(this.element,p))).pipe(wa(p=>this.element?tt(this.element.buffered,this.element.currentTime*1e3):0),Vl(),nC(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(Vl()).subscribe(m=>Dl(this.element,1))),this.representationSubscription.add(Pa({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(bn(({bufferLength:m,isActiveLowLatency:b})=>b&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(Pa({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(bn(({isLive:m})=>m),wa(m=>({...m})),Vl((m,b)=>b.bufferLength<m.bufferLength),wa(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=Bs(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Pa({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:m,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=m-g,E=1;Math.abs(y)>v&&(E=1+Math.sign(y)*T),Dl(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let b=0;if(m){let T=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var I,A;return(A=(I=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?A:T}))-T}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(Pa({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(oC(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:b})=>{if(lr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Bs(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,A=isFinite(m)?m:b,F=this.isActiveLowLatency$.getValue(),D=T<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(F&&D);let L="none";if(F?L="active_low_latency":this.isLowLatency$.getValue()&&D?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(q=>q.proceedLowLatencyLive()),L="active_low_latency"):v!==0&&A<y?L="live_forward_buffering":A<y+I&&(L="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),L==="live_forward_buffering"||L==="live_with_target_offset"){let q=p-(y+E),O=this.normolizeLiveOffset(Math.trunc(v+q/g)),k=Math.abs(O-v),w;!m||k<=this.tuning.dashCmafLive.offsetCalculationError?w=v:O>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=O:w=0,this.manifestUrlString=ue(this.manifestUrlString,w,2)}L!=="none"&&L!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=dr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(wa(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=dr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(wa(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(dr(this.forceEnded$,Pa({allBuffersFull:l,someBufferEnded:c}).pipe(bn(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:Vt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),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 m;return(m=this.source)==null?void 0:m.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...(0,_l.default)((0,_l.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),Re(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&dy(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=Bl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Vt.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 pn({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=ue(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(...uC.map(e=>cr(this.element,e)),cr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Vt.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&&Mt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,b,g,v,T,y,E,I,A;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=sC(),n=100,o=(m=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(T=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?T: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 F=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(F),(A=this.audioBufferManager)==null||A.maintain(F),i.position=F}this.tracer.log("stallIntervalCallback",Aa(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Bl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Vt.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),Mt(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",Aa({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=aC(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",Aa(t)))}}};var vn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Sn=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 my=`attribute vec2 a_vertex;
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
70
  attribute vec2 a_texel;
71
71
 
72
72
  varying vec2 v_texel;
@@ -77,7 +77,7 @@ void main(void) {
77
77
  // save texel vector to pass to fragment shader
78
78
  v_texel = a_texel;
79
79
  }
80
- `;var fy=`#ifdef GL_ES
80
+ `;var py=`#ifdef GL_ES
81
81
  precision highp float;
82
82
  precision highp int;
83
83
  #else
@@ -120,5 +120,5 @@ void main(void) {
120
120
  // sample using new coordinates
121
121
  gl_FragColor = texture2D(u_texture, tc);
122
122
  }
123
- `;var yn=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 vn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Sn(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(my,this.gl.VERTEX_SHADER),r=this.createShader(fy,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 pC,now as by,Subscription as hC,filter as mC,combine as gy,ValueSubject as vy,isNonNullable as fC}from"@vkontakte/videoplayer-shared/es2018";var Nl=class{constructor(){this.isSeeked$=new vy(!1);this.isBuffering$=new vy(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new hC}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(gy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(mC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(gy({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(pC(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=by(),h=n&&this.currentStallsCount>=n,p=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,m=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(h||p||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,fC(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=by(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Sy=Nl;import{combine as bC,map as gC,observeElementSize as vC,Subscription as SC,ValueSubject as Fl,noop as yC}from"@vkontakte/videoplayer-shared/es2018";var Tn=class{constructor(){this.subscription=new SC;this.pipSize$=new Fl(void 0);this.videoSize$=new Fl(void 0);this.elementSize$=new Fl(void 0);this.pictureInPictureWindowRemoveEventListener=yC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(vC(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(bC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(gC(({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 kC;this.videoState=new $("stopped");this.textTracksManager=new De;this.droppedFramesManager=new Gs;this.stallsManager=new Sy;this.elementSizeManager=new Tn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Vi;this.audioTrackSwitchHistory=new Vi;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 EC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new yn(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=fe(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 gn({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=ve(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:ql.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(yy(c=>!!c.length),Iy()).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(Ul(c=>c.to.state!=="none"),Ra());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ra()),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(yy(Ty),Iy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Ul(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(ge(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ve(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(xC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let m of d.audio){p.push(wl(m));let b=[];for(let g of m.representations){let v=ey(g);b.push(v),this.audioTracksMap.set(v,{stream:m,representation:g})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(kl(p));let m=[];for(let b of p.representations){let g=ZS({...b,streamId:p.id});g&&(m.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,m)}this.params.output.availableVideoStreams$.next(h);for(let p of d.text)for(let m of p.representations){let b=ty(p,m);this.textTracksMap.set(b,{stream:p,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:ql.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(In(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$,AC(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Ey.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,m]=h,b=[...this.videoTracksMap.keys()].find(v=>{var T;return((T=this.videoTracksMap.get(v))==null?void 0:T.representation.id)===p.id});Ty(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,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(o),m){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,v).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ra()).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,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(kl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ra()).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,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(wl(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(Ul(({to:c})=>c==="ready"),Ra());this.subscription.add(In(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(In(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=In(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,wC(["init"])).pipe(PC(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var A,F,D,L,q,O,k,w,H,J,S,R,j;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(A=e.videoTrack.getState())==null?void 0:A.id,n=[...this.videoTracksMap.keys()].find(({id:V})=>V===i),o=t.currentVideoTrack$.getValue(),u=((L=(D=e.videoStream.getState())!=null?D:n&&((F=this.videoTracksMap.get(n))==null?void 0:F.stream))!=null?L:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:V})=>V===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),m=(q=e.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(O=[...this.audioStreamsMap.keys()].find(({id:V})=>V===(m==null?void 0:m.id)))!=null?O:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let V=Us(n,c,(k=this.audioStreamsMap.get(b))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(w=V==null?void 0:V.bitrate)!=null?w:-1/0)}if(o){let V=Us(o,c,(H=this.audioStreamsMap.get(b))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(J=V==null?void 0:V.bitrate)!=null?J:-1/0)}}let v=Lt(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}),T=r?v!=null?v:n:n!=null?n:v,y=b&&Pg(T,c,(S=this.audioStreamsMap.get(b))!=null?S:[],{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=(R=this.videoTracksMap.get(T))==null?void 0:R.representation,I=y&&((j=this.audioTracksMap.get(y))==null?void 0:j.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(){Se(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:ql.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),be(this.video),this.tracer.end()}};var $a=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 xy,interval as RC,map as Py}from"@vkontakte/videoplayer-shared/es2018";var La=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(Py(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(xy({interval:RC(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(xy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Py(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=ry(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var wy=C(Vs(),1);import{assertNever as Ma,assertNonNullable as Ay,debounce as $C,ErrorCategory as En,filter as LC,isNonNullable as MC,isNullable as CC,map as xn,merge as DC,Observable as OC,observableFrom as VC,Subscription as BC,videoSizeToQuality as _C}from"@vkontakte/videoplayer-shared/es2018";var Ge={};var Xr=(a,e)=>new OC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ca=class{constructor(e){this.subscription=new BC;this.videoState=new $("initializing");this.textTracksManager=new De;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:Ma(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ma(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ma(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:Ma(e)}break;default:Ma(t)}};this.video=fe(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),be(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:En.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,wy.default)(import("hls.js").then(i=>{e||(Ge.Hls=i.default,Ge.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Ay(Ge.Hls,"hls.js not loaded"),this.hls=new Ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Ay(Ge.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:En.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=ve(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(ge(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ve(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(xn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Xr(this.hls,Ge.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:En.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(Xr(this.hls,Ge.Events.MANIFEST_PARSED).pipe(xn(({levels:l})=>l.reduce((c,d)=>{var T,y;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(y=Rt((T=d.attrs.QUALITY)!=null?T:""))!=null?y:_C({width:p,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(Xr(this.hls,Ge.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Xr(this.hls,Ge.Events.LEVEL_LOADING).pipe(xn(({url:l})=>ie(l))),t.hostname$),s(Xr(this.hls,Ge.Events.FRAG_CHANGED),l=>{var h,p,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(At(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=Xr(this.hls,Ge.Events.LEVEL_SWITCHED).pipe(xn(({level:l})=>n(this.hls.levels[l])));o.pipe(LC(MC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(At(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(CC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=DC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,VC(["init"])).pipe($C(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 Se(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:En.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 ky="X-Playback-Duration",Hl=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(ky)?parseInt(e.headers.get(ky),10):void 0};import{assertNever as jC,combine as QC,debounce as GC,ErrorCategory as An,filter as WC,filterChanged as YC,isNonNullable as $y,isNullable as wn,map as Ly,merge as zC,observableFrom as KC,Subscription as JC,ValueSubject as Gl,VideoQuality as XC}from"@vkontakte/videoplayer-shared/es2018";var Ql=C(Ko(),1);import{videoSizeToQuality as NC,getExponentialDelay as FC}from"@vkontakte/videoplayer-shared/es2018";var qC=a=>{let e=null;if(a.QUALITY&&(e=Rt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=NC({width:t,height:r})}return e!=null?e:null},UC=(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,Ql.default)(l[1].split(",").map(T=>T.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=qC(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[T,y]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));T&&y&&(g={width:T,height:y})}let v=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,Ql.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,m=d.NAME;h&&p&&i.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},HC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),jl=0,Ry=async(a,e=a,t)=>{let i=await(await lt(a)).text();jl+=1;try{let{qualityManifests:s,textTracks:n}=UC(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(jl<=t.manifestRetryMaxCount)return await HC(FC(jl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ry(a,e,t)}return{qualityManifests:[],textTracks:[]}},Pn=Ry;var Da=class{constructor(e){this.subscription=new JC;this.videoState=new $("stopped");this.textTracksManager=new De;this.manifests$=new Gl([]);this.liveOffset=new ot;this.manifestStartTime$=new Gl(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 jC(t)}};var t;this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:XC.INVARIANT,url:this.params.source.url},Pn(ue(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:An.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:An.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 Gl((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:An.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ve(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(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(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(YC(),Ly(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&&$y(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(QC({startTime:this.manifestStartTime$.pipe(WC($y)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Ly(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=zC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,KC(["init"])).pipe(GC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){var o,u;let e=this.selectManifest();if(wn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max: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=ue(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Hl(n).then(l=>{var c;if(!wn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(wn(d)||!isFinite(d))try{lt(n).then(h=>h.text()).then(h=>{var m;let p=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:m[1];if(p){let b=new URL(p,n).toString();Hl(b).then(g=>{wn(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){Se(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:An.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 ZC,debounce as e0,ErrorCategory as Wl,fromEvent as Yl,isNonNullable as t0,isNullable as r0,map as My,merge as Cy,observableFrom as Dy,Subscription as i0,ValueSubject as a0,VideoQuality as s0,clientChecker as n0}from"@vkontakte/videoplayer-shared/es2018";var Oa=class{constructor(e){this.subscription=new i0;this.videoState=new $("stopped");this.textTracksManager=new De;this.manifests$=new a0([]);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 ZC(t)}};this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:s0.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),Pn(ue(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:Wl.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:Wl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ve(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(My(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ze(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(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&&t0(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(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 m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(My(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)),!n0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Cy(Yl(o,"addtrack"),Yl(o,"removetrack"),Yl(o,"change"),Dy(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Cy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Dy(["init"])).pipe(e0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){var s,n;let e=this.selectManifest();if(r0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Se(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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var _y=C($r(),1),Va=C(Mi(),1);import{assertNever as o0,assertNonNullable as Oy,debounce as u0,ErrorCategory as Vy,isHigher as l0,isHigherOrEqual as c0,isInvariantQuality as By,isLowerOrEqual as d0,isNonNullable as p0,merge as h0,observableFrom as m0,Subscription as f0,map as b0}from"@vkontakte/videoplayer-shared/es2018";var Ba=class{constructor(e){this.subscription=new f0;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new De;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 o0(e)}};this.params=e,this.video=fe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,_y.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,Va.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:Vy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ve(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(b0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ze(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(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&&p0(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=h0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,m0(["init"])).pipe(u0(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),be(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Oy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Oy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ya(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ie(t))}playIfAllowed(){Se(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:Vy.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,Va.default)(this.trackUrls).find(d=>!By(d.track.quality)&&d0(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&&c0(c.quality,u.quality)&&(t=u),!t){let d=(0,Va.default)(this.trackUrls).filter(p=>!By(p.track.quality)&&l0(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Va.default)(this.trackUrls).map(l=>l.track);t=Lt(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 Fy,debounce as y0,merge as qy,observableFrom as T0,Subscription as I0,map as Uy,ValueSubject as E0,ErrorCategory as Kl,VideoQuality as x0}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as g0}from"@vkontakte/videoplayer-shared/es2018";var Ny=["stun:videostun.mycdn.me:80"],v0=1e3,S0=3,zl=()=>null,kn=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:Ny}]};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:g0.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),v0)}normalizeOptions(e={}){let t={stunServerList:Ny,maxRetryNumber:S0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var _a=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new E0(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 Fy(e)}};this.subscription=new I0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=fe(e.container,e.tuning),this.liveStreamClient=new kn(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),be(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Kl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};qy(this.videoState.stateChangeStarted$.pipe(Uy(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Uy(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ve(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(Ve(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(ge(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 Fy(n.to)}},r)).add(qy(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,T0(["init"])).pipe(y0(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:x0.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:Kl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Se(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:Kl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Na=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 qa,assertNonNullable as Bt,ErrorCategory as Rn,filter as Yy,isNonNullable as zy,isNullable as M0,map as C0,merge as D0,once as O0,Subject as Ie,Subscription as Ky,ValueSubject as M,flattenObject as Jy}from"@vkontakte/videoplayer-shared/es2018";import{Observable as P0,map as Hy,Subscription as A0,Subject as w0}from"@vkontakte/videoplayer-shared/es2018";var jy=a=>new P0(e=>{let t=new A0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(Hy(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(Hy(({type:l})=>l!==void 0)),n=new w0,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 k0,Subscription as R0,combine as $0,filter as Gy,once as Wy}from"@vkontakte/videoplayer-shared/es2018";function Qy(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as L0}from"@vkontakte/videoplayer-shared/es2018";var Fa=class Fa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ke;this.subscriptions=new R0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Gy(s=>!!s.type),Wy()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){L0.isSafari&&e!=="MPEG"||this.subscriptions.add($0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Gy(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),Wy()).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=Qy();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:Fa.errorId,category:k0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Fa.errorId} exception`,thrown:e})}};Fa.errorId="VolumeMultiplierManager";var Zr=Fa;var V0={chunkDuration:5e3,maxParallelRequests:5},Ua=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new Ie;this.noAvailableProvidersError$=new Ie;this.volumeMultiplierError$=new Ie;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new Ie,warning$:new Ie,willSeekEvent$:new Ie,soundProhibitedEvent$:new Ie,seekedEvent$:new Ie,loopedEvent$:new Ie,endedEvent$:new Ie,firstBytesEvent$:new Ie,loadedMetadataEvent$:new Ie,firstFrameEvent$:new Ie,canplay$:new Ie,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new Ky;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=Iv([...xv(this.params.tuning),...Ev(this.params.tuning)],this.params.tuning).filter(l=>zy(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Jl.default)(i,l)),...t.filter(l=>(0,Jl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Jy(s)),this.screenFormatsIterator=new Na(s);let n=[...nl(!0),...nl(!1)];this.chromecastFormatsIterator=new Na(n.filter(l=>zy(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Zr.isSupported()&&(this.volumeMultiplierManager=new Zr(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(M0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Rn.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 qa(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 Bt(o),new $a({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new La({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Bt(o),Gr||!this.params.tuning.useHlsJs?new Oa({...n,source:o}):new Ca({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Da({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Ba({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Fg({...n,source:o,config:{...V0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new _a({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 qa(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 Bt(o),new Li({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 qa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return qa(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 qa(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,Zy.default)((0,Xy.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new Ky,t=!1,r=0;return e.add(D0(this.providerOutput.error$.pipe(Yy(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),jy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(C0(i=>({id:`ProviderHangup:${i}`,category:Rn.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(Yy(({to:s})=>s==="playing"),O0()).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===Rn.NETWORK,u=i.category===Rn.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",Jy(n))})),e}};import{fromEvent as $n,once as B0,combine as _0,Subscription as eT,ValueSubject as Xl,map as N0,filter as F0,isNonNullable as Ln,now as $e,safeStorage as Zl}from"@vkontakte/videoplayer-shared/es2018";var q0=5e3,tT="one_video_throughput",rT="one_video_rtt",ht=window.navigator.connection,iT=()=>{let a=ht==null?void 0:ht.downlink;if(Ln(a)&&a!==10)return a*1e3},aT=()=>{let a=ht==null?void 0:ht.rtt;if(Ln(a)&&a!==3e3)return a},sT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},ec=class a{constructor(e){this.subscription=new eT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(tT)||(e.useBrowserEstimation?iT():void 0)||q0,r=(s=(i=a.load(rT))!=null?i:e.useBrowserEstimation?aT():void 0)!=null?s:0;if(this.throughput$=new Xl(t),this.rtt$=new Xl(r),this.rttAdjustedThroughput$=new Xl(sT(t,r,e.rttPenaltyRequestSize)),this.throughput=ur.getSmoothedValue(t,-1,e),this.rtt=ur.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=iT();u&&this.throughput.next(u);let l=aT();Ln(l)&&this.rtt.next(l)};ht&&"onchange"in ht&&this.subscription.add($n(ht,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Zl.set(tT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Zl.set(rT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(_0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(N0(({throughput:n,rtt:o})=>sT(n,o,e.rttPenaltyRequestSize)),F0(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 eT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add($n(e,"progress").pipe(B0()).subscribe(s=>{t=s.loaded,r=$e()}));break;case 1:case 0:i.add($n(e,"loadstart").subscribe(()=>{t=0,r=$e()}));break}i.add($n(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 m=o-s;m&&this.addRawSpeed(n,m,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=Zl.get(e);if(Ln(t))return(r=parseInt(t,10))!=null?r:void 0}},nT=ec;import{fillWithDefault as U0,VideoQuality as Mn}from"@vkontakte/videoplayer-shared/es2018";var oT={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:Mn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Mn.Q_720P,trafficSavingLimit:Mn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Mn.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},uT=a=>{var e;return{...U0(a,oT),configName:[...(e=a.configName)!=null?e:[],...oT.configName]}};import{assertNonNullable as Cn,combine as mt,ErrorCategory as Dn,filter as he,filterChanged as N,fromEvent as rc,isNonNullable as z0,isNullable as K0,Logger as J0,map as B,mapTo as pT,merge as _t,now as On,once as rt,Subject as Q,Subscription as hT,tap as mT,ValueSubject as P,isHigher as X0,isInvariantQuality as fT,flattenObject as Nt,throttle as ic,getTraceSubscriptionMethod as bT,Tracer as Z0,InternalsExposure as eD}from"@vkontakte/videoplayer-shared/es2018";import{merge as H0,map as j0,filter as lT,isNonNullable as Q0}from"@vkontakte/videoplayer-shared/es2018";var tc=({seekState:a,position$:e})=>H0(a.stateChangeEnded$.pipe(j0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),lT(Q0)),e.pipe(lT(()=>a.getState().state==="none")));import{assertNonNullable as G0}from"@vkontakte/videoplayer-shared/es2018";var cT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return G0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as W0,once as Y0}from"@vkontakte/videoplayer-shared/es2018";var dT=(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(W0(i=>i.length>0),Y0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Vn=class{constructor(e={configName:[]},t=Z0.createRootTracer(!1)){this.subscription=new hT;this.logger=new J0;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 $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),isLowLatency:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({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({}),predefinedQualityLimitType$:new P("unknown"),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),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:fg};if(this.initLogs(),this.tuning=uT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new us({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new nT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new eD("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,m)=>{let b=typeof m;return(0,gT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Dn.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",Nt(r)),this.domContainer=cT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new Ua({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&&!qi()?(this.tracer.log("request play from hidden tab"),rc(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){Cn(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(he(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",Nt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.desiredState.autoVideoTrackLimits.startTransitionTo(i),this}setPlaybackRate(e){var r;Cn(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",Nt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return dT(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(K0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return z0(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(_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(B(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Fs({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(he(({from:e})=>e==="stopped"),rt()).subscribe(()=>{this.initedAt=On(),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",Nt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Dn.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",Nt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(B(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(B(n=>n.destination),N()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(mt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(B(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>fT(u)?1:fT(l)?-1:X0(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(N()).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(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(N()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(N()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(N()).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(B(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(mt({hasLiveOffsetByPaused:_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(B(n=>n.to),N(),B(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(mt({atLiveEdge:mt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:tc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(B(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),N(),mT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(B(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(mt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(B(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),N(),mT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(B(n=>n.muted),N()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(B(n=>n.volume),N()).subscribe(this.info.volume$)).add(tc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(_t(e.providerOutput.endedEvent$.pipe(pT(!0)),e.providerOutput.seekedEvent$.pipe(pT(!1))).pipe(N()).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(B(n=>({id:n?`No${n}`:"NoProviders",category:Dn.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(),B(n=>n!=null?n:On()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(rt(),B(()=>On()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(rt(),B(()=>On()-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(he(({to:n})=>n==="playing"),rt()).subscribe(()=>r.next(!1)));let i=0,s=_t(e.providerOutput.isBuffering$,t,r).pipe(B(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),N());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(_t(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(_t(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(B(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 hT;this.subscription.add(t),this.subscription.add(e.current$.pipe(N((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(he(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=Lt(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(_t(this.desiredState.videoTrack.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(B(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;Cn(this.providerContainer),Cn(e),mg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>hg(r)),this.providerContainer.current$.subscribe(({type:r})=>Oi("provider",r)),e.duration$.subscribe(r=>Oi("duration",r)),e.availableVideoTracks$.pipe(he(r=>!!r.length),rt()).subscribe(r=>Oi("tracks",r)),this.events.fatalError$.subscribe(new de("fatalError")),this.events.managedError$.subscribe(new de("managedError")),e.position$.subscribe(new de("position")),e.currentVideoTrack$.pipe(B(r=>r==null?void 0:r.quality)).subscribe(new de("quality")),this.info.currentBuffer$.subscribe(new de("buffer")),e.isBuffering$.subscribe(new de("isBuffering"))].forEach(r=>this.subscription.add(r)),Oi("codecs",Tv())}initTracerSubscription(){let e=bT(this.tracer.log.bind(this.tracer)),t=bT(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(N()).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(mt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(he(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),N((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(he(r=>r>0),N()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(he(r=>r>0),N()).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(mt({currentBuffer:this.info.currentBuffer$.pipe(he(r=>r.end>0),N((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(N())}).pipe(ic(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(N()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(N()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(N()).subscribe(e("canChangePlaybackSpeed"))).add(mt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(he(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),ic(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(N(),he(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(N(),he(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(N()).subscribe(e("muted"))).add(this.info.volume$.pipe(N()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(N(),he(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(mt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(he(({throughputEstimation:r,rtt:i})=>!!r&&!!i),ic(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(N(),he(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:Dn.DOM,message:String(i)})})};this.subscription.add(_t(rc(document,"visibilitychange"),rc(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",Nt({quality:t,availableTracks:Nt(e),track:Nt(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 xz,Observable as Pz,Subject as Az,ValueSubject as wz,VideoQuality as kz}from"@vkontakte/videoplayer-shared/es2018";var Rz=`@vkontakte/videoplayer-core@${_c}`;export{rs as ChromecastState,Un as HttpConnectionType,Pz as Observable,me as PlaybackState,Vn as Player,oi as PredefinedQualityLimits,Rz as SDK_VERSION,Az as Subject,xz as Subscription,Hn as Surface,_c as VERSION,wz as ValueSubject,It as VideoFormat,kz as VideoQuality};
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};