@vkontakte/videoplayer-core 2.0.126-dev.c7a026f6.0 → 2.0.126-dev.e6a91ecc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +12 -12
- package/es2015.esm.js +12 -12
- package/es2018.cjs.js +12 -12
- package/es2018.esm.js +12 -12
- package/esnext.cjs.js +10 -10
- package/esnext.esm.js +12 -12
- package/evergreen.esm.js +4 -4
- package/package.json +2 -2
package/esnext.esm.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.126-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.126-dev.e6a91ecc.0
|
|
3
|
+
* Thu, 20 Mar 2025 14:51:50 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-126/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Ey=Object.create;var ql=Object.defineProperty;var xy=Object.getOwnPropertyDescriptor;var Py=Object.getOwnPropertyNames;var wy=Object.getPrototypeOf,ky=Object.prototype.hasOwnProperty;var h=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Ay=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Py(e))!ky.call(r,a)&&a!==t&&ql(r,a,{get:()=>e[a],enumerable:!(i=xy(e,a))||i.enumerable});return r};var M=(r,e,t)=>(t=r!=null?Ey(wy(r)):{},Ay(e||!r||!r.__esModule?ql(t,"default",{value:r,enumerable:!0}):t,r));var Y=h((En,Hl)=>{"use strict";var er=function(r){return r&&r.Math===Math&&r};Hl.exports=er(typeof globalThis=="object"&&globalThis)||er(typeof window=="object"&&window)||er(typeof self=="object"&&self)||er(typeof global=="object"&&global)||er(typeof En=="object"&&En)||function(){return this}()||Function("return this")()});var ie=h((a0,jl)=>{"use strict";jl.exports=function(r){try{return!!r()}catch{return!0}}});var tr=h((s0,Ql)=>{"use strict";var Ly=ie();Ql.exports=!Ly(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var xn=h((n0,zl)=>{"use strict";var Ry=tr(),Yl=Function.prototype,Gl=Yl.apply,Wl=Yl.call;zl.exports=typeof Reflect=="object"&&Reflect.apply||(Ry?Wl.bind(Gl):function(){return Wl.apply(Gl,arguments)})});var J=h((o0,Jl)=>{"use strict";var Kl=tr(),Xl=Function.prototype,Pn=Xl.call,$y=Kl&&Xl.bind.bind(Pn,Pn);Jl.exports=Kl?$y:function(r){return function(){return Pn.apply(r,arguments)}}});var Ht=h((u0,ec)=>{"use strict";var Zl=J(),My=Zl({}.toString),Dy=Zl("".slice);ec.exports=function(r){return Dy(My(r),8,-1)}});var wn=h((l0,tc)=>{"use strict";var Cy=Ht(),Vy=J();tc.exports=function(r){if(Cy(r)==="Function")return Vy(r)}});var W=h((c0,ic)=>{"use strict";var kn=typeof document=="object"&&document.all;ic.exports=typeof kn>"u"&&kn!==void 0?function(r){return typeof r=="function"||r===kn}:function(r){return typeof r=="function"}});var Ee=h((d0,rc)=>{"use strict";var By=ie();rc.exports=!By(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var xe=h((p0,ac)=>{"use strict";var Oy=tr(),ja=Function.prototype.call;ac.exports=Oy?ja.bind(ja):function(){return ja.apply(ja,arguments)}});var An=h(oc=>{"use strict";var sc={}.propertyIsEnumerable,nc=Object.getOwnPropertyDescriptor,_y=nc&&!sc.call({1:2},1);oc.f=_y?function(e){var t=nc(this,e);return!!t&&t.enumerable}:sc});var ir=h((m0,uc)=>{"use strict";uc.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var cc=h((f0,lc)=>{"use strict";var Ny=J(),Fy=ie(),qy=Ht(),Ln=Object,Uy=Ny("".split);lc.exports=Fy(function(){return!Ln("z").propertyIsEnumerable(0)})?function(r){return qy(r)==="String"?Uy(r,""):Ln(r)}:Ln});var gi=h((b0,dc)=>{"use strict";dc.exports=function(r){return r==null}});var Et=h((g0,pc)=>{"use strict";var Hy=gi(),jy=TypeError;pc.exports=function(r){if(Hy(r))throw new jy("Can't call method on "+r);return r}});var jt=h((v0,hc)=>{"use strict";var Qy=cc(),Gy=Et();hc.exports=function(r){return Qy(Gy(r))}});var Pe=h((S0,mc)=>{"use strict";var Wy=W();mc.exports=function(r){return typeof r=="object"?r!==null:Wy(r)}});var vi=h((y0,fc)=>{"use strict";fc.exports={}});var lt=h((T0,gc)=>{"use strict";var Rn=vi(),$n=Y(),Yy=W(),bc=function(r){return Yy(r)?r:void 0};gc.exports=function(r,e){return arguments.length<2?bc(Rn[r])||bc($n[r]):Rn[r]&&Rn[r][e]||$n[r]&&$n[r][e]}});var rr=h((I0,vc)=>{"use strict";var zy=J();vc.exports=zy({}.isPrototypeOf)});var Qt=h((E0,Tc)=>{"use strict";var Ky=Y(),Sc=Ky.navigator,yc=Sc&&Sc.userAgent;Tc.exports=yc?String(yc):""});var Dn=h((x0,kc)=>{"use strict";var wc=Y(),Mn=Qt(),Ic=wc.process,Ec=wc.Deno,xc=Ic&&Ic.versions||Ec&&Ec.version,Pc=xc&&xc.v8,qe,Qa;Pc&&(qe=Pc.split("."),Qa=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!Qa&&Mn&&(qe=Mn.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=Mn.match(/Chrome\/(\d+)/),qe&&(Qa=+qe[1])));kc.exports=Qa});var Cn=h((P0,Lc)=>{"use strict";var Ac=Dn(),Xy=ie(),Jy=Y(),Zy=Jy.String;Lc.exports=!!Object.getOwnPropertySymbols&&!Xy(function(){var r=Symbol("symbol detection");return!Zy(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&Ac&&Ac<41})});var Vn=h((w0,Rc)=>{"use strict";var eT=Cn();Rc.exports=eT&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Bn=h((k0,$c)=>{"use strict";var tT=lt(),iT=W(),rT=rr(),aT=Vn(),sT=Object;$c.exports=aT?function(r){return typeof r=="symbol"}:function(r){var e=tT("Symbol");return iT(e)&&rT(e.prototype,sT(r))}});var ar=h((A0,Mc)=>{"use strict";var nT=String;Mc.exports=function(r){try{return nT(r)}catch{return"Object"}}});var Ze=h((L0,Dc)=>{"use strict";var oT=W(),uT=ar(),lT=TypeError;Dc.exports=function(r){if(oT(r))return r;throw new lT(uT(r)+" is not a function")}});var sr=h((R0,Cc)=>{"use strict";var cT=Ze(),dT=gi();Cc.exports=function(r,e){var t=r[e];return dT(t)?void 0:cT(t)}});var Bc=h(($0,Vc)=>{"use strict";var On=xe(),_n=W(),Nn=Pe(),pT=TypeError;Vc.exports=function(r,e){var t,i;if(e==="string"&&_n(t=r.toString)&&!Nn(i=On(t,r))||_n(t=r.valueOf)&&!Nn(i=On(t,r))||e!=="string"&&_n(t=r.toString)&&!Nn(i=On(t,r)))return i;throw new pT("Can't convert object to primitive value")}});var Ue=h((M0,Oc)=>{"use strict";Oc.exports=!0});var Fc=h((D0,Nc)=>{"use strict";var _c=Y(),hT=Object.defineProperty;Nc.exports=function(r,e){try{hT(_c,r,{value:e,configurable:!0,writable:!0})}catch{_c[r]=e}return e}});var nr=h((C0,Hc)=>{"use strict";var mT=Ue(),fT=Y(),bT=Fc(),qc="__core-js_shared__",Uc=Hc.exports=fT[qc]||bT(qc,{});(Uc.versions||(Uc.versions=[])).push({version:"3.38.0",mode:mT?"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 Fn=h((V0,Qc)=>{"use strict";var jc=nr();Qc.exports=function(r,e){return jc[r]||(jc[r]=e||{})}});var Si=h((B0,Gc)=>{"use strict";var gT=Et(),vT=Object;Gc.exports=function(r){return vT(gT(r))}});var He=h((O0,Wc)=>{"use strict";var ST=J(),yT=Si(),TT=ST({}.hasOwnProperty);Wc.exports=Object.hasOwn||function(e,t){return TT(yT(e),t)}});var qn=h((_0,Yc)=>{"use strict";var IT=J(),ET=0,xT=Math.random(),PT=IT(1 .toString);Yc.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+PT(++ET+xT,36)}});var re=h((N0,Kc)=>{"use strict";var wT=Y(),kT=Fn(),zc=He(),AT=qn(),LT=Cn(),RT=Vn(),yi=wT.Symbol,Un=kT("wks"),$T=RT?yi.for||yi:yi&&yi.withoutSetter||AT;Kc.exports=function(r){return zc(Un,r)||(Un[r]=LT&&zc(yi,r)?yi[r]:$T("Symbol."+r)),Un[r]}});var ed=h((F0,Zc)=>{"use strict";var MT=xe(),Xc=Pe(),Jc=Bn(),DT=sr(),CT=Bc(),VT=re(),BT=TypeError,OT=VT("toPrimitive");Zc.exports=function(r,e){if(!Xc(r)||Jc(r))return r;var t=DT(r,OT),i;if(t){if(e===void 0&&(e="default"),i=MT(t,r,e),!Xc(i)||Jc(i))return i;throw new BT("Can't convert object to primitive value")}return e===void 0&&(e="number"),CT(r,e)}});var Hn=h((q0,td)=>{"use strict";var _T=ed(),NT=Bn();td.exports=function(r){var e=_T(r,"string");return NT(e)?e:e+""}});var Ga=h((U0,rd)=>{"use strict";var FT=Y(),id=Pe(),jn=FT.document,qT=id(jn)&&id(jn.createElement);rd.exports=function(r){return qT?jn.createElement(r):{}}});var Qn=h((H0,ad)=>{"use strict";var UT=Ee(),HT=ie(),jT=Ga();ad.exports=!UT&&!HT(function(){return Object.defineProperty(jT("div"),"a",{get:function(){return 7}}).a!==7})});var od=h(nd=>{"use strict";var QT=Ee(),GT=xe(),WT=An(),YT=ir(),zT=jt(),KT=Hn(),XT=He(),JT=Qn(),sd=Object.getOwnPropertyDescriptor;nd.f=QT?sd:function(e,t){if(e=zT(e),t=KT(t),JT)try{return sd(e,t)}catch{}if(XT(e,t))return YT(!GT(WT.f,e,t),e[t])}});var Gn=h((Q0,ud)=>{"use strict";var ZT=ie(),eI=W(),tI=/#|\.prototype\./,or=function(r,e){var t=rI[iI(r)];return t===sI?!0:t===aI?!1:eI(e)?ZT(e):!!e},iI=or.normalize=function(r){return String(r).replace(tI,".").toLowerCase()},rI=or.data={},aI=or.NATIVE="N",sI=or.POLYFILL="P";ud.exports=or});var Ti=h((G0,cd)=>{"use strict";var ld=wn(),nI=Ze(),oI=tr(),uI=ld(ld.bind);cd.exports=function(r,e){return nI(r),e===void 0?r:oI?uI(r,e):function(){return r.apply(e,arguments)}}});var Wn=h((W0,dd)=>{"use strict";var lI=Ee(),cI=ie();dd.exports=lI&&cI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var et=h((Y0,pd)=>{"use strict";var dI=Pe(),pI=String,hI=TypeError;pd.exports=function(r){if(dI(r))return r;throw new hI(pI(r)+" is not an object")}});var Gt=h(md=>{"use strict";var mI=Ee(),fI=Qn(),bI=Wn(),Wa=et(),hd=Hn(),gI=TypeError,Yn=Object.defineProperty,vI=Object.getOwnPropertyDescriptor,zn="enumerable",Kn="configurable",Xn="writable";md.f=mI?bI?function(e,t,i){if(Wa(e),t=hd(t),Wa(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Xn in i&&!i[Xn]){var a=vI(e,t);a&&a[Xn]&&(e[t]=i.value,i={configurable:Kn in i?i[Kn]:a[Kn],enumerable:zn in i?i[zn]:a[zn],writable:!1})}return Yn(e,t,i)}:Yn:function(e,t,i){if(Wa(e),t=hd(t),Wa(i),fI)try{return Yn(e,t,i)}catch{}if("get"in i||"set"in i)throw new gI("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ii=h((K0,fd)=>{"use strict";var SI=Ee(),yI=Gt(),TI=ir();fd.exports=SI?function(r,e,t){return yI.f(r,e,TI(1,t))}:function(r,e,t){return r[e]=t,r}});var K=h((X0,gd)=>{"use strict";var ur=Y(),II=xn(),EI=wn(),xI=W(),PI=od().f,wI=Gn(),Ei=vi(),kI=Ti(),xi=Ii(),bd=He();nr();var AI=function(r){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new r;case 1:return new r(t);case 2:return new r(t,i)}return new r(t,i,a)}return II(r,this,arguments)};return e.prototype=r.prototype,e};gd.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?ur:a?ur[t]:ur[t]&&ur[t].prototype,o=i?Ei:Ei[t]||xi(Ei,t,{})[t],u=o.prototype,l,d,c,p,m,f,b,g,S;for(p in e)l=wI(i?p:t+(a?".":"#")+p,r.forced),d=!l&&n&&bd(n,p),f=o[p],d&&(r.dontCallGetSet?(S=PI(n,p),b=S&&S.value):b=n[p]),m=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof m)&&(r.bind&&d?g=kI(m,ur):r.wrap&&d?g=AI(m):s&&xI(m)?g=EI(m):g=m,(r.sham||m&&m.sham||f&&f.sham)&&xi(g,"sham",!0),xi(o,p,g),s&&(c=t+"Prototype",bd(Ei,c)||xi(Ei,c,{}),xi(Ei[c],p,m),r.real&&u&&(l||!u[p])&&xi(u,p,m)))}});var Sd=h((J0,vd)=>{"use strict";var LI=Math.ceil,RI=Math.floor;vd.exports=Math.trunc||function(e){var t=+e;return(t>0?RI:LI)(t)}});var lr=h((Z0,yd)=>{"use strict";var $I=Sd();yd.exports=function(r){var e=+r;return e!==e||e===0?0:$I(e)}});var Id=h((eC,Td)=>{"use strict";var MI=lr(),DI=Math.max,CI=Math.min;Td.exports=function(r,e){var t=MI(r);return t<0?DI(t+e,0):CI(t,e)}});var Jn=h((tC,Ed)=>{"use strict";var VI=lr(),BI=Math.min;Ed.exports=function(r){var e=VI(r);return e>0?BI(e,9007199254740991):0}});var Pi=h((iC,xd)=>{"use strict";var OI=Jn();xd.exports=function(r){return OI(r.length)}});var Zn=h((rC,wd)=>{"use strict";var _I=jt(),NI=Id(),FI=Pi(),Pd=function(r){return function(e,t,i){var a=_I(e),s=FI(a);if(s===0)return!r&&-1;var n=NI(i,s),o;if(r&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((r||n in a)&&a[n]===t)return r||n||0;return!r&&-1}};wd.exports={includes:Pd(!0),indexOf:Pd(!1)}});var cr=h((aC,kd)=>{"use strict";kd.exports=function(){}});var Ad=h(()=>{"use strict";var qI=K(),UI=Zn().includes,HI=ie(),jI=cr(),QI=HI(function(){return!Array(1).includes()});qI({target:"Array",proto:!0,forced:QI},{includes:function(e){return UI(this,e,arguments.length>1?arguments[1]:void 0)}});jI("includes")});var xt=h((oC,Ld)=>{"use strict";var GI=lt();Ld.exports=GI});var $d=h((uC,Rd)=>{"use strict";Ad();var WI=xt();Rd.exports=WI("Array","includes")});var Dd=h((lC,Md)=>{"use strict";var YI=$d();Md.exports=YI});var je=h((cC,Cd)=>{"use strict";var zI=Dd();Cd.exports=zI});var Ka=h((IC,Ud)=>{"use strict";var rE=Fn(),aE=qn(),qd=rE("keys");Ud.exports=function(r){return qd[r]||(qd[r]=aE(r))}});var jd=h((EC,Hd)=>{"use strict";var sE=ie();Hd.exports=!sE(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var Xa=h((xC,Gd)=>{"use strict";var nE=He(),oE=W(),uE=Si(),lE=Ka(),cE=jd(),Qd=lE("IE_PROTO"),io=Object,dE=io.prototype;Gd.exports=cE?io.getPrototypeOf:function(r){var e=uE(r);if(nE(e,Qd))return e[Qd];var t=e.constructor;return oE(t)&&e instanceof t?t.prototype:e instanceof io?dE:null}});var Ja=h((PC,Wd)=>{"use strict";Wd.exports={}});var Kd=h((wC,zd)=>{"use strict";var pE=J(),ro=He(),hE=jt(),mE=Zn().indexOf,fE=Ja(),Yd=pE([].push);zd.exports=function(r,e){var t=hE(r),i=0,a=[],s;for(s in t)!ro(fE,s)&&ro(t,s)&&Yd(a,s);for(;e.length>i;)ro(t,s=e[i++])&&(~mE(a,s)||Yd(a,s));return a}});var ao=h((kC,Xd)=>{"use strict";Xd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var so=h((AC,Jd)=>{"use strict";var bE=Kd(),gE=ao();Jd.exports=Object.keys||function(e){return bE(e,gE)}});var no=h((LC,rp)=>{"use strict";var ep=Ee(),vE=ie(),tp=J(),SE=Xa(),yE=so(),TE=jt(),IE=An().f,ip=tp(IE),EE=tp([].push),xE=ep&&vE(function(){var r=Object.create(null);return r[2]=2,!ip(r,2)}),Zd=function(r){return function(e){for(var t=TE(e),i=yE(t),a=xE&&SE(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!ep||(a?u in t:ip(t,u)))&&EE(o,r?[u,t[u]]:t[u]);return o}};rp.exports={entries:Zd(!0),values:Zd(!1)}});var ap=h(()=>{"use strict";var PE=K(),wE=no().entries;PE({target:"Object",stat:!0},{entries:function(e){return wE(e)}})});var np=h((MC,sp)=>{"use strict";ap();var kE=vi();sp.exports=kE.Object.entries});var up=h((DC,op)=>{"use strict";var AE=np();op.exports=AE});var wi=h((CC,lp)=>{"use strict";var LE=up();lp.exports=LE});var Wt=h((VC,cp)=>{"use strict";cp.exports={}});var hp=h((BC,pp)=>{"use strict";var RE=Y(),$E=W(),dp=RE.WeakMap;pp.exports=$E(dp)&&/native code/.test(String(dp))});var co=h((OC,bp)=>{"use strict";var ME=hp(),fp=Y(),DE=Pe(),CE=Ii(),oo=He(),uo=nr(),VE=Ka(),BE=Ja(),mp="Object already initialized",lo=fp.TypeError,OE=fp.WeakMap,Za,dr,es,_E=function(r){return es(r)?dr(r):Za(r,{})},NE=function(r){return function(e){var t;if(!DE(e)||(t=dr(e)).type!==r)throw new lo("Incompatible receiver, "+r+" required");return t}};ME||uo.state?(Qe=uo.state||(uo.state=new OE),Qe.get=Qe.get,Qe.has=Qe.has,Qe.set=Qe.set,Za=function(r,e){if(Qe.has(r))throw new lo(mp);return e.facade=r,Qe.set(r,e),e},dr=function(r){return Qe.get(r)||{}},es=function(r){return Qe.has(r)}):(Yt=VE("state"),BE[Yt]=!0,Za=function(r,e){if(oo(r,Yt))throw new lo(mp);return e.facade=r,CE(r,Yt,e),e},dr=function(r){return oo(r,Yt)?r[Yt]:{}},es=function(r){return oo(r,Yt)});var Qe,Yt;bp.exports={set:Za,get:dr,has:es,enforce:_E,getterFor:NE}});var mo=h((_C,vp)=>{"use strict";var po=Ee(),FE=He(),gp=Function.prototype,qE=po&&Object.getOwnPropertyDescriptor,ho=FE(gp,"name"),UE=ho&&function(){}.name==="something",HE=ho&&(!po||po&&qE(gp,"name").configurable);vp.exports={EXISTS:ho,PROPER:UE,CONFIGURABLE:HE}});var yp=h(Sp=>{"use strict";var jE=Ee(),QE=Wn(),GE=Gt(),WE=et(),YE=jt(),zE=so();Sp.f=jE&&!QE?Object.defineProperties:function(e,t){WE(e);for(var i=YE(t),a=zE(t),s=a.length,n=0,o;s>n;)GE.f(e,o=a[n++],i[o]);return e}});var fo=h((FC,Tp)=>{"use strict";var KE=lt();Tp.exports=KE("document","documentElement")});var So=h((qC,Ap)=>{"use strict";var XE=et(),JE=yp(),Ip=ao(),ZE=Ja(),ex=fo(),tx=Ga(),ix=Ka(),Ep=">",xp="<",go="prototype",vo="script",wp=ix("IE_PROTO"),bo=function(){},kp=function(r){return xp+vo+Ep+r+xp+"/"+vo+Ep},Pp=function(r){r.write(kp("")),r.close();var e=r.parentWindow.Object;return r=null,e},rx=function(){var r=tx("iframe"),e="java"+vo+":",t;return r.style.display="none",ex.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(kp("document.F=Object")),t.close(),t.F},ts,is=function(){try{ts=new ActiveXObject("htmlfile")}catch{}is=typeof document<"u"?document.domain&&ts?Pp(ts):rx():Pp(ts);for(var r=Ip.length;r--;)delete is[go][Ip[r]];return is()};ZE[wp]=!0;Ap.exports=Object.create||function(e,t){var i;return e!==null?(bo[go]=XE(e),i=new bo,bo[go]=null,i[wp]=e):i=is(),t===void 0?i:JE.f(i,t)}});var ki=h((UC,Lp)=>{"use strict";var ax=Ii();Lp.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:ax(r,e,t),r}});var Eo=h((HC,Mp)=>{"use strict";var sx=ie(),nx=W(),ox=Pe(),ux=So(),Rp=Xa(),lx=ki(),cx=re(),dx=Ue(),Io=cx("iterator"),$p=!1,ct,yo,To;[].keys&&(To=[].keys(),"next"in To?(yo=Rp(Rp(To)),yo!==Object.prototype&&(ct=yo)):$p=!0);var px=!ox(ct)||sx(function(){var r={};return ct[Io].call(r)!==r});px?ct={}:dx&&(ct=ux(ct));nx(ct[Io])||lx(ct,Io,function(){return this});Mp.exports={IteratorPrototype:ct,BUGGY_SAFARI_ITERATORS:$p}});var rs=h((jC,Cp)=>{"use strict";var hx=re(),mx=hx("toStringTag"),Dp={};Dp[mx]="z";Cp.exports=String(Dp)==="[object z]"});var pr=h((QC,Vp)=>{"use strict";var fx=rs(),bx=W(),as=Ht(),gx=re(),vx=gx("toStringTag"),Sx=Object,yx=as(function(){return arguments}())==="Arguments",Tx=function(r,e){try{return r[e]}catch{}};Vp.exports=fx?as:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=Tx(e=Sx(r),vx))=="string"?t:yx?as(e):(i=as(e))==="Object"&&bx(e.callee)?"Arguments":i}});var Op=h((GC,Bp)=>{"use strict";var Ix=rs(),Ex=pr();Bp.exports=Ix?{}.toString:function(){return"[object "+Ex(this)+"]"}});var hr=h((WC,Np)=>{"use strict";var xx=rs(),Px=Gt().f,wx=Ii(),kx=He(),Ax=Op(),Lx=re(),_p=Lx("toStringTag");Np.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(kx(a,_p)||Px(a,_p,{configurable:!0,value:e}),i&&!xx&&wx(a,"toString",Ax))}});var qp=h((YC,Fp)=>{"use strict";var Rx=Eo().IteratorPrototype,$x=So(),Mx=ir(),Dx=hr(),Cx=Wt(),Vx=function(){return this};Fp.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=$x(Rx,{next:Mx(+!i,t)}),Dx(r,a,!1,!0),Cx[a]=Vx,r}});var Hp=h((zC,Up)=>{"use strict";var Bx=J(),Ox=Ze();Up.exports=function(r,e,t){try{return Bx(Ox(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var Qp=h((KC,jp)=>{"use strict";var _x=Pe();jp.exports=function(r){return _x(r)||r===null}});var Wp=h((XC,Gp)=>{"use strict";var Nx=Qp(),Fx=String,qx=TypeError;Gp.exports=function(r){if(Nx(r))return r;throw new qx("Can't set "+Fx(r)+" as a prototype")}});var xo=h((JC,Yp)=>{"use strict";var Ux=Hp(),Hx=Pe(),jx=Et(),Qx=Wp();Yp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=Ux(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return jx(a),Qx(s),Hx(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var sh=h((ZC,ah)=>{"use strict";var Gx=K(),Wx=xe(),ss=Ue(),ih=mo(),Yx=W(),zx=qp(),zp=Xa(),Kp=xo(),Kx=hr(),Xx=Ii(),Po=ki(),Jx=re(),Xp=Wt(),rh=Eo(),Zx=ih.PROPER,eP=ih.CONFIGURABLE,Jp=rh.IteratorPrototype,ns=rh.BUGGY_SAFARI_ITERATORS,mr=Jx("iterator"),Zp="keys",fr="values",eh="entries",th=function(){return this};ah.exports=function(r,e,t,i,a,s,n){zx(t,e,i);var o=function(S){if(S===a&&p)return p;if(!ns&&S&&S in d)return d[S];switch(S){case Zp:return function(){return new t(this,S)};case fr:return function(){return new t(this,S)};case eh:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=r.prototype,c=d[mr]||d["@@iterator"]||a&&d[a],p=!ns&&c||o(a),m=e==="Array"&&d.entries||c,f,b,g;if(m&&(f=zp(m.call(new r)),f!==Object.prototype&&f.next&&(!ss&&zp(f)!==Jp&&(Kp?Kp(f,Jp):Yx(f[mr])||Po(f,mr,th)),Kx(f,u,!0,!0),ss&&(Xp[u]=th))),Zx&&a===fr&&c&&c.name!==fr&&(!ss&&eP?Xx(d,"name",fr):(l=!0,p=function(){return Wx(c,this)})),a)if(b={values:o(fr),keys:s?p:o(Zp),entries:o(eh)},n)for(g in b)(ns||l||!(g in d))&&Po(d,g,b[g]);else Gx({target:e,proto:!0,forced:ns||l},b);return(!ss||n)&&d[mr]!==p&&Po(d,mr,p,{name:a}),Xp[e]=p,b}});var oh=h((eV,nh)=>{"use strict";nh.exports=function(r,e){return{value:r,done:e}}});var ko=h((tV,ph)=>{"use strict";var tP=jt(),wo=cr(),uh=Wt(),ch=co(),iP=Gt().f,rP=sh(),os=oh(),aP=Ue(),sP=Ee(),dh="Array Iterator",nP=ch.set,oP=ch.getterFor(dh);ph.exports=rP(Array,"Array",function(r,e){nP(this,{type:dh,target:tP(r),index:0,kind:e})},function(){var r=oP(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,os(void 0,!0);switch(r.kind){case"keys":return os(t,!1);case"values":return os(e[t],!1)}return os([t,e[t]],!1)},"values");var lh=uh.Arguments=uh.Array;wo("keys");wo("values");wo("entries");if(!aP&&sP&&lh.name!=="values")try{iP(lh,"name",{value:"values"})}catch{}});var mh=h((iV,hh)=>{"use strict";var uP=re(),lP=Wt(),cP=uP("iterator"),dP=Array.prototype;hh.exports=function(r){return r!==void 0&&(lP.Array===r||dP[cP]===r)}});var Ao=h((rV,bh)=>{"use strict";var pP=pr(),fh=sr(),hP=gi(),mP=Wt(),fP=re(),bP=fP("iterator");bh.exports=function(r){if(!hP(r))return fh(r,bP)||fh(r,"@@iterator")||mP[pP(r)]}});var vh=h((aV,gh)=>{"use strict";var gP=xe(),vP=Ze(),SP=et(),yP=ar(),TP=Ao(),IP=TypeError;gh.exports=function(r,e){var t=arguments.length<2?TP(r):e;if(vP(t))return SP(gP(t,r));throw new IP(yP(r)+" is not iterable")}});var Th=h((sV,yh)=>{"use strict";var EP=xe(),Sh=et(),xP=sr();yh.exports=function(r,e,t){var i,a;Sh(r);try{if(i=xP(r,"return"),!i){if(e==="throw")throw t;return t}i=EP(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return Sh(i),t}});var ls=h((nV,Ph)=>{"use strict";var PP=Ti(),wP=xe(),kP=et(),AP=ar(),LP=mh(),RP=Pi(),Ih=rr(),$P=vh(),MP=Ao(),Eh=Th(),DP=TypeError,us=function(r,e){this.stopped=r,this.result=e},xh=us.prototype;Ph.exports=function(r,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=PP(e,i),l,d,c,p,m,f,b,g=function(w){return l&&Eh(l,"normal",w),new us(!0,w)},S=function(w){return a?(kP(w),o?u(w[0],w[1],g):u(w[0],w[1])):o?u(w,g):u(w)};if(s)l=r.iterator;else if(n)l=r;else{if(d=MP(r),!d)throw new DP(AP(r)+" is not iterable");if(LP(d)){for(c=0,p=RP(r);p>c;c++)if(m=S(r[c]),m&&Ih(xh,m))return m;return new us(!1)}l=$P(r,d)}for(f=s?r.next:l.next;!(b=wP(f,l)).done;){try{m=S(b.value)}catch(w){Eh(l,"throw",w)}if(typeof m=="object"&&m&&Ih(xh,m))return m}return new us(!1)}});var kh=h((oV,wh)=>{"use strict";var CP=Ee(),VP=Gt(),BP=ir();wh.exports=function(r,e,t){CP?VP.f(r,e,BP(0,t)):r[e]=t}});var Ah=h(()=>{"use strict";var OP=K(),_P=ls(),NP=kh();OP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return _P(e,function(i,a){NP(t,i,a)},{AS_ENTRIES:!0}),t}})});var Rh=h((cV,Lh)=>{"use strict";ko();Ah();var FP=vi();Lh.exports=FP.Object.fromEntries});var Mh=h((dV,$h)=>{"use strict";$h.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 Ch=h(()=>{"use strict";ko();var qP=Mh(),UP=Y(),HP=hr(),Dh=Wt();for(cs in qP)HP(UP[cs],cs),Dh[cs]=Dh.Array;var cs});var Bh=h((mV,Vh)=>{"use strict";var jP=Rh();Ch();Vh.exports=jP});var Lo=h((fV,Oh)=>{"use strict";var QP=Bh();Oh.exports=QP});var _h=h(()=>{"use strict"});var Ro=h((vV,Nh)=>{"use strict";var br=Y(),GP=Qt(),WP=Ht(),ds=function(r){return GP.slice(0,r.length)===r};Nh.exports=function(){return ds("Bun/")?"BUN":ds("Cloudflare-Workers")?"CLOUDFLARE":ds("Deno/")?"DENO":ds("Node.js/")?"NODE":br.Bun&&typeof Bun.version=="string"?"BUN":br.Deno&&typeof Deno.version=="object"?"DENO":WP(br.process)==="process"?"NODE":br.window&&br.document?"BROWSER":"REST"}()});var ps=h((SV,Fh)=>{"use strict";var YP=Ro();Fh.exports=YP==="NODE"});var Uh=h((yV,qh)=>{"use strict";var zP=Gt();qh.exports=function(r,e,t){return zP.f(r,e,t)}});var Qh=h((TV,jh)=>{"use strict";var KP=lt(),XP=Uh(),JP=re(),ZP=Ee(),Hh=JP("species");jh.exports=function(r){var e=KP(r);ZP&&e&&!e[Hh]&&XP(e,Hh,{configurable:!0,get:function(){return this}})}});var Wh=h((IV,Gh)=>{"use strict";var ew=rr(),tw=TypeError;Gh.exports=function(r,e){if(ew(e,r))return r;throw new tw("Incorrect invocation")}});var Mo=h((EV,Yh)=>{"use strict";var iw=J(),rw=W(),$o=nr(),aw=iw(Function.toString);rw($o.inspectSource)||($o.inspectSource=function(r){return aw(r)});Yh.exports=$o.inspectSource});var Co=h((xV,Zh)=>{"use strict";var sw=J(),nw=ie(),zh=W(),ow=pr(),uw=lt(),lw=Mo(),Kh=function(){},Xh=uw("Reflect","construct"),Do=/^\s*(?:class|function)\b/,cw=sw(Do.exec),dw=!Do.test(Kh),gr=function(e){if(!zh(e))return!1;try{return Xh(Kh,[],e),!0}catch{return!1}},Jh=function(e){if(!zh(e))return!1;switch(ow(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return dw||!!cw(Do,lw(e))}catch{return!0}};Jh.sham=!0;Zh.exports=!Xh||nw(function(){var r;return gr(gr.call)||!gr(Object)||!gr(function(){r=!0})||r})?Jh:gr});var tm=h((PV,em)=>{"use strict";var pw=Co(),hw=ar(),mw=TypeError;em.exports=function(r){if(pw(r))return r;throw new mw(hw(r)+" is not a constructor")}});var Vo=h((wV,rm)=>{"use strict";var im=et(),fw=tm(),bw=gi(),gw=re(),vw=gw("species");rm.exports=function(r,e){var t=im(r).constructor,i;return t===void 0||bw(i=im(t)[vw])?e:fw(i)}});var sm=h((kV,am)=>{"use strict";var Sw=J();am.exports=Sw([].slice)});var om=h((AV,nm)=>{"use strict";var yw=TypeError;nm.exports=function(r,e){if(r<e)throw new yw("Not enough arguments");return r}});var Bo=h((LV,um)=>{"use strict";var Tw=Qt();um.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Tw)});var Qo=h((RV,gm)=>{"use strict";var we=Y(),Iw=xn(),Ew=Ti(),lm=W(),xw=He(),bm=ie(),cm=fo(),Pw=sm(),dm=Ga(),ww=om(),kw=Bo(),Aw=ps(),Uo=we.setImmediate,Ho=we.clearImmediate,Lw=we.process,Oo=we.Dispatch,Rw=we.Function,pm=we.MessageChannel,$w=we.String,_o=0,vr={},hm="onreadystatechange",Sr,zt,No,Fo;bm(function(){Sr=we.location});var jo=function(r){if(xw(vr,r)){var e=vr[r];delete vr[r],e()}},qo=function(r){return function(){jo(r)}},mm=function(r){jo(r.data)},fm=function(r){we.postMessage($w(r),Sr.protocol+"//"+Sr.host)};(!Uo||!Ho)&&(Uo=function(e){ww(arguments.length,1);var t=lm(e)?e:Rw(e),i=Pw(arguments,1);return vr[++_o]=function(){Iw(t,void 0,i)},zt(_o),_o},Ho=function(e){delete vr[e]},Aw?zt=function(r){Lw.nextTick(qo(r))}:Oo&&Oo.now?zt=function(r){Oo.now(qo(r))}:pm&&!kw?(No=new pm,Fo=No.port2,No.port1.onmessage=mm,zt=Ew(Fo.postMessage,Fo)):we.addEventListener&&lm(we.postMessage)&&!we.importScripts&&Sr&&Sr.protocol!=="file:"&&!bm(fm)?(zt=fm,we.addEventListener("message",mm,!1)):hm in dm("script")?zt=function(r){cm.appendChild(dm("script"))[hm]=function(){cm.removeChild(this),jo(r)}}:zt=function(r){setTimeout(qo(r),0)});gm.exports={set:Uo,clear:Ho}});var ym=h(($V,Sm)=>{"use strict";var vm=Y(),Mw=Ee(),Dw=Object.getOwnPropertyDescriptor;Sm.exports=function(r){if(!Mw)return vm[r];var e=Dw(vm,r);return e&&e.value}});var Go=h((MV,Im)=>{"use strict";var Tm=function(){this.head=null,this.tail=null};Tm.prototype={add:function(r){var e={item:r,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var r=this.head;if(r){var e=this.head=r.next;return e===null&&(this.tail=null),r.item}}};Im.exports=Tm});var xm=h((DV,Em)=>{"use strict";var Cw=Qt();Em.exports=/ipad|iphone|ipod/i.test(Cw)&&typeof Pebble<"u"});var wm=h((CV,Pm)=>{"use strict";var Vw=Qt();Pm.exports=/web0s(?!.*chrome)/i.test(Vw)});var Dm=h((VV,Mm)=>{"use strict";var Li=Y(),Bw=ym(),km=Ti(),Wo=Qo().set,Ow=Go(),_w=Bo(),Nw=xm(),Fw=wm(),Yo=ps(),Am=Li.MutationObserver||Li.WebKitMutationObserver,Lm=Li.document,Rm=Li.process,hs=Li.Promise,Xo=Bw("queueMicrotask"),Ai,zo,Ko,ms,$m;Xo||(yr=new Ow,Tr=function(){var r,e;for(Yo&&(r=Rm.domain)&&r.exit();e=yr.get();)try{e()}catch(t){throw yr.head&&Ai(),t}r&&r.enter()},!_w&&!Yo&&!Fw&&Am&&Lm?(zo=!0,Ko=Lm.createTextNode(""),new Am(Tr).observe(Ko,{characterData:!0}),Ai=function(){Ko.data=zo=!zo}):!Nw&&hs&&hs.resolve?(ms=hs.resolve(void 0),ms.constructor=hs,$m=km(ms.then,ms),Ai=function(){$m(Tr)}):Yo?Ai=function(){Rm.nextTick(Tr)}:(Wo=km(Wo,Li),Ai=function(){Wo(Tr)}),Xo=function(r){yr.head||Ai(),yr.add(r)});var yr,Tr;Mm.exports=Xo});var Vm=h((BV,Cm)=>{"use strict";Cm.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var fs=h((OV,Bm)=>{"use strict";Bm.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var Kt=h((_V,Om)=>{"use strict";var qw=Y();Om.exports=qw.Promise});var Ri=h((NV,qm)=>{"use strict";var Uw=Y(),Ir=Kt(),Hw=W(),jw=Gn(),Qw=Mo(),Gw=re(),_m=Ro(),Ww=Ue(),Jo=Dn(),Nm=Ir&&Ir.prototype,Yw=Gw("species"),Zo=!1,Fm=Hw(Uw.PromiseRejectionEvent),zw=jw("Promise",function(){var r=Qw(Ir),e=r!==String(Ir);if(!e&&Jo===66||Ww&&!(Nm.catch&&Nm.finally))return!0;if(!Jo||Jo<51||!/native code/.test(r)){var t=new Ir(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Yw]=i,Zo=t.then(function(){})instanceof i,!Zo)return!0}return!e&&(_m==="BROWSER"||_m==="DENO")&&!Fm});qm.exports={CONSTRUCTOR:zw,REJECTION_EVENT:Fm,SUBCLASSING:Zo}});var $i=h((FV,Hm)=>{"use strict";var Um=Ze(),Kw=TypeError,Xw=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new Kw("Bad Promise constructor");e=i,t=a}),this.resolve=Um(e),this.reject=Um(t)};Hm.exports.f=function(r){return new Xw(r)}});var lf=h(()=>{"use strict";var Jw=K(),Zw=Ue(),Ss=ps(),Pt=Y(),Vi=xe(),jm=ki(),Qm=xo(),ek=hr(),tk=Qh(),ik=Ze(),vs=W(),rk=Pe(),ak=Wh(),sk=Vo(),Km=Qo().set,au=Dm(),nk=Vm(),ok=fs(),uk=Go(),Xm=co(),ys=Kt(),su=Ri(),Jm=$i(),Ts="Promise",Zm=su.CONSTRUCTOR,lk=su.REJECTION_EVENT,ck=su.SUBCLASSING,eu=Xm.getterFor(Ts),dk=Xm.set,Mi=ys&&ys.prototype,Xt=ys,bs=Mi,ef=Pt.TypeError,tu=Pt.document,nu=Pt.process,iu=Jm.f,pk=iu,hk=!!(tu&&tu.createEvent&&Pt.dispatchEvent),tf="unhandledrejection",mk="rejectionhandled",Gm=0,rf=1,fk=2,ou=1,af=2,gs,Wm,bk,Ym,sf=function(r){var e;return rk(r)&&vs(e=r.then)?e:!1},nf=function(r,e){var t=e.value,i=e.state===rf,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,u,l,d;try{a?(i||(e.rejection===af&&vk(e),e.rejection=ou),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),d=!0)),u===r.promise?n(new ef("Promise-chain cycle")):(l=sf(u))?Vi(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},of=function(r,e){r.notified||(r.notified=!0,au(function(){for(var t=r.reactions,i;i=t.get();)nf(i,r);r.notified=!1,e&&!r.rejection&&gk(r)}))},uf=function(r,e,t){var i,a;hk?(i=tu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),Pt.dispatchEvent(i)):i={promise:e,reason:t},!lk&&(a=Pt["on"+r])?a(i):r===tf&&nk("Unhandled promise rejection",t)},gk=function(r){Vi(Km,Pt,function(){var e=r.facade,t=r.value,i=zm(r),a;if(i&&(a=ok(function(){Ss?nu.emit("unhandledRejection",t,e):uf(tf,e,t)}),r.rejection=Ss||zm(r)?af:ou,a.error))throw a.value})},zm=function(r){return r.rejection!==ou&&!r.parent},vk=function(r){Vi(Km,Pt,function(){var e=r.facade;Ss?nu.emit("rejectionHandled",e):uf(mk,e,r.value)})},Di=function(r,e,t){return function(i){r(e,i,t)}},Ci=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=fk,of(r,!0))},ru=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new ef("Promise can't be resolved itself");var i=sf(e);i?au(function(){var a={done:!1};try{Vi(i,e,Di(ru,a,r),Di(Ci,a,r))}catch(s){Ci(a,s,r)}}):(r.value=e,r.state=rf,of(r,!1))}catch(a){Ci({done:!1},a,r)}}};if(Zm&&(Xt=function(e){ak(this,bs),ik(e),Vi(gs,this);var t=eu(this);try{e(Di(ru,t),Di(Ci,t))}catch(i){Ci(t,i)}},bs=Xt.prototype,gs=function(e){dk(this,{type:Ts,done:!1,notified:!1,parent:!1,reactions:new uk,rejection:!1,state:Gm,value:void 0})},gs.prototype=jm(bs,"then",function(e,t){var i=eu(this),a=iu(sk(this,Xt));return i.parent=!0,a.ok=vs(e)?e:!0,a.fail=vs(t)&&t,a.domain=Ss?nu.domain:void 0,i.state===Gm?i.reactions.add(a):au(function(){nf(a,i)}),a.promise}),Wm=function(){var r=new gs,e=eu(r);this.promise=r,this.resolve=Di(ru,e),this.reject=Di(Ci,e)},Jm.f=iu=function(r){return r===Xt||r===bk?new Wm(r):pk(r)},!Zw&&vs(ys)&&Mi!==Object.prototype)){Ym=Mi.then,ck||jm(Mi,"then",function(e,t){var i=this;return new Xt(function(a,s){Vi(Ym,i,a,s)}).then(e,t)},{unsafe:!0});try{delete Mi.constructor}catch{}Qm&&Qm(Mi,bs)}Jw({global:!0,constructor:!0,wrap:!0,forced:Zm},{Promise:Xt});ek(Xt,Ts,!1,!0);tk(Ts)});var mf=h((HV,hf)=>{"use strict";var Sk=re(),df=Sk("iterator"),pf=!1;try{cf=0,uu={next:function(){return{done:!!cf++}},return:function(){pf=!0}},uu[df]=function(){return this},Array.from(uu,function(){throw 2})}catch{}var cf,uu;hf.exports=function(r,e){try{if(!e&&!pf)return!1}catch{return!1}var t=!1;try{var i={};i[df]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var lu=h((jV,ff)=>{"use strict";var yk=Kt(),Tk=mf(),Ik=Ri().CONSTRUCTOR;ff.exports=Ik||!Tk(function(r){yk.all(r).then(void 0,function(){})})});var bf=h(()=>{"use strict";var Ek=K(),xk=xe(),Pk=Ze(),wk=$i(),kk=fs(),Ak=ls(),Lk=lu();Ek({target:"Promise",stat:!0,forced:Lk},{all:function(e){var t=this,i=wk.f(t),a=i.resolve,s=i.reject,n=kk(function(){var o=Pk(t.resolve),u=[],l=0,d=1;Ak(e,function(c){var p=l++,m=!1;d++,xk(o,t,c).then(function(f){m||(m=!0,u[p]=f,--d||a(u))},s)}),--d||a(u)});return n.error&&s(n.value),i.promise}})});var vf=h(()=>{"use strict";var Rk=K(),$k=Ue(),Mk=Ri().CONSTRUCTOR,du=Kt(),Dk=lt(),Ck=W(),Vk=ki(),gf=du&&du.prototype;Rk({target:"Promise",proto:!0,forced:Mk,real:!0},{catch:function(r){return this.then(void 0,r)}});!$k&&Ck(du)&&(cu=Dk("Promise").prototype.catch,gf.catch!==cu&&Vk(gf,"catch",cu,{unsafe:!0}));var cu});var Sf=h(()=>{"use strict";var Bk=K(),Ok=xe(),_k=Ze(),Nk=$i(),Fk=fs(),qk=ls(),Uk=lu();Bk({target:"Promise",stat:!0,forced:Uk},{race:function(e){var t=this,i=Nk.f(t),a=i.reject,s=Fk(function(){var n=_k(t.resolve);qk(e,function(o){Ok(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var yf=h(()=>{"use strict";var Hk=K(),jk=$i(),Qk=Ri().CONSTRUCTOR;Hk({target:"Promise",stat:!0,forced:Qk},{reject:function(e){var t=jk.f(this),i=t.reject;return i(e),t.promise}})});var pu=h((ZV,Tf)=>{"use strict";var Gk=et(),Wk=Pe(),Yk=$i();Tf.exports=function(r,e){if(Gk(r),Wk(e)&&e.constructor===r)return e;var t=Yk.f(r),i=t.resolve;return i(e),t.promise}});var xf=h(()=>{"use strict";var zk=K(),Kk=lt(),If=Ue(),Xk=Kt(),Ef=Ri().CONSTRUCTOR,Jk=pu(),Zk=Kk("Promise"),eA=If&&!Ef;zk({target:"Promise",stat:!0,forced:If||Ef},{resolve:function(e){return Jk(eA&&this===Zk?Xk:this,e)}})});var Pf=h(()=>{"use strict";lf();bf();vf();Sf();yf();xf()});var Lf=h(()=>{"use strict";var tA=K(),iA=Ue(),Is=Kt(),rA=ie(),kf=lt(),Af=W(),aA=Vo(),wf=pu(),sA=ki(),mu=Is&&Is.prototype,nA=!!Is&&rA(function(){mu.finally.call({then:function(){}},function(){})});tA({target:"Promise",proto:!0,real:!0,forced:nA},{finally:function(r){var e=aA(this,kf("Promise")),t=Af(r);return this.then(t?function(i){return wf(e,r()).then(function(){return i})}:r,t?function(i){return wf(e,r()).then(function(){throw i})}:r)}});!iA&&Af(Is)&&(hu=kf("Promise").prototype.finally,mu.finally!==hu&&sA(mu,"finally",hu,{unsafe:!0}));var hu});var $f=h((nB,Rf)=>{"use strict";_h();Pf();Lf();var oA=xt();Rf.exports=oA("Promise","finally")});var Df=h((oB,Mf)=>{"use strict";var uA=$f();Mf.exports=uA});var Es=h((uB,Cf)=>{"use strict";var lA=Df();Cf.exports=lA});var Wf=h(()=>{"use strict";var EA=K(),xA=no().values;EA({target:"Object",stat:!0},{values:function(e){return xA(e)}})});var zf=h((GB,Yf)=>{"use strict";Wf();var PA=vi();Yf.exports=PA.Object.values});var Xf=h((WB,Kf)=>{"use strict";var wA=zf();Kf.exports=wA});var Oi=h((YB,Jf)=>{"use strict";var kA=Xf();Jf.exports=kA});var db=h(()=>{"use strict";var HA=K(),jA=Si(),QA=Pi(),GA=lr(),WA=cr();HA({target:"Array",proto:!0},{at:function(e){var t=jA(this),i=QA(t),a=GA(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});WA("at")});var hb=h((IO,pb)=>{"use strict";db();var YA=xt();pb.exports=YA("Array","at")});var fb=h((EO,mb)=>{"use strict";var zA=hb();mb.exports=zA});var Rt=h((xO,bb)=>{"use strict";var KA=fb();bb.exports=KA});var Ou=h((oN,Xb)=>{"use strict";var DL=Ht();Xb.exports=Array.isArray||function(e){return DL(e)==="Array"}});var Zb=h((uN,Jb)=>{"use strict";var CL=TypeError,VL=9007199254740991;Jb.exports=function(r){if(r>VL)throw CL("Maximum allowed index exceeded");return r}});var ig=h((lN,tg)=>{"use strict";var BL=Ou(),OL=Pi(),_L=Zb(),NL=Ti(),eg=function(r,e,t,i,a,s,n,o){for(var u=a,l=0,d=n?NL(n,o):!1,c,p;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&BL(c)?(p=OL(c),u=eg(r,e,c,p,u,s-1)-1):(_L(u+1),r[u]=c),u++),l++;return u};tg.exports=eg});var ng=h((cN,sg)=>{"use strict";var rg=Ou(),FL=Co(),qL=Pe(),UL=re(),HL=UL("species"),ag=Array;sg.exports=function(r){var e;return rg(r)&&(e=r.constructor,FL(e)&&(e===ag||rg(e.prototype))?e=void 0:qL(e)&&(e=e[HL],e===null&&(e=void 0))),e===void 0?ag:e}});var ug=h((dN,og)=>{"use strict";var jL=ng();og.exports=function(r,e){return new(jL(r))(e===0?0:e)}});var lg=h(()=>{"use strict";var QL=K(),GL=ig(),WL=Ze(),YL=Si(),zL=Pi(),KL=ug();QL({target:"Array",proto:!0},{flatMap:function(e){var t=YL(this),i=zL(t),a;return WL(e),a=KL(t,0),a.length=GL(a,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var cg=h(()=>{"use strict";var XL=cr();XL("flatMap")});var pg=h((bN,dg)=>{"use strict";lg();cg();var JL=xt();dg.exports=JL("Array","flatMap")});var mg=h((gN,hg)=>{"use strict";var ZL=pg();hg.exports=ZL});var _u=h((vN,fg)=>{"use strict";var eR=mg();fg.exports=eR});var _r=h((AN,Pg)=>{"use strict";var uR=pr(),lR=String;Pg.exports=function(r){if(uR(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return lR(r)}});var Fu=h((LN,wg)=>{"use strict";wg.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 Lg=h((RN,Ag)=>{"use strict";var cR=J(),dR=Et(),pR=_r(),Uu=Fu(),kg=cR("".replace),hR=RegExp("^["+Uu+"]+"),mR=RegExp("(^|[^"+Uu+"])["+Uu+"]+$"),qu=function(r){return function(e){var t=pR(dR(e));return r&1&&(t=kg(t,hR,"")),r&2&&(t=kg(t,mR,"$1")),t}};Ag.exports={start:qu(1),end:qu(2),trim:qu(3)}});var Dg=h(($N,Mg)=>{"use strict";var fR=mo().PROPER,bR=ie(),Rg=Fu(),$g="\u200B\x85\u180E";Mg.exports=function(r){return bR(function(){return!!Rg[r]()||$g[r]()!==$g||fR&&Rg[r].name!==r})}});var Hu=h((MN,Cg)=>{"use strict";var gR=Lg().start,vR=Dg();Cg.exports=vR("trimStart")?function(){return gR(this)}:"".trimStart});var Bg=h(()=>{"use strict";var SR=K(),Vg=Hu();SR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Vg},{trimLeft:Vg})});var _g=h(()=>{"use strict";Bg();var yR=K(),Og=Hu();yR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Og},{trimStart:Og})});var Fg=h((ON,Ng)=>{"use strict";_g();var TR=xt();Ng.exports=TR("String","trimLeft")});var Ug=h((_N,qg)=>{"use strict";var IR=Fg();qg.exports=IR});var jg=h((NN,Hg)=>{"use strict";var ER=Ug();Hg.exports=ER});var nv=h(()=>{"use strict"});var ov=h(()=>{"use strict"});var lv=h((vU,uv)=>{"use strict";var GR=Pe(),WR=Ht(),YR=re(),zR=YR("match");uv.exports=function(r){var e;return GR(r)&&((e=r[zR])!==void 0?!!e:WR(r)==="RegExp")}});var dv=h((SU,cv)=>{"use strict";var KR=et();cv.exports=function(){var r=KR(this),e="";return r.hasIndices&&(e+="d"),r.global&&(e+="g"),r.ignoreCase&&(e+="i"),r.multiline&&(e+="m"),r.dotAll&&(e+="s"),r.unicode&&(e+="u"),r.unicodeSets&&(e+="v"),r.sticky&&(e+="y"),e}});var mv=h((yU,hv)=>{"use strict";var XR=xe(),JR=He(),ZR=rr(),e$=dv(),pv=RegExp.prototype;hv.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in pv)&&!JR(r,"flags")&&ZR(pv,r)?XR(e$,r):e}});var bv=h((TU,fv)=>{"use strict";var Ju=J(),t$=Si(),i$=Math.floor,Ku=Ju("".charAt),r$=Ju("".replace),Xu=Ju("".slice),a$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,s$=/\$([$&'`]|\d{1,2})/g;fv.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,u=s$;return a!==void 0&&(a=t$(a),u=a$),r$(s,u,function(l,d){var c;switch(Ku(d,0)){case"$":return"$";case"&":return r;case"`":return Xu(e,0,t);case"'":return Xu(e,n);case"<":c=a[Xu(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var m=i$(p/10);return m===0?l:m<=o?i[m-1]===void 0?Ku(d,1):i[m-1]+Ku(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var Sv=h(()=>{"use strict";var n$=K(),o$=xe(),el=J(),gv=Et(),u$=W(),l$=gi(),c$=lv(),ji=_r(),d$=sr(),p$=mv(),h$=bv(),m$=re(),f$=Ue(),b$=m$("replace"),g$=TypeError,Zu=el("".indexOf),v$=el("".replace),vv=el("".slice),S$=Math.max;n$({target:"String",proto:!0},{replaceAll:function(e,t){var i=gv(this),a,s,n,o,u,l,d,c,p,m,f=0,b="";if(!l$(e)){if(a=c$(e),a&&(s=ji(gv(p$(e))),!~Zu(s,"g")))throw new g$("`.replaceAll` does not allow non-global regexes");if(n=d$(e,b$),n)return o$(n,e,i,t);if(f$&&a)return v$(ji(i),e,t)}for(o=ji(i),u=ji(e),l=u$(t),l||(t=ji(t)),d=u.length,c=S$(1,d),p=Zu(o,u);p!==-1;)m=l?ji(t(u,p,o)):h$(u,o,p,[],void 0,t),b+=vv(o,f,p)+m,f=p+d,p=p+c>o.length?-1:Zu(o,u,p+c);return f<o.length&&(b+=vv(o,f)),b}})});var Tv=h((xU,yv)=>{"use strict";nv();ov();Sv();var y$=xt();yv.exports=y$("String","replaceAll")});var Ev=h((PU,Iv)=>{"use strict";var T$=Tv();Iv.exports=T$});var Pv=h((wU,xv)=>{"use strict";var I$=Ev();xv.exports=I$});var kv=h((kU,wv)=>{"use strict";var E$=lr(),x$=_r(),P$=Et(),w$=RangeError;wv.exports=function(e){var t=x$(P$(this)),i="",a=E$(e);if(a<0||a===1/0)throw new w$("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(i+=t);return i}});var Mv=h((AU,$v)=>{"use strict";var Rv=J(),k$=Jn(),Av=_r(),A$=kv(),L$=Et(),R$=Rv(A$),$$=Rv("".slice),M$=Math.ceil,Lv=function(r){return function(e,t,i){var a=Av(L$(e)),s=k$(t),n=a.length,o=i===void 0?" ":Av(i),u,l;return s<=n||o===""?a:(u=s-n,l=R$(o,M$(u/o.length)),l.length>u&&(l=$$(l,0,u)),r?a+l:l+a)}};$v.exports={start:Lv(!1),end:Lv(!0)}});var Cv=h((LU,Dv)=>{"use strict";var D$=Qt();Dv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(D$)});var Vv=h(()=>{"use strict";var C$=K(),V$=Mv().start,B$=Cv();C$({target:"String",proto:!0,forced:B$},{padStart:function(e){return V$(this,e,arguments.length>1?arguments[1]:void 0)}})});var Ov=h((MU,Bv)=>{"use strict";Vv();var O$=xt();Bv.exports=O$("String","padStart")});var Nv=h((DU,_v)=>{"use strict";var _$=Ov();_v.exports=_$});var qv=h((CU,Fv)=>{"use strict";var N$=Nv();Fv.exports=N$});var Ul="2.0.126-dev.c7a026f6.0";var he=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(he||{}),It=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(It||{});var Ua=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ua||{}),Tn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Tn||{});var In=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(In||{}),Ha=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ha||{});var vy=M(je(),1);import{assertNever as Fd,assertNonNullable as KI,isNonNullable as Ya,ValueSubject as eo,Subject as XI,Subscription as JI,merge as ZI,observableFrom as eE,fromEvent as Bd,map as Od,tap as _d,filterChanged as tE,isNullable as to,ErrorCategory as Nd}from"@vkontakte/videoplayer-shared";var Vd=r=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e(),i.onerror=a=>t(a),document.body.appendChild(i)});var za=class{constructor(e){this.connection$=new eo(void 0);this.castState$=new eo("NOT_AVAILABLE");this.errorEvent$=new XI;this.realCastState$=new eo("NOT_AVAILABLE");this.subscription=new JI;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Ya(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},a||Vd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Nd.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ya(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();to(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();to(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Bd(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.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 Fd(a.sessionState)}})).add(ZI(Bd(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_d(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Od(a=>a.castState)),eE([i.getCastState()])).pipe(tE(),Od(iE),_d(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ya(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();KI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(to(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Ya(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Nd.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},iE=r=>{switch(r){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 Fd(r)}};var Dl=M(je(),1),ZS=M(wi(),1),ey=M(Lo(),1);var jf=M(Es(),1);import{assertNever as Vf}from"@vkontakte/videoplayer-shared";var ae=(r,e=0,t=0)=>{switch(t){case 0:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return r;let i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Vf(t)}return r},xs=(r,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:Vf(e)}};var T=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};import{isNonNullable as cA,Subject as Ps,merge as Bf}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Ps;this.transitionEnded$=new Ps;this.transitionUpdated$=new Ps;this.forceChanged$=new Ps;this.stateChangeStarted$=Bf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Bf(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||cA(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as dA}from"@vkontakte/videoplayer-shared";var Of=r=>{switch(r){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 dA(r)}};import{assertNever as Bi,assertNonNullable as Jt,debounce as _f,ErrorCategory as Nf,fromEvent as Zt,isNonNullable as Ff,map as qf,merge as Uf,observableFrom as pA,Subject as hA,Subscription as fu,timeout as mA,getHighestQuality as fA}from"@vkontakte/videoplayer-shared";var bA=5,gA=5,vA=500,Hf=7e3,Er=class{constructor(e){this.subscription=new fu;this.loadMediaTimeoutSubscription=new fu;this.videoState=new $("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Bi(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:Bi(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:Bi(e)}break}default:Bi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Of(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 fu;this.subscription.add(e),this.subscription.add(Uf(this.videoState.stateChangeStarted$.pipe(qf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(qf(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new hA;e.add(a.pipe(_f(vA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Zt(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)>bA)&&a.next(o),s=o})),e.add(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.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<gA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:Bi(n)}}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let i=Uf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pA(["init"])).pipe(_f(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&T(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,a,s;switch(e){case"MPEG":{let l=t[e];Jt(l);let d=fA(Object.keys(l));Jt(d);let c=l[d];Jt(c),i=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Jt(l),i=l.url,a="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 l=t[e];Jt(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Jt(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Jt(l),i=ae(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Nf.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Bi(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Ff(o)&&(n.metadata.title=o),Ff(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(mA(Hf).subscribe(()=>s(`timeout(${Hf})`)))});(0,jf.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Nf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Vu=M(je(),1);import{clearVideoElement as Gf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as SA}from"@vkontakte/videoplayer-shared";var Qf=r=>{try{r.pause(),r.playbackRate=0,SA(r),r.remove()}catch(e){console.error(e)}};import{fromEvent as yA,Subscription as TA}from"@vkontakte/videoplayer-shared";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)}},gu=window.WeakMap?new WeakMap:new bu,vu=window.WeakMap?new WeakMap:new Map,IA=(r,e=20)=>{let t=0;return yA(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},me=(r,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=r.querySelector("video"),a=!!i;i?Gf(i):(i=document.createElement("video"),r.appendChild(i)),gu.set(i,a);let s=new TA;return s.add(IA(i,e)),vu.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},fe=r=>{vu.get(r)?.unsubscribe(),vu.delete(r);let t=gu.get(r);gu.delete(r),t?Gf(r):Qf(r)};var yu=M(Oi(),1);import{assertNonNullable as xr,isNonNullable as it,isNullable as RA,fromEvent as _i,merge as Zf,observableFrom as eb,filterChanged as tb,map as Pr,Subject as ib,Subscription as $A,ValueSubject as MA,ErrorCategory as DA}from"@vkontakte/videoplayer-shared";import{isNonNullable as Su,isNullable as AA,Subscription as LA}from"@vkontakte/videoplayer-shared";var ws=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),u=AA(a),l=new LA;return a&&l.add(a.subscribe(d=>{let c=r.getState();i(d,c)&&r.setState(d)},s)),i(o,n)||(t(n),u&&r.setState(n)),l.add(r.stateChangeStarted$.subscribe(d=>{t(d.to),u&&r.setState(d.to)},s)),l},tt=(r,e,t)=>ws(e,()=>r.loop,i=>{Su(i)&&(r.loop=i)},{onError:t}),be=(r,e,t,i)=>ws(e,()=>({muted:r.muted,volume:r.volume}),a=>{Su(a)&&(r.muted=a.muted,r.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:i}),De=(r,e,t,i)=>ws(e,()=>r.playbackRate,a=>{Su(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),wt=ws;var CA=r=>["__",r.language,r.label].join("|"),VA=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},Tu=class r{constructor(e){this.available$=new ib;this.current$=new MA(void 0);this.error$=new ib;this.subscription=new $A;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:DA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(wt(t.internalTextTracks,()=>(0,yu.default)(this.internalTracks),s=>{it(s)&&this.setInternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Pr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(wt(t.externalTextTracks,()=>(0,yu.default)(this.externalTracks),s=>{it(s)&&this.setExternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Pr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),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:a})),this.subscription.add(wt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){xr(this.video);let{textTracks:e}=this.video;this.subscription.add(_i(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Zf(_i(e,"addtrack"),_i(e,"removetrack"),eb(["init"])).pipe(Pr(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),tb((i,a)=>i.length===a.length&&i.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Zf(_i(e,"change"),eb(["init"])).pipe(Pr(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Pr(i=>i&&this.htmlTextTrackToITextTrack(i).id),tb()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(_i(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};i.track?.addEventListener("cuechange",a)})),this.subscription.add(_i(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let a=i;it(t.align)&&(a.align=t.align),it(t.position)&&(a.position=t.position),it(t.size)&&(a.size=t.size),it(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){xr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(r.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,a=e.id?e.id:CA(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:a,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){xr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(RA(e)||!VA(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){xr(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){xr(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ce=Tu;var pt=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 rb=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Iu=r=>{let e=rb(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},ab=r=>{let e=rb(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};import{fromEvent as Ve,map as kt,merge as nb,filterChanged as OA,isNonNullable as ob,Subject as _A,filter as ub,mapTo as lb,combine as NA,once as FA,ErrorCategory as qA,ValueSubject as cb,clientChecker as UA}from"@vkontakte/videoplayer-shared";var BA=3,sb=(r,e,t=BA)=>{let i=0,a=0;for(let s=0;s<r.length;s++){let n=r.start(s),o=r.end(s);if(n<=e&&e<=o){if(i=n,a=o,!t)return{from:i,to:a};for(let u=s-1;u>=0;u--)r.end(u)+t>=i&&(i=r.start(u));for(let u=s+1;u<r.length;u++)r.start(u)-t<=a&&(a=r.end(u))}}return{from:i,to:a}};var ge=r=>{let e=x=>Ve(r,x).pipe(lb(void 0)),i=nb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>Ve(r,x))).pipe(kt(x=>x.type==="ended"?r.readyState<2:r.readyState<3),OA()),a=nb(Ve(r,"progress"),Ve(r,"timeupdate")).pipe(kt(()=>sb(r.buffered,r.currentTime))),s=UA.isSafari?NA({play:e("play").pipe(FA()),playing:e("playing")}).pipe(lb(void 0)):e("playing"),n=Ve(r,"volumechange").pipe(kt(()=>({muted:r.muted,volume:r.volume}))),o=Ve(r,"ratechange").pipe(kt(()=>r.playbackRate)),u=Ve(r,"error").pipe(ub(()=>!!(r.error||r.played.length)),kt(()=>{let x=r.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:qA.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:r.error??void 0}})),l=Ve(r,"timeupdate").pipe(kt(()=>r.currentTime)),d=new _A,c=.3,p;l.subscribe(x=>{r.loop&&ob(p)&&ob(x)&&p>=r.duration-c&&x<=c&&d.next(p),p=x});let m=e("pause").pipe(ub(()=>!r.error&&p!==r.duration)),f=Ve(r,"enterpictureinpicture"),b=Ve(r,"leavepictureinpicture"),g=new cb(ab(r));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new cb(Iu(r));return Ve(r,"fullscreenchange").pipe(kt(()=>Iu(r))).subscribe(S),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ve(r,"durationchange").pipe(kt(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b}};import{VideoQuality as At}from"@vkontakte/videoplayer-shared";var Lt=r=>{switch(r){case"mobile":return At.Q_144P;case"lowest":return At.Q_240P;case"low":return At.Q_360P;case"sd":case"medium":return At.Q_480P;case"hd":case"high":return At.Q_720P;case"fullhd":case"full":return At.Q_1080P;case"quadhd":case"quad":return At.Q_1440P;case"ultrahd":case"ultra":return At.Q_2160P}};var $t=M(Rt(),1),wb=M(je(),1),Ls=M(wi(),1);import{isNonNullable as ke,isNullable as Ib,now as kb,isHigher as Eb,isHigherOrEqual as wu,isInvariantQuality as xb,isLowerOrEqual as ku,videoSizeToQuality as ZA,assertNotEmptyArray as Ab,assertNonNullable as eL}from"@vkontakte/videoplayer-shared";var Eu=!1,ht={},gb=r=>{Eu=r},vb=()=>{ht={}},Sb=r=>{r(ht)},wr=(r,e)=>{Eu&&(ht.meta=ht.meta??{},ht.meta[r]=e)},le=class{constructor(e){this.name=e}next(e){if(!Eu)return;ht.series=ht.series??{};let t=ht.series[this.name]??[];t.push([Date.now(),e]),ht.series[this.name]=t}};import{isHigher as XA,isHigherOrEqual as RO,isLower as yb,isLowerOrEqual as $O,isNonNullable as ks,isNullable as JA,videoHeightToQuality as As}from"@vkontakte/videoplayer-shared";function xu({limits:r,highQualityLimit:e,trafficSavingLimit:t}){return!r.max&&r.min===e?"high_quality":!r.min&&r.max===t?"traffic_saving":"unknown"}function Pu({limits:r,highQualityLimit:e,trafficSavingLimit:t}){return!!r&&xu({limits:r,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function kr({limits:r,highestAvailableQuality:e,lowestAvailableQuality:t}){return JA(r)||ks(r.min)&&ks(r.max)&&yb(r.max,r.min)||ks(r.min)&&e&&XA(r.min,e)||ks(r.max)&&t&&yb(r.max,t)}function Tb({limits:r,highestAvailableHeight:e,lowestAvailableHeight:t}){return kr({limits:{max:r?.max?As(r.max):void 0,min:r?.min?As(r.min):void 0},highestAvailableQuality:e?As(e):void 0,lowestAvailableQuality:t?As(t):void 0})}var tL=new le("best_bitrate"),Lb=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var Au=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),Ar=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=kb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Rb='Assertion "ABR Tracks is empty array" failed',Rs=(r,e,t,i)=>{let a=[...e].sort(Au(1)),s=[...t].sort(Au(1)),n=s.filter(u=>ke(u.bitrate)&&ke(r.bitrate)?r.bitrate/u.bitrate>i:!0),o=(0,$t.default)(s,Math.round(s.length*a.indexOf(r)/(a.length+1)))??(0,$t.default)(s,-1);return o&&(0,wb.default)(n,o)?o:n.length?(0,$t.default)(n,-1):(0,$t.default)(s,0)},Pb=r=>"quality"in r,$b=(r,e,t,i)=>{let a=ke(i?.last?.bitrate)&&ke(t?.bitrate)&&i.last.bitrate<t.bitrate?r.trackCooldownIncreaseQuality:r.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&kb()-i.history[t.id]<=a&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=Pb(n)?"video":"audio",u=Pb(n)?n.quality:n.bitrate;return e({message:`
|
|
6
|
+
var Ey=Object.create;var ql=Object.defineProperty;var xy=Object.getOwnPropertyDescriptor;var Py=Object.getOwnPropertyNames;var ky=Object.getPrototypeOf,wy=Object.prototype.hasOwnProperty;var h=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Ay=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Py(e))!wy.call(r,a)&&a!==t&&ql(r,a,{get:()=>e[a],enumerable:!(i=xy(e,a))||i.enumerable});return r};var M=(r,e,t)=>(t=r!=null?Ey(ky(r)):{},Ay(e||!r||!r.__esModule?ql(t,"default",{value:r,enumerable:!0}):t,r));var Y=h((En,Hl)=>{"use strict";var er=function(r){return r&&r.Math===Math&&r};Hl.exports=er(typeof globalThis=="object"&&globalThis)||er(typeof window=="object"&&window)||er(typeof self=="object"&&self)||er(typeof global=="object"&&global)||er(typeof En=="object"&&En)||function(){return this}()||Function("return this")()});var ie=h((aC,jl)=>{"use strict";jl.exports=function(r){try{return!!r()}catch{return!0}}});var tr=h((sC,Ql)=>{"use strict";var Ly=ie();Ql.exports=!Ly(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var xn=h((nC,zl)=>{"use strict";var Ry=tr(),Yl=Function.prototype,Gl=Yl.apply,Wl=Yl.call;zl.exports=typeof Reflect=="object"&&Reflect.apply||(Ry?Wl.bind(Gl):function(){return Wl.apply(Gl,arguments)})});var J=h((oC,Jl)=>{"use strict";var Kl=tr(),Xl=Function.prototype,Pn=Xl.call,$y=Kl&&Xl.bind.bind(Pn,Pn);Jl.exports=Kl?$y:function(r){return function(){return Pn.apply(r,arguments)}}});var Ht=h((uC,ec)=>{"use strict";var Zl=J(),My=Zl({}.toString),Dy=Zl("".slice);ec.exports=function(r){return Dy(My(r),8,-1)}});var kn=h((lC,tc)=>{"use strict";var Cy=Ht(),Vy=J();tc.exports=function(r){if(Cy(r)==="Function")return Vy(r)}});var W=h((cC,ic)=>{"use strict";var wn=typeof document=="object"&&document.all;ic.exports=typeof wn>"u"&&wn!==void 0?function(r){return typeof r=="function"||r===wn}:function(r){return typeof r=="function"}});var Ee=h((dC,rc)=>{"use strict";var By=ie();rc.exports=!By(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var xe=h((pC,ac)=>{"use strict";var Oy=tr(),ja=Function.prototype.call;ac.exports=Oy?ja.bind(ja):function(){return ja.apply(ja,arguments)}});var An=h(oc=>{"use strict";var sc={}.propertyIsEnumerable,nc=Object.getOwnPropertyDescriptor,_y=nc&&!sc.call({1:2},1);oc.f=_y?function(e){var t=nc(this,e);return!!t&&t.enumerable}:sc});var ir=h((mC,uc)=>{"use strict";uc.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var cc=h((fC,lc)=>{"use strict";var Ny=J(),Fy=ie(),qy=Ht(),Ln=Object,Uy=Ny("".split);lc.exports=Fy(function(){return!Ln("z").propertyIsEnumerable(0)})?function(r){return qy(r)==="String"?Uy(r,""):Ln(r)}:Ln});var gi=h((bC,dc)=>{"use strict";dc.exports=function(r){return r==null}});var Et=h((gC,pc)=>{"use strict";var Hy=gi(),jy=TypeError;pc.exports=function(r){if(Hy(r))throw new jy("Can't call method on "+r);return r}});var jt=h((vC,hc)=>{"use strict";var Qy=cc(),Gy=Et();hc.exports=function(r){return Qy(Gy(r))}});var Pe=h((SC,mc)=>{"use strict";var Wy=W();mc.exports=function(r){return typeof r=="object"?r!==null:Wy(r)}});var vi=h((yC,fc)=>{"use strict";fc.exports={}});var lt=h((TC,gc)=>{"use strict";var Rn=vi(),$n=Y(),Yy=W(),bc=function(r){return Yy(r)?r:void 0};gc.exports=function(r,e){return arguments.length<2?bc(Rn[r])||bc($n[r]):Rn[r]&&Rn[r][e]||$n[r]&&$n[r][e]}});var rr=h((IC,vc)=>{"use strict";var zy=J();vc.exports=zy({}.isPrototypeOf)});var Qt=h((EC,Tc)=>{"use strict";var Ky=Y(),Sc=Ky.navigator,yc=Sc&&Sc.userAgent;Tc.exports=yc?String(yc):""});var Dn=h((xC,wc)=>{"use strict";var kc=Y(),Mn=Qt(),Ic=kc.process,Ec=kc.Deno,xc=Ic&&Ic.versions||Ec&&Ec.version,Pc=xc&&xc.v8,qe,Qa;Pc&&(qe=Pc.split("."),Qa=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!Qa&&Mn&&(qe=Mn.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=Mn.match(/Chrome\/(\d+)/),qe&&(Qa=+qe[1])));wc.exports=Qa});var Cn=h((PC,Lc)=>{"use strict";var Ac=Dn(),Xy=ie(),Jy=Y(),Zy=Jy.String;Lc.exports=!!Object.getOwnPropertySymbols&&!Xy(function(){var r=Symbol("symbol detection");return!Zy(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&Ac&&Ac<41})});var Vn=h((kC,Rc)=>{"use strict";var eT=Cn();Rc.exports=eT&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Bn=h((wC,$c)=>{"use strict";var tT=lt(),iT=W(),rT=rr(),aT=Vn(),sT=Object;$c.exports=aT?function(r){return typeof r=="symbol"}:function(r){var e=tT("Symbol");return iT(e)&&rT(e.prototype,sT(r))}});var ar=h((AC,Mc)=>{"use strict";var nT=String;Mc.exports=function(r){try{return nT(r)}catch{return"Object"}}});var Ze=h((LC,Dc)=>{"use strict";var oT=W(),uT=ar(),lT=TypeError;Dc.exports=function(r){if(oT(r))return r;throw new lT(uT(r)+" is not a function")}});var sr=h((RC,Cc)=>{"use strict";var cT=Ze(),dT=gi();Cc.exports=function(r,e){var t=r[e];return dT(t)?void 0:cT(t)}});var Bc=h(($C,Vc)=>{"use strict";var On=xe(),_n=W(),Nn=Pe(),pT=TypeError;Vc.exports=function(r,e){var t,i;if(e==="string"&&_n(t=r.toString)&&!Nn(i=On(t,r))||_n(t=r.valueOf)&&!Nn(i=On(t,r))||e!=="string"&&_n(t=r.toString)&&!Nn(i=On(t,r)))return i;throw new pT("Can't convert object to primitive value")}});var Ue=h((MC,Oc)=>{"use strict";Oc.exports=!0});var Fc=h((DC,Nc)=>{"use strict";var _c=Y(),hT=Object.defineProperty;Nc.exports=function(r,e){try{hT(_c,r,{value:e,configurable:!0,writable:!0})}catch{_c[r]=e}return e}});var nr=h((CC,Hc)=>{"use strict";var mT=Ue(),fT=Y(),bT=Fc(),qc="__core-js_shared__",Uc=Hc.exports=fT[qc]||bT(qc,{});(Uc.versions||(Uc.versions=[])).push({version:"3.38.0",mode:mT?"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 Fn=h((VC,Qc)=>{"use strict";var jc=nr();Qc.exports=function(r,e){return jc[r]||(jc[r]=e||{})}});var Si=h((BC,Gc)=>{"use strict";var gT=Et(),vT=Object;Gc.exports=function(r){return vT(gT(r))}});var He=h((OC,Wc)=>{"use strict";var ST=J(),yT=Si(),TT=ST({}.hasOwnProperty);Wc.exports=Object.hasOwn||function(e,t){return TT(yT(e),t)}});var qn=h((_C,Yc)=>{"use strict";var IT=J(),ET=0,xT=Math.random(),PT=IT(1 .toString);Yc.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+PT(++ET+xT,36)}});var re=h((NC,Kc)=>{"use strict";var kT=Y(),wT=Fn(),zc=He(),AT=qn(),LT=Cn(),RT=Vn(),yi=kT.Symbol,Un=wT("wks"),$T=RT?yi.for||yi:yi&&yi.withoutSetter||AT;Kc.exports=function(r){return zc(Un,r)||(Un[r]=LT&&zc(yi,r)?yi[r]:$T("Symbol."+r)),Un[r]}});var ed=h((FC,Zc)=>{"use strict";var MT=xe(),Xc=Pe(),Jc=Bn(),DT=sr(),CT=Bc(),VT=re(),BT=TypeError,OT=VT("toPrimitive");Zc.exports=function(r,e){if(!Xc(r)||Jc(r))return r;var t=DT(r,OT),i;if(t){if(e===void 0&&(e="default"),i=MT(t,r,e),!Xc(i)||Jc(i))return i;throw new BT("Can't convert object to primitive value")}return e===void 0&&(e="number"),CT(r,e)}});var Hn=h((qC,td)=>{"use strict";var _T=ed(),NT=Bn();td.exports=function(r){var e=_T(r,"string");return NT(e)?e:e+""}});var Ga=h((UC,rd)=>{"use strict";var FT=Y(),id=Pe(),jn=FT.document,qT=id(jn)&&id(jn.createElement);rd.exports=function(r){return qT?jn.createElement(r):{}}});var Qn=h((HC,ad)=>{"use strict";var UT=Ee(),HT=ie(),jT=Ga();ad.exports=!UT&&!HT(function(){return Object.defineProperty(jT("div"),"a",{get:function(){return 7}}).a!==7})});var od=h(nd=>{"use strict";var QT=Ee(),GT=xe(),WT=An(),YT=ir(),zT=jt(),KT=Hn(),XT=He(),JT=Qn(),sd=Object.getOwnPropertyDescriptor;nd.f=QT?sd:function(e,t){if(e=zT(e),t=KT(t),JT)try{return sd(e,t)}catch{}if(XT(e,t))return YT(!GT(WT.f,e,t),e[t])}});var Gn=h((QC,ud)=>{"use strict";var ZT=ie(),eI=W(),tI=/#|\.prototype\./,or=function(r,e){var t=rI[iI(r)];return t===sI?!0:t===aI?!1:eI(e)?ZT(e):!!e},iI=or.normalize=function(r){return String(r).replace(tI,".").toLowerCase()},rI=or.data={},aI=or.NATIVE="N",sI=or.POLYFILL="P";ud.exports=or});var Ti=h((GC,cd)=>{"use strict";var ld=kn(),nI=Ze(),oI=tr(),uI=ld(ld.bind);cd.exports=function(r,e){return nI(r),e===void 0?r:oI?uI(r,e):function(){return r.apply(e,arguments)}}});var Wn=h((WC,dd)=>{"use strict";var lI=Ee(),cI=ie();dd.exports=lI&&cI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var et=h((YC,pd)=>{"use strict";var dI=Pe(),pI=String,hI=TypeError;pd.exports=function(r){if(dI(r))return r;throw new hI(pI(r)+" is not an object")}});var Gt=h(md=>{"use strict";var mI=Ee(),fI=Qn(),bI=Wn(),Wa=et(),hd=Hn(),gI=TypeError,Yn=Object.defineProperty,vI=Object.getOwnPropertyDescriptor,zn="enumerable",Kn="configurable",Xn="writable";md.f=mI?bI?function(e,t,i){if(Wa(e),t=hd(t),Wa(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Xn in i&&!i[Xn]){var a=vI(e,t);a&&a[Xn]&&(e[t]=i.value,i={configurable:Kn in i?i[Kn]:a[Kn],enumerable:zn in i?i[zn]:a[zn],writable:!1})}return Yn(e,t,i)}:Yn:function(e,t,i){if(Wa(e),t=hd(t),Wa(i),fI)try{return Yn(e,t,i)}catch{}if("get"in i||"set"in i)throw new gI("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ii=h((KC,fd)=>{"use strict";var SI=Ee(),yI=Gt(),TI=ir();fd.exports=SI?function(r,e,t){return yI.f(r,e,TI(1,t))}:function(r,e,t){return r[e]=t,r}});var K=h((XC,gd)=>{"use strict";var ur=Y(),II=xn(),EI=kn(),xI=W(),PI=od().f,kI=Gn(),Ei=vi(),wI=Ti(),xi=Ii(),bd=He();nr();var AI=function(r){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new r;case 1:return new r(t);case 2:return new r(t,i)}return new r(t,i,a)}return II(r,this,arguments)};return e.prototype=r.prototype,e};gd.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?ur:a?ur[t]:ur[t]&&ur[t].prototype,o=i?Ei:Ei[t]||xi(Ei,t,{})[t],u=o.prototype,l,d,c,p,m,f,b,g,S;for(p in e)l=kI(i?p:t+(a?".":"#")+p,r.forced),d=!l&&n&&bd(n,p),f=o[p],d&&(r.dontCallGetSet?(S=PI(n,p),b=S&&S.value):b=n[p]),m=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof m)&&(r.bind&&d?g=wI(m,ur):r.wrap&&d?g=AI(m):s&&xI(m)?g=EI(m):g=m,(r.sham||m&&m.sham||f&&f.sham)&&xi(g,"sham",!0),xi(o,p,g),s&&(c=t+"Prototype",bd(Ei,c)||xi(Ei,c,{}),xi(Ei[c],p,m),r.real&&u&&(l||!u[p])&&xi(u,p,m)))}});var Sd=h((JC,vd)=>{"use strict";var LI=Math.ceil,RI=Math.floor;vd.exports=Math.trunc||function(e){var t=+e;return(t>0?RI:LI)(t)}});var lr=h((ZC,yd)=>{"use strict";var $I=Sd();yd.exports=function(r){var e=+r;return e!==e||e===0?0:$I(e)}});var Id=h((e0,Td)=>{"use strict";var MI=lr(),DI=Math.max,CI=Math.min;Td.exports=function(r,e){var t=MI(r);return t<0?DI(t+e,0):CI(t,e)}});var Jn=h((t0,Ed)=>{"use strict";var VI=lr(),BI=Math.min;Ed.exports=function(r){var e=VI(r);return e>0?BI(e,9007199254740991):0}});var Pi=h((i0,xd)=>{"use strict";var OI=Jn();xd.exports=function(r){return OI(r.length)}});var Zn=h((r0,kd)=>{"use strict";var _I=jt(),NI=Id(),FI=Pi(),Pd=function(r){return function(e,t,i){var a=_I(e),s=FI(a);if(s===0)return!r&&-1;var n=NI(i,s),o;if(r&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((r||n in a)&&a[n]===t)return r||n||0;return!r&&-1}};kd.exports={includes:Pd(!0),indexOf:Pd(!1)}});var cr=h((a0,wd)=>{"use strict";wd.exports=function(){}});var Ad=h(()=>{"use strict";var qI=K(),UI=Zn().includes,HI=ie(),jI=cr(),QI=HI(function(){return!Array(1).includes()});qI({target:"Array",proto:!0,forced:QI},{includes:function(e){return UI(this,e,arguments.length>1?arguments[1]:void 0)}});jI("includes")});var xt=h((o0,Ld)=>{"use strict";var GI=lt();Ld.exports=GI});var $d=h((u0,Rd)=>{"use strict";Ad();var WI=xt();Rd.exports=WI("Array","includes")});var Dd=h((l0,Md)=>{"use strict";var YI=$d();Md.exports=YI});var je=h((c0,Cd)=>{"use strict";var zI=Dd();Cd.exports=zI});var Ka=h((I0,Ud)=>{"use strict";var rE=Fn(),aE=qn(),qd=rE("keys");Ud.exports=function(r){return qd[r]||(qd[r]=aE(r))}});var jd=h((E0,Hd)=>{"use strict";var sE=ie();Hd.exports=!sE(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var Xa=h((x0,Gd)=>{"use strict";var nE=He(),oE=W(),uE=Si(),lE=Ka(),cE=jd(),Qd=lE("IE_PROTO"),io=Object,dE=io.prototype;Gd.exports=cE?io.getPrototypeOf:function(r){var e=uE(r);if(nE(e,Qd))return e[Qd];var t=e.constructor;return oE(t)&&e instanceof t?t.prototype:e instanceof io?dE:null}});var Ja=h((P0,Wd)=>{"use strict";Wd.exports={}});var Kd=h((k0,zd)=>{"use strict";var pE=J(),ro=He(),hE=jt(),mE=Zn().indexOf,fE=Ja(),Yd=pE([].push);zd.exports=function(r,e){var t=hE(r),i=0,a=[],s;for(s in t)!ro(fE,s)&&ro(t,s)&&Yd(a,s);for(;e.length>i;)ro(t,s=e[i++])&&(~mE(a,s)||Yd(a,s));return a}});var ao=h((w0,Xd)=>{"use strict";Xd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var so=h((A0,Jd)=>{"use strict";var bE=Kd(),gE=ao();Jd.exports=Object.keys||function(e){return bE(e,gE)}});var no=h((L0,rp)=>{"use strict";var ep=Ee(),vE=ie(),tp=J(),SE=Xa(),yE=so(),TE=jt(),IE=An().f,ip=tp(IE),EE=tp([].push),xE=ep&&vE(function(){var r=Object.create(null);return r[2]=2,!ip(r,2)}),Zd=function(r){return function(e){for(var t=TE(e),i=yE(t),a=xE&&SE(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!ep||(a?u in t:ip(t,u)))&&EE(o,r?[u,t[u]]:t[u]);return o}};rp.exports={entries:Zd(!0),values:Zd(!1)}});var ap=h(()=>{"use strict";var PE=K(),kE=no().entries;PE({target:"Object",stat:!0},{entries:function(e){return kE(e)}})});var np=h((M0,sp)=>{"use strict";ap();var wE=vi();sp.exports=wE.Object.entries});var up=h((D0,op)=>{"use strict";var AE=np();op.exports=AE});var ki=h((C0,lp)=>{"use strict";var LE=up();lp.exports=LE});var Wt=h((V0,cp)=>{"use strict";cp.exports={}});var hp=h((B0,pp)=>{"use strict";var RE=Y(),$E=W(),dp=RE.WeakMap;pp.exports=$E(dp)&&/native code/.test(String(dp))});var co=h((O0,bp)=>{"use strict";var ME=hp(),fp=Y(),DE=Pe(),CE=Ii(),oo=He(),uo=nr(),VE=Ka(),BE=Ja(),mp="Object already initialized",lo=fp.TypeError,OE=fp.WeakMap,Za,dr,es,_E=function(r){return es(r)?dr(r):Za(r,{})},NE=function(r){return function(e){var t;if(!DE(e)||(t=dr(e)).type!==r)throw new lo("Incompatible receiver, "+r+" required");return t}};ME||uo.state?(Qe=uo.state||(uo.state=new OE),Qe.get=Qe.get,Qe.has=Qe.has,Qe.set=Qe.set,Za=function(r,e){if(Qe.has(r))throw new lo(mp);return e.facade=r,Qe.set(r,e),e},dr=function(r){return Qe.get(r)||{}},es=function(r){return Qe.has(r)}):(Yt=VE("state"),BE[Yt]=!0,Za=function(r,e){if(oo(r,Yt))throw new lo(mp);return e.facade=r,CE(r,Yt,e),e},dr=function(r){return oo(r,Yt)?r[Yt]:{}},es=function(r){return oo(r,Yt)});var Qe,Yt;bp.exports={set:Za,get:dr,has:es,enforce:_E,getterFor:NE}});var mo=h((_0,vp)=>{"use strict";var po=Ee(),FE=He(),gp=Function.prototype,qE=po&&Object.getOwnPropertyDescriptor,ho=FE(gp,"name"),UE=ho&&function(){}.name==="something",HE=ho&&(!po||po&&qE(gp,"name").configurable);vp.exports={EXISTS:ho,PROPER:UE,CONFIGURABLE:HE}});var yp=h(Sp=>{"use strict";var jE=Ee(),QE=Wn(),GE=Gt(),WE=et(),YE=jt(),zE=so();Sp.f=jE&&!QE?Object.defineProperties:function(e,t){WE(e);for(var i=YE(t),a=zE(t),s=a.length,n=0,o;s>n;)GE.f(e,o=a[n++],i[o]);return e}});var fo=h((F0,Tp)=>{"use strict";var KE=lt();Tp.exports=KE("document","documentElement")});var So=h((q0,Ap)=>{"use strict";var XE=et(),JE=yp(),Ip=ao(),ZE=Ja(),ex=fo(),tx=Ga(),ix=Ka(),Ep=">",xp="<",go="prototype",vo="script",kp=ix("IE_PROTO"),bo=function(){},wp=function(r){return xp+vo+Ep+r+xp+"/"+vo+Ep},Pp=function(r){r.write(wp("")),r.close();var e=r.parentWindow.Object;return r=null,e},rx=function(){var r=tx("iframe"),e="java"+vo+":",t;return r.style.display="none",ex.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(wp("document.F=Object")),t.close(),t.F},ts,is=function(){try{ts=new ActiveXObject("htmlfile")}catch{}is=typeof document<"u"?document.domain&&ts?Pp(ts):rx():Pp(ts);for(var r=Ip.length;r--;)delete is[go][Ip[r]];return is()};ZE[kp]=!0;Ap.exports=Object.create||function(e,t){var i;return e!==null?(bo[go]=XE(e),i=new bo,bo[go]=null,i[kp]=e):i=is(),t===void 0?i:JE.f(i,t)}});var wi=h((U0,Lp)=>{"use strict";var ax=Ii();Lp.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:ax(r,e,t),r}});var Eo=h((H0,Mp)=>{"use strict";var sx=ie(),nx=W(),ox=Pe(),ux=So(),Rp=Xa(),lx=wi(),cx=re(),dx=Ue(),Io=cx("iterator"),$p=!1,ct,yo,To;[].keys&&(To=[].keys(),"next"in To?(yo=Rp(Rp(To)),yo!==Object.prototype&&(ct=yo)):$p=!0);var px=!ox(ct)||sx(function(){var r={};return ct[Io].call(r)!==r});px?ct={}:dx&&(ct=ux(ct));nx(ct[Io])||lx(ct,Io,function(){return this});Mp.exports={IteratorPrototype:ct,BUGGY_SAFARI_ITERATORS:$p}});var rs=h((j0,Cp)=>{"use strict";var hx=re(),mx=hx("toStringTag"),Dp={};Dp[mx]="z";Cp.exports=String(Dp)==="[object z]"});var pr=h((Q0,Vp)=>{"use strict";var fx=rs(),bx=W(),as=Ht(),gx=re(),vx=gx("toStringTag"),Sx=Object,yx=as(function(){return arguments}())==="Arguments",Tx=function(r,e){try{return r[e]}catch{}};Vp.exports=fx?as:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=Tx(e=Sx(r),vx))=="string"?t:yx?as(e):(i=as(e))==="Object"&&bx(e.callee)?"Arguments":i}});var Op=h((G0,Bp)=>{"use strict";var Ix=rs(),Ex=pr();Bp.exports=Ix?{}.toString:function(){return"[object "+Ex(this)+"]"}});var hr=h((W0,Np)=>{"use strict";var xx=rs(),Px=Gt().f,kx=Ii(),wx=He(),Ax=Op(),Lx=re(),_p=Lx("toStringTag");Np.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(wx(a,_p)||Px(a,_p,{configurable:!0,value:e}),i&&!xx&&kx(a,"toString",Ax))}});var qp=h((Y0,Fp)=>{"use strict";var Rx=Eo().IteratorPrototype,$x=So(),Mx=ir(),Dx=hr(),Cx=Wt(),Vx=function(){return this};Fp.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=$x(Rx,{next:Mx(+!i,t)}),Dx(r,a,!1,!0),Cx[a]=Vx,r}});var Hp=h((z0,Up)=>{"use strict";var Bx=J(),Ox=Ze();Up.exports=function(r,e,t){try{return Bx(Ox(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var Qp=h((K0,jp)=>{"use strict";var _x=Pe();jp.exports=function(r){return _x(r)||r===null}});var Wp=h((X0,Gp)=>{"use strict";var Nx=Qp(),Fx=String,qx=TypeError;Gp.exports=function(r){if(Nx(r))return r;throw new qx("Can't set "+Fx(r)+" as a prototype")}});var xo=h((J0,Yp)=>{"use strict";var Ux=Hp(),Hx=Pe(),jx=Et(),Qx=Wp();Yp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=Ux(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return jx(a),Qx(s),Hx(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var sh=h((Z0,ah)=>{"use strict";var Gx=K(),Wx=xe(),ss=Ue(),ih=mo(),Yx=W(),zx=qp(),zp=Xa(),Kp=xo(),Kx=hr(),Xx=Ii(),Po=wi(),Jx=re(),Xp=Wt(),rh=Eo(),Zx=ih.PROPER,eP=ih.CONFIGURABLE,Jp=rh.IteratorPrototype,ns=rh.BUGGY_SAFARI_ITERATORS,mr=Jx("iterator"),Zp="keys",fr="values",eh="entries",th=function(){return this};ah.exports=function(r,e,t,i,a,s,n){zx(t,e,i);var o=function(S){if(S===a&&p)return p;if(!ns&&S&&S in d)return d[S];switch(S){case Zp:return function(){return new t(this,S)};case fr:return function(){return new t(this,S)};case eh:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=r.prototype,c=d[mr]||d["@@iterator"]||a&&d[a],p=!ns&&c||o(a),m=e==="Array"&&d.entries||c,f,b,g;if(m&&(f=zp(m.call(new r)),f!==Object.prototype&&f.next&&(!ss&&zp(f)!==Jp&&(Kp?Kp(f,Jp):Yx(f[mr])||Po(f,mr,th)),Kx(f,u,!0,!0),ss&&(Xp[u]=th))),Zx&&a===fr&&c&&c.name!==fr&&(!ss&&eP?Xx(d,"name",fr):(l=!0,p=function(){return Wx(c,this)})),a)if(b={values:o(fr),keys:s?p:o(Zp),entries:o(eh)},n)for(g in b)(ns||l||!(g in d))&&Po(d,g,b[g]);else Gx({target:e,proto:!0,forced:ns||l},b);return(!ss||n)&&d[mr]!==p&&Po(d,mr,p,{name:a}),Xp[e]=p,b}});var oh=h((eV,nh)=>{"use strict";nh.exports=function(r,e){return{value:r,done:e}}});var wo=h((tV,ph)=>{"use strict";var tP=jt(),ko=cr(),uh=Wt(),ch=co(),iP=Gt().f,rP=sh(),os=oh(),aP=Ue(),sP=Ee(),dh="Array Iterator",nP=ch.set,oP=ch.getterFor(dh);ph.exports=rP(Array,"Array",function(r,e){nP(this,{type:dh,target:tP(r),index:0,kind:e})},function(){var r=oP(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,os(void 0,!0);switch(r.kind){case"keys":return os(t,!1);case"values":return os(e[t],!1)}return os([t,e[t]],!1)},"values");var lh=uh.Arguments=uh.Array;ko("keys");ko("values");ko("entries");if(!aP&&sP&&lh.name!=="values")try{iP(lh,"name",{value:"values"})}catch{}});var mh=h((iV,hh)=>{"use strict";var uP=re(),lP=Wt(),cP=uP("iterator"),dP=Array.prototype;hh.exports=function(r){return r!==void 0&&(lP.Array===r||dP[cP]===r)}});var Ao=h((rV,bh)=>{"use strict";var pP=pr(),fh=sr(),hP=gi(),mP=Wt(),fP=re(),bP=fP("iterator");bh.exports=function(r){if(!hP(r))return fh(r,bP)||fh(r,"@@iterator")||mP[pP(r)]}});var vh=h((aV,gh)=>{"use strict";var gP=xe(),vP=Ze(),SP=et(),yP=ar(),TP=Ao(),IP=TypeError;gh.exports=function(r,e){var t=arguments.length<2?TP(r):e;if(vP(t))return SP(gP(t,r));throw new IP(yP(r)+" is not iterable")}});var Th=h((sV,yh)=>{"use strict";var EP=xe(),Sh=et(),xP=sr();yh.exports=function(r,e,t){var i,a;Sh(r);try{if(i=xP(r,"return"),!i){if(e==="throw")throw t;return t}i=EP(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return Sh(i),t}});var ls=h((nV,Ph)=>{"use strict";var PP=Ti(),kP=xe(),wP=et(),AP=ar(),LP=mh(),RP=Pi(),Ih=rr(),$P=vh(),MP=Ao(),Eh=Th(),DP=TypeError,us=function(r,e){this.stopped=r,this.result=e},xh=us.prototype;Ph.exports=function(r,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=PP(e,i),l,d,c,p,m,f,b,g=function(k){return l&&Eh(l,"normal",k),new us(!0,k)},S=function(k){return a?(wP(k),o?u(k[0],k[1],g):u(k[0],k[1])):o?u(k,g):u(k)};if(s)l=r.iterator;else if(n)l=r;else{if(d=MP(r),!d)throw new DP(AP(r)+" is not iterable");if(LP(d)){for(c=0,p=RP(r);p>c;c++)if(m=S(r[c]),m&&Ih(xh,m))return m;return new us(!1)}l=$P(r,d)}for(f=s?r.next:l.next;!(b=kP(f,l)).done;){try{m=S(b.value)}catch(k){Eh(l,"throw",k)}if(typeof m=="object"&&m&&Ih(xh,m))return m}return new us(!1)}});var wh=h((oV,kh)=>{"use strict";var CP=Ee(),VP=Gt(),BP=ir();kh.exports=function(r,e,t){CP?VP.f(r,e,BP(0,t)):r[e]=t}});var Ah=h(()=>{"use strict";var OP=K(),_P=ls(),NP=wh();OP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return _P(e,function(i,a){NP(t,i,a)},{AS_ENTRIES:!0}),t}})});var Rh=h((cV,Lh)=>{"use strict";wo();Ah();var FP=vi();Lh.exports=FP.Object.fromEntries});var Mh=h((dV,$h)=>{"use strict";$h.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 Ch=h(()=>{"use strict";wo();var qP=Mh(),UP=Y(),HP=hr(),Dh=Wt();for(cs in qP)HP(UP[cs],cs),Dh[cs]=Dh.Array;var cs});var Bh=h((mV,Vh)=>{"use strict";var jP=Rh();Ch();Vh.exports=jP});var Lo=h((fV,Oh)=>{"use strict";var QP=Bh();Oh.exports=QP});var _h=h(()=>{"use strict"});var Ro=h((vV,Nh)=>{"use strict";var br=Y(),GP=Qt(),WP=Ht(),ds=function(r){return GP.slice(0,r.length)===r};Nh.exports=function(){return ds("Bun/")?"BUN":ds("Cloudflare-Workers")?"CLOUDFLARE":ds("Deno/")?"DENO":ds("Node.js/")?"NODE":br.Bun&&typeof Bun.version=="string"?"BUN":br.Deno&&typeof Deno.version=="object"?"DENO":WP(br.process)==="process"?"NODE":br.window&&br.document?"BROWSER":"REST"}()});var ps=h((SV,Fh)=>{"use strict";var YP=Ro();Fh.exports=YP==="NODE"});var Uh=h((yV,qh)=>{"use strict";var zP=Gt();qh.exports=function(r,e,t){return zP.f(r,e,t)}});var Qh=h((TV,jh)=>{"use strict";var KP=lt(),XP=Uh(),JP=re(),ZP=Ee(),Hh=JP("species");jh.exports=function(r){var e=KP(r);ZP&&e&&!e[Hh]&&XP(e,Hh,{configurable:!0,get:function(){return this}})}});var Wh=h((IV,Gh)=>{"use strict";var ek=rr(),tk=TypeError;Gh.exports=function(r,e){if(ek(e,r))return r;throw new tk("Incorrect invocation")}});var Mo=h((EV,Yh)=>{"use strict";var ik=J(),rk=W(),$o=nr(),ak=ik(Function.toString);rk($o.inspectSource)||($o.inspectSource=function(r){return ak(r)});Yh.exports=$o.inspectSource});var Co=h((xV,Zh)=>{"use strict";var sk=J(),nk=ie(),zh=W(),ok=pr(),uk=lt(),lk=Mo(),Kh=function(){},Xh=uk("Reflect","construct"),Do=/^\s*(?:class|function)\b/,ck=sk(Do.exec),dk=!Do.test(Kh),gr=function(e){if(!zh(e))return!1;try{return Xh(Kh,[],e),!0}catch{return!1}},Jh=function(e){if(!zh(e))return!1;switch(ok(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return dk||!!ck(Do,lk(e))}catch{return!0}};Jh.sham=!0;Zh.exports=!Xh||nk(function(){var r;return gr(gr.call)||!gr(Object)||!gr(function(){r=!0})||r})?Jh:gr});var tm=h((PV,em)=>{"use strict";var pk=Co(),hk=ar(),mk=TypeError;em.exports=function(r){if(pk(r))return r;throw new mk(hk(r)+" is not a constructor")}});var Vo=h((kV,rm)=>{"use strict";var im=et(),fk=tm(),bk=gi(),gk=re(),vk=gk("species");rm.exports=function(r,e){var t=im(r).constructor,i;return t===void 0||bk(i=im(t)[vk])?e:fk(i)}});var sm=h((wV,am)=>{"use strict";var Sk=J();am.exports=Sk([].slice)});var om=h((AV,nm)=>{"use strict";var yk=TypeError;nm.exports=function(r,e){if(r<e)throw new yk("Not enough arguments");return r}});var Bo=h((LV,um)=>{"use strict";var Tk=Qt();um.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Tk)});var Qo=h((RV,gm)=>{"use strict";var ke=Y(),Ik=xn(),Ek=Ti(),lm=W(),xk=He(),bm=ie(),cm=fo(),Pk=sm(),dm=Ga(),kk=om(),wk=Bo(),Ak=ps(),Uo=ke.setImmediate,Ho=ke.clearImmediate,Lk=ke.process,Oo=ke.Dispatch,Rk=ke.Function,pm=ke.MessageChannel,$k=ke.String,_o=0,vr={},hm="onreadystatechange",Sr,zt,No,Fo;bm(function(){Sr=ke.location});var jo=function(r){if(xk(vr,r)){var e=vr[r];delete vr[r],e()}},qo=function(r){return function(){jo(r)}},mm=function(r){jo(r.data)},fm=function(r){ke.postMessage($k(r),Sr.protocol+"//"+Sr.host)};(!Uo||!Ho)&&(Uo=function(e){kk(arguments.length,1);var t=lm(e)?e:Rk(e),i=Pk(arguments,1);return vr[++_o]=function(){Ik(t,void 0,i)},zt(_o),_o},Ho=function(e){delete vr[e]},Ak?zt=function(r){Lk.nextTick(qo(r))}:Oo&&Oo.now?zt=function(r){Oo.now(qo(r))}:pm&&!wk?(No=new pm,Fo=No.port2,No.port1.onmessage=mm,zt=Ek(Fo.postMessage,Fo)):ke.addEventListener&&lm(ke.postMessage)&&!ke.importScripts&&Sr&&Sr.protocol!=="file:"&&!bm(fm)?(zt=fm,ke.addEventListener("message",mm,!1)):hm in dm("script")?zt=function(r){cm.appendChild(dm("script"))[hm]=function(){cm.removeChild(this),jo(r)}}:zt=function(r){setTimeout(qo(r),0)});gm.exports={set:Uo,clear:Ho}});var ym=h(($V,Sm)=>{"use strict";var vm=Y(),Mk=Ee(),Dk=Object.getOwnPropertyDescriptor;Sm.exports=function(r){if(!Mk)return vm[r];var e=Dk(vm,r);return e&&e.value}});var Go=h((MV,Im)=>{"use strict";var Tm=function(){this.head=null,this.tail=null};Tm.prototype={add:function(r){var e={item:r,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var r=this.head;if(r){var e=this.head=r.next;return e===null&&(this.tail=null),r.item}}};Im.exports=Tm});var xm=h((DV,Em)=>{"use strict";var Ck=Qt();Em.exports=/ipad|iphone|ipod/i.test(Ck)&&typeof Pebble<"u"});var km=h((CV,Pm)=>{"use strict";var Vk=Qt();Pm.exports=/web0s(?!.*chrome)/i.test(Vk)});var Dm=h((VV,Mm)=>{"use strict";var Li=Y(),Bk=ym(),wm=Ti(),Wo=Qo().set,Ok=Go(),_k=Bo(),Nk=xm(),Fk=km(),Yo=ps(),Am=Li.MutationObserver||Li.WebKitMutationObserver,Lm=Li.document,Rm=Li.process,hs=Li.Promise,Xo=Bk("queueMicrotask"),Ai,zo,Ko,ms,$m;Xo||(yr=new Ok,Tr=function(){var r,e;for(Yo&&(r=Rm.domain)&&r.exit();e=yr.get();)try{e()}catch(t){throw yr.head&&Ai(),t}r&&r.enter()},!_k&&!Yo&&!Fk&&Am&&Lm?(zo=!0,Ko=Lm.createTextNode(""),new Am(Tr).observe(Ko,{characterData:!0}),Ai=function(){Ko.data=zo=!zo}):!Nk&&hs&&hs.resolve?(ms=hs.resolve(void 0),ms.constructor=hs,$m=wm(ms.then,ms),Ai=function(){$m(Tr)}):Yo?Ai=function(){Rm.nextTick(Tr)}:(Wo=wm(Wo,Li),Ai=function(){Wo(Tr)}),Xo=function(r){yr.head||Ai(),yr.add(r)});var yr,Tr;Mm.exports=Xo});var Vm=h((BV,Cm)=>{"use strict";Cm.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var fs=h((OV,Bm)=>{"use strict";Bm.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var Kt=h((_V,Om)=>{"use strict";var qk=Y();Om.exports=qk.Promise});var Ri=h((NV,qm)=>{"use strict";var Uk=Y(),Ir=Kt(),Hk=W(),jk=Gn(),Qk=Mo(),Gk=re(),_m=Ro(),Wk=Ue(),Jo=Dn(),Nm=Ir&&Ir.prototype,Yk=Gk("species"),Zo=!1,Fm=Hk(Uk.PromiseRejectionEvent),zk=jk("Promise",function(){var r=Qk(Ir),e=r!==String(Ir);if(!e&&Jo===66||Wk&&!(Nm.catch&&Nm.finally))return!0;if(!Jo||Jo<51||!/native code/.test(r)){var t=new Ir(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Yk]=i,Zo=t.then(function(){})instanceof i,!Zo)return!0}return!e&&(_m==="BROWSER"||_m==="DENO")&&!Fm});qm.exports={CONSTRUCTOR:zk,REJECTION_EVENT:Fm,SUBCLASSING:Zo}});var $i=h((FV,Hm)=>{"use strict";var Um=Ze(),Kk=TypeError,Xk=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new Kk("Bad Promise constructor");e=i,t=a}),this.resolve=Um(e),this.reject=Um(t)};Hm.exports.f=function(r){return new Xk(r)}});var lf=h(()=>{"use strict";var Jk=K(),Zk=Ue(),Ss=ps(),Pt=Y(),Vi=xe(),jm=wi(),Qm=xo(),ew=hr(),tw=Qh(),iw=Ze(),vs=W(),rw=Pe(),aw=Wh(),sw=Vo(),Km=Qo().set,au=Dm(),nw=Vm(),ow=fs(),uw=Go(),Xm=co(),ys=Kt(),su=Ri(),Jm=$i(),Ts="Promise",Zm=su.CONSTRUCTOR,lw=su.REJECTION_EVENT,cw=su.SUBCLASSING,eu=Xm.getterFor(Ts),dw=Xm.set,Mi=ys&&ys.prototype,Xt=ys,bs=Mi,ef=Pt.TypeError,tu=Pt.document,nu=Pt.process,iu=Jm.f,pw=iu,hw=!!(tu&&tu.createEvent&&Pt.dispatchEvent),tf="unhandledrejection",mw="rejectionhandled",Gm=0,rf=1,fw=2,ou=1,af=2,gs,Wm,bw,Ym,sf=function(r){var e;return rw(r)&&vs(e=r.then)?e:!1},nf=function(r,e){var t=e.value,i=e.state===rf,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,u,l,d;try{a?(i||(e.rejection===af&&vw(e),e.rejection=ou),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),d=!0)),u===r.promise?n(new ef("Promise-chain cycle")):(l=sf(u))?Vi(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},of=function(r,e){r.notified||(r.notified=!0,au(function(){for(var t=r.reactions,i;i=t.get();)nf(i,r);r.notified=!1,e&&!r.rejection&&gw(r)}))},uf=function(r,e,t){var i,a;hw?(i=tu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),Pt.dispatchEvent(i)):i={promise:e,reason:t},!lw&&(a=Pt["on"+r])?a(i):r===tf&&nw("Unhandled promise rejection",t)},gw=function(r){Vi(Km,Pt,function(){var e=r.facade,t=r.value,i=zm(r),a;if(i&&(a=ow(function(){Ss?nu.emit("unhandledRejection",t,e):uf(tf,e,t)}),r.rejection=Ss||zm(r)?af:ou,a.error))throw a.value})},zm=function(r){return r.rejection!==ou&&!r.parent},vw=function(r){Vi(Km,Pt,function(){var e=r.facade;Ss?nu.emit("rejectionHandled",e):uf(mw,e,r.value)})},Di=function(r,e,t){return function(i){r(e,i,t)}},Ci=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=fw,of(r,!0))},ru=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new ef("Promise can't be resolved itself");var i=sf(e);i?au(function(){var a={done:!1};try{Vi(i,e,Di(ru,a,r),Di(Ci,a,r))}catch(s){Ci(a,s,r)}}):(r.value=e,r.state=rf,of(r,!1))}catch(a){Ci({done:!1},a,r)}}};if(Zm&&(Xt=function(e){aw(this,bs),iw(e),Vi(gs,this);var t=eu(this);try{e(Di(ru,t),Di(Ci,t))}catch(i){Ci(t,i)}},bs=Xt.prototype,gs=function(e){dw(this,{type:Ts,done:!1,notified:!1,parent:!1,reactions:new uw,rejection:!1,state:Gm,value:void 0})},gs.prototype=jm(bs,"then",function(e,t){var i=eu(this),a=iu(sw(this,Xt));return i.parent=!0,a.ok=vs(e)?e:!0,a.fail=vs(t)&&t,a.domain=Ss?nu.domain:void 0,i.state===Gm?i.reactions.add(a):au(function(){nf(a,i)}),a.promise}),Wm=function(){var r=new gs,e=eu(r);this.promise=r,this.resolve=Di(ru,e),this.reject=Di(Ci,e)},Jm.f=iu=function(r){return r===Xt||r===bw?new Wm(r):pw(r)},!Zk&&vs(ys)&&Mi!==Object.prototype)){Ym=Mi.then,cw||jm(Mi,"then",function(e,t){var i=this;return new Xt(function(a,s){Vi(Ym,i,a,s)}).then(e,t)},{unsafe:!0});try{delete Mi.constructor}catch{}Qm&&Qm(Mi,bs)}Jk({global:!0,constructor:!0,wrap:!0,forced:Zm},{Promise:Xt});ew(Xt,Ts,!1,!0);tw(Ts)});var mf=h((HV,hf)=>{"use strict";var Sw=re(),df=Sw("iterator"),pf=!1;try{cf=0,uu={next:function(){return{done:!!cf++}},return:function(){pf=!0}},uu[df]=function(){return this},Array.from(uu,function(){throw 2})}catch{}var cf,uu;hf.exports=function(r,e){try{if(!e&&!pf)return!1}catch{return!1}var t=!1;try{var i={};i[df]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var lu=h((jV,ff)=>{"use strict";var yw=Kt(),Tw=mf(),Iw=Ri().CONSTRUCTOR;ff.exports=Iw||!Tw(function(r){yw.all(r).then(void 0,function(){})})});var bf=h(()=>{"use strict";var Ew=K(),xw=xe(),Pw=Ze(),kw=$i(),ww=fs(),Aw=ls(),Lw=lu();Ew({target:"Promise",stat:!0,forced:Lw},{all:function(e){var t=this,i=kw.f(t),a=i.resolve,s=i.reject,n=ww(function(){var o=Pw(t.resolve),u=[],l=0,d=1;Aw(e,function(c){var p=l++,m=!1;d++,xw(o,t,c).then(function(f){m||(m=!0,u[p]=f,--d||a(u))},s)}),--d||a(u)});return n.error&&s(n.value),i.promise}})});var vf=h(()=>{"use strict";var Rw=K(),$w=Ue(),Mw=Ri().CONSTRUCTOR,du=Kt(),Dw=lt(),Cw=W(),Vw=wi(),gf=du&&du.prototype;Rw({target:"Promise",proto:!0,forced:Mw,real:!0},{catch:function(r){return this.then(void 0,r)}});!$w&&Cw(du)&&(cu=Dw("Promise").prototype.catch,gf.catch!==cu&&Vw(gf,"catch",cu,{unsafe:!0}));var cu});var Sf=h(()=>{"use strict";var Bw=K(),Ow=xe(),_w=Ze(),Nw=$i(),Fw=fs(),qw=ls(),Uw=lu();Bw({target:"Promise",stat:!0,forced:Uw},{race:function(e){var t=this,i=Nw.f(t),a=i.reject,s=Fw(function(){var n=_w(t.resolve);qw(e,function(o){Ow(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var yf=h(()=>{"use strict";var Hw=K(),jw=$i(),Qw=Ri().CONSTRUCTOR;Hw({target:"Promise",stat:!0,forced:Qw},{reject:function(e){var t=jw.f(this),i=t.reject;return i(e),t.promise}})});var pu=h((ZV,Tf)=>{"use strict";var Gw=et(),Ww=Pe(),Yw=$i();Tf.exports=function(r,e){if(Gw(r),Ww(e)&&e.constructor===r)return e;var t=Yw.f(r),i=t.resolve;return i(e),t.promise}});var xf=h(()=>{"use strict";var zw=K(),Kw=lt(),If=Ue(),Xw=Kt(),Ef=Ri().CONSTRUCTOR,Jw=pu(),Zw=Kw("Promise"),eA=If&&!Ef;zw({target:"Promise",stat:!0,forced:If||Ef},{resolve:function(e){return Jw(eA&&this===Zw?Xw:this,e)}})});var Pf=h(()=>{"use strict";lf();bf();vf();Sf();yf();xf()});var Lf=h(()=>{"use strict";var tA=K(),iA=Ue(),Is=Kt(),rA=ie(),wf=lt(),Af=W(),aA=Vo(),kf=pu(),sA=wi(),mu=Is&&Is.prototype,nA=!!Is&&rA(function(){mu.finally.call({then:function(){}},function(){})});tA({target:"Promise",proto:!0,real:!0,forced:nA},{finally:function(r){var e=aA(this,wf("Promise")),t=Af(r);return this.then(t?function(i){return kf(e,r()).then(function(){return i})}:r,t?function(i){return kf(e,r()).then(function(){throw i})}:r)}});!iA&&Af(Is)&&(hu=wf("Promise").prototype.finally,mu.finally!==hu&&sA(mu,"finally",hu,{unsafe:!0}));var hu});var $f=h((nB,Rf)=>{"use strict";_h();Pf();Lf();var oA=xt();Rf.exports=oA("Promise","finally")});var Df=h((oB,Mf)=>{"use strict";var uA=$f();Mf.exports=uA});var Es=h((uB,Cf)=>{"use strict";var lA=Df();Cf.exports=lA});var Wf=h(()=>{"use strict";var EA=K(),xA=no().values;EA({target:"Object",stat:!0},{values:function(e){return xA(e)}})});var zf=h((GB,Yf)=>{"use strict";Wf();var PA=vi();Yf.exports=PA.Object.values});var Xf=h((WB,Kf)=>{"use strict";var kA=zf();Kf.exports=kA});var Oi=h((YB,Jf)=>{"use strict";var wA=Xf();Jf.exports=wA});var db=h(()=>{"use strict";var HA=K(),jA=Si(),QA=Pi(),GA=lr(),WA=cr();HA({target:"Array",proto:!0},{at:function(e){var t=jA(this),i=QA(t),a=GA(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});WA("at")});var hb=h((IO,pb)=>{"use strict";db();var YA=xt();pb.exports=YA("Array","at")});var fb=h((EO,mb)=>{"use strict";var zA=hb();mb.exports=zA});var Rt=h((xO,bb)=>{"use strict";var KA=fb();bb.exports=KA});var Ou=h((oN,Xb)=>{"use strict";var DL=Ht();Xb.exports=Array.isArray||function(e){return DL(e)==="Array"}});var Zb=h((uN,Jb)=>{"use strict";var CL=TypeError,VL=9007199254740991;Jb.exports=function(r){if(r>VL)throw CL("Maximum allowed index exceeded");return r}});var ig=h((lN,tg)=>{"use strict";var BL=Ou(),OL=Pi(),_L=Zb(),NL=Ti(),eg=function(r,e,t,i,a,s,n,o){for(var u=a,l=0,d=n?NL(n,o):!1,c,p;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&BL(c)?(p=OL(c),u=eg(r,e,c,p,u,s-1)-1):(_L(u+1),r[u]=c),u++),l++;return u};tg.exports=eg});var ng=h((cN,sg)=>{"use strict";var rg=Ou(),FL=Co(),qL=Pe(),UL=re(),HL=UL("species"),ag=Array;sg.exports=function(r){var e;return rg(r)&&(e=r.constructor,FL(e)&&(e===ag||rg(e.prototype))?e=void 0:qL(e)&&(e=e[HL],e===null&&(e=void 0))),e===void 0?ag:e}});var ug=h((dN,og)=>{"use strict";var jL=ng();og.exports=function(r,e){return new(jL(r))(e===0?0:e)}});var lg=h(()=>{"use strict";var QL=K(),GL=ig(),WL=Ze(),YL=Si(),zL=Pi(),KL=ug();QL({target:"Array",proto:!0},{flatMap:function(e){var t=YL(this),i=zL(t),a;return WL(e),a=KL(t,0),a.length=GL(a,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var cg=h(()=>{"use strict";var XL=cr();XL("flatMap")});var pg=h((bN,dg)=>{"use strict";lg();cg();var JL=xt();dg.exports=JL("Array","flatMap")});var mg=h((gN,hg)=>{"use strict";var ZL=pg();hg.exports=ZL});var _u=h((vN,fg)=>{"use strict";var eR=mg();fg.exports=eR});var _r=h((AN,Pg)=>{"use strict";var uR=pr(),lR=String;Pg.exports=function(r){if(uR(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return lR(r)}});var Fu=h((LN,kg)=>{"use strict";kg.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 Lg=h((RN,Ag)=>{"use strict";var cR=J(),dR=Et(),pR=_r(),Uu=Fu(),wg=cR("".replace),hR=RegExp("^["+Uu+"]+"),mR=RegExp("(^|[^"+Uu+"])["+Uu+"]+$"),qu=function(r){return function(e){var t=pR(dR(e));return r&1&&(t=wg(t,hR,"")),r&2&&(t=wg(t,mR,"$1")),t}};Ag.exports={start:qu(1),end:qu(2),trim:qu(3)}});var Dg=h(($N,Mg)=>{"use strict";var fR=mo().PROPER,bR=ie(),Rg=Fu(),$g="\u200B\x85\u180E";Mg.exports=function(r){return bR(function(){return!!Rg[r]()||$g[r]()!==$g||fR&&Rg[r].name!==r})}});var Hu=h((MN,Cg)=>{"use strict";var gR=Lg().start,vR=Dg();Cg.exports=vR("trimStart")?function(){return gR(this)}:"".trimStart});var Bg=h(()=>{"use strict";var SR=K(),Vg=Hu();SR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Vg},{trimLeft:Vg})});var _g=h(()=>{"use strict";Bg();var yR=K(),Og=Hu();yR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Og},{trimStart:Og})});var Fg=h((ON,Ng)=>{"use strict";_g();var TR=xt();Ng.exports=TR("String","trimLeft")});var Ug=h((_N,qg)=>{"use strict";var IR=Fg();qg.exports=IR});var jg=h((NN,Hg)=>{"use strict";var ER=Ug();Hg.exports=ER});var nv=h(()=>{"use strict"});var ov=h(()=>{"use strict"});var lv=h((vU,uv)=>{"use strict";var GR=Pe(),WR=Ht(),YR=re(),zR=YR("match");uv.exports=function(r){var e;return GR(r)&&((e=r[zR])!==void 0?!!e:WR(r)==="RegExp")}});var dv=h((SU,cv)=>{"use strict";var KR=et();cv.exports=function(){var r=KR(this),e="";return r.hasIndices&&(e+="d"),r.global&&(e+="g"),r.ignoreCase&&(e+="i"),r.multiline&&(e+="m"),r.dotAll&&(e+="s"),r.unicode&&(e+="u"),r.unicodeSets&&(e+="v"),r.sticky&&(e+="y"),e}});var mv=h((yU,hv)=>{"use strict";var XR=xe(),JR=He(),ZR=rr(),e$=dv(),pv=RegExp.prototype;hv.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in pv)&&!JR(r,"flags")&&ZR(pv,r)?XR(e$,r):e}});var bv=h((TU,fv)=>{"use strict";var Ju=J(),t$=Si(),i$=Math.floor,Ku=Ju("".charAt),r$=Ju("".replace),Xu=Ju("".slice),a$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,s$=/\$([$&'`]|\d{1,2})/g;fv.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,u=s$;return a!==void 0&&(a=t$(a),u=a$),r$(s,u,function(l,d){var c;switch(Ku(d,0)){case"$":return"$";case"&":return r;case"`":return Xu(e,0,t);case"'":return Xu(e,n);case"<":c=a[Xu(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var m=i$(p/10);return m===0?l:m<=o?i[m-1]===void 0?Ku(d,1):i[m-1]+Ku(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var Sv=h(()=>{"use strict";var n$=K(),o$=xe(),el=J(),gv=Et(),u$=W(),l$=gi(),c$=lv(),ji=_r(),d$=sr(),p$=mv(),h$=bv(),m$=re(),f$=Ue(),b$=m$("replace"),g$=TypeError,Zu=el("".indexOf),v$=el("".replace),vv=el("".slice),S$=Math.max;n$({target:"String",proto:!0},{replaceAll:function(e,t){var i=gv(this),a,s,n,o,u,l,d,c,p,m,f=0,b="";if(!l$(e)){if(a=c$(e),a&&(s=ji(gv(p$(e))),!~Zu(s,"g")))throw new g$("`.replaceAll` does not allow non-global regexes");if(n=d$(e,b$),n)return o$(n,e,i,t);if(f$&&a)return v$(ji(i),e,t)}for(o=ji(i),u=ji(e),l=u$(t),l||(t=ji(t)),d=u.length,c=S$(1,d),p=Zu(o,u);p!==-1;)m=l?ji(t(u,p,o)):h$(u,o,p,[],void 0,t),b+=vv(o,f,p)+m,f=p+d,p=p+c>o.length?-1:Zu(o,u,p+c);return f<o.length&&(b+=vv(o,f)),b}})});var Tv=h((xU,yv)=>{"use strict";nv();ov();Sv();var y$=xt();yv.exports=y$("String","replaceAll")});var Ev=h((PU,Iv)=>{"use strict";var T$=Tv();Iv.exports=T$});var Pv=h((kU,xv)=>{"use strict";var I$=Ev();xv.exports=I$});var wv=h((wU,kv)=>{"use strict";var E$=lr(),x$=_r(),P$=Et(),k$=RangeError;kv.exports=function(e){var t=x$(P$(this)),i="",a=E$(e);if(a<0||a===1/0)throw new k$("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(i+=t);return i}});var Mv=h((AU,$v)=>{"use strict";var Rv=J(),w$=Jn(),Av=_r(),A$=wv(),L$=Et(),R$=Rv(A$),$$=Rv("".slice),M$=Math.ceil,Lv=function(r){return function(e,t,i){var a=Av(L$(e)),s=w$(t),n=a.length,o=i===void 0?" ":Av(i),u,l;return s<=n||o===""?a:(u=s-n,l=R$(o,M$(u/o.length)),l.length>u&&(l=$$(l,0,u)),r?a+l:l+a)}};$v.exports={start:Lv(!1),end:Lv(!0)}});var Cv=h((LU,Dv)=>{"use strict";var D$=Qt();Dv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(D$)});var Vv=h(()=>{"use strict";var C$=K(),V$=Mv().start,B$=Cv();C$({target:"String",proto:!0,forced:B$},{padStart:function(e){return V$(this,e,arguments.length>1?arguments[1]:void 0)}})});var Ov=h((MU,Bv)=>{"use strict";Vv();var O$=xt();Bv.exports=O$("String","padStart")});var Nv=h((DU,_v)=>{"use strict";var _$=Ov();_v.exports=_$});var qv=h((CU,Fv)=>{"use strict";var N$=Nv();Fv.exports=N$});var Ul="2.0.126-dev.e6a91ecc.0";var he=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(he||{}),It=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(It||{});var Ua=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ua||{}),Tn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Tn||{});var In=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(In||{}),Ha=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ha||{});var vy=M(je(),1);import{assertNever as Fd,assertNonNullable as KI,isNonNullable as Ya,ValueSubject as eo,Subject as XI,Subscription as JI,merge as ZI,observableFrom as eE,fromEvent as Bd,map as Od,tap as _d,filterChanged as tE,isNullable as to,ErrorCategory as Nd}from"@vkontakte/videoplayer-shared";var Vd=r=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e(),i.onerror=a=>t(a),document.body.appendChild(i)});var za=class{constructor(e){this.connection$=new eo(void 0);this.castState$=new eo("NOT_AVAILABLE");this.errorEvent$=new XI;this.realCastState$=new eo("NOT_AVAILABLE");this.subscription=new JI;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Ya(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},a||Vd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Nd.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ya(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();to(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();to(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Bd(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.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 Fd(a.sessionState)}})).add(ZI(Bd(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_d(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Od(a=>a.castState)),eE([i.getCastState()])).pipe(tE(),Od(iE),_d(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ya(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();KI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(to(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Ya(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Nd.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},iE=r=>{switch(r){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 Fd(r)}};var Dl=M(je(),1),ZS=M(ki(),1),ey=M(Lo(),1);var jf=M(Es(),1);import{assertNever as Vf}from"@vkontakte/videoplayer-shared";var ae=(r,e=0,t=0)=>{switch(t){case 0:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return r;let i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Vf(t)}return r},xs=(r,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:Vf(e)}};var T=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};import{isNonNullable as cA,Subject as Ps,merge as Bf}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Ps;this.transitionEnded$=new Ps;this.transitionUpdated$=new Ps;this.forceChanged$=new Ps;this.stateChangeStarted$=Bf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Bf(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||cA(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as dA}from"@vkontakte/videoplayer-shared";var Of=r=>{switch(r){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 dA(r)}};import{assertNever as Bi,assertNonNullable as Jt,debounce as _f,ErrorCategory as Nf,fromEvent as Zt,isNonNullable as Ff,map as qf,merge as Uf,observableFrom as pA,Subject as hA,Subscription as fu,timeout as mA,getHighestQuality as fA}from"@vkontakte/videoplayer-shared";var bA=5,gA=5,vA=500,Hf=7e3,Er=class{constructor(e){this.subscription=new fu;this.loadMediaTimeoutSubscription=new fu;this.videoState=new $("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Bi(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:Bi(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:Bi(e)}break}default:Bi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Of(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 fu;this.subscription.add(e),this.subscription.add(Uf(this.videoState.stateChangeStarted$.pipe(qf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(qf(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new hA;e.add(a.pipe(_f(vA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Zt(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)>bA)&&a.next(o),s=o})),e.add(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.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<gA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:Bi(n)}}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let i=Uf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pA(["init"])).pipe(_f(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&T(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,i,a,s;switch(e){case"MPEG":{let l=t[e];Jt(l);let d=fA(Object.keys(l));Jt(d);let c=l[d];Jt(c),i=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Jt(l),i=l.url,a="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 l=t[e];Jt(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Jt(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Jt(l),i=ae(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Nf.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Bi(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Ff(o)&&(n.metadata.title=o),Ff(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(mA(Hf).subscribe(()=>s(`timeout(${Hf})`)))});(0,jf.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Nf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Vu=M(je(),1);import{clearVideoElement as Gf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as SA}from"@vkontakte/videoplayer-shared";var Qf=r=>{try{r.pause(),r.playbackRate=0,SA(r),r.remove()}catch(e){console.error(e)}};import{fromEvent as yA,Subscription as TA}from"@vkontakte/videoplayer-shared";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)}},gu=window.WeakMap?new WeakMap:new bu,vu=window.WeakMap?new WeakMap:new Map,IA=(r,e=20)=>{let t=0;return yA(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},me=(r,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=r.querySelector("video"),a=!!i;i?Gf(i):(i=document.createElement("video"),r.appendChild(i)),gu.set(i,a);let s=new TA;return s.add(IA(i,e)),vu.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},fe=r=>{vu.get(r)?.unsubscribe(),vu.delete(r);let t=gu.get(r);gu.delete(r),t?Gf(r):Qf(r)};var yu=M(Oi(),1);import{assertNonNullable as xr,isNonNullable as it,isNullable as RA,fromEvent as _i,merge as Zf,observableFrom as eb,filterChanged as tb,map as Pr,Subject as ib,Subscription as $A,ValueSubject as MA,ErrorCategory as DA}from"@vkontakte/videoplayer-shared";import{isNonNullable as Su,isNullable as AA,Subscription as LA}from"@vkontakte/videoplayer-shared";var ks=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),u=AA(a),l=new LA;return a&&l.add(a.subscribe(d=>{let c=r.getState();i(d,c)&&r.setState(d)},s)),i(o,n)||(t(n),u&&r.setState(n)),l.add(r.stateChangeStarted$.subscribe(d=>{t(d.to),u&&r.setState(d.to)},s)),l},tt=(r,e,t)=>ks(e,()=>r.loop,i=>{Su(i)&&(r.loop=i)},{onError:t}),be=(r,e,t,i)=>ks(e,()=>({muted:r.muted,volume:r.volume}),a=>{Su(a)&&(r.muted=a.muted,r.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:i}),De=(r,e,t,i)=>ks(e,()=>r.playbackRate,a=>{Su(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),kt=ks;var CA=r=>["__",r.language,r.label].join("|"),VA=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},Tu=class r{constructor(e){this.available$=new ib;this.current$=new MA(void 0);this.error$=new ib;this.subscription=new $A;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:DA.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(kt(t.internalTextTracks,()=>(0,yu.default)(this.internalTracks),s=>{it(s)&&this.setInternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Pr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(kt(t.externalTextTracks,()=>(0,yu.default)(this.externalTracks),s=>{it(s)&&this.setExternal(s)},{equal:(s,n)=>it(s)&&it(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Pr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(kt(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:a})),this.subscription.add(kt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){xr(this.video);let{textTracks:e}=this.video;this.subscription.add(_i(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Zf(_i(e,"addtrack"),_i(e,"removetrack"),eb(["init"])).pipe(Pr(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),tb((i,a)=>i.length===a.length&&i.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Zf(_i(e,"change"),eb(["init"])).pipe(Pr(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Pr(i=>i&&this.htmlTextTrackToITextTrack(i).id),tb()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(_i(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};i.track?.addEventListener("cuechange",a)})),this.subscription.add(_i(e,"removetrack").subscribe(i=>{i.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let a=i;it(t.align)&&(a.align=t.align),it(t.position)&&(a.position=t.position),it(t.size)&&(a.size=t.size),it(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){xr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(r.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,a=e.id?e.id:CA(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:a,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){xr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(RA(e)||!VA(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){xr(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){xr(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ce=Tu;var pt=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 rb=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Iu=r=>{let e=rb(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},ab=r=>{let e=rb(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};import{fromEvent as Ve,map as wt,merge as nb,filterChanged as OA,isNonNullable as ob,Subject as _A,filter as ub,mapTo as lb,combine as NA,once as FA,ErrorCategory as qA,ValueSubject as cb,clientChecker as UA}from"@vkontakte/videoplayer-shared";var BA=3,sb=(r,e,t=BA)=>{let i=0,a=0;for(let s=0;s<r.length;s++){let n=r.start(s),o=r.end(s);if(n<=e&&e<=o){if(i=n,a=o,!t)return{from:i,to:a};for(let u=s-1;u>=0;u--)r.end(u)+t>=i&&(i=r.start(u));for(let u=s+1;u<r.length;u++)r.start(u)-t<=a&&(a=r.end(u))}}return{from:i,to:a}};var ge=r=>{let e=x=>Ve(r,x).pipe(lb(void 0)),i=nb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>Ve(r,x))).pipe(wt(x=>x.type==="ended"?r.readyState<2:r.readyState<3),OA()),a=nb(Ve(r,"progress"),Ve(r,"timeupdate")).pipe(wt(()=>sb(r.buffered,r.currentTime))),s=UA.isSafari?NA({play:e("play").pipe(FA()),playing:e("playing")}).pipe(lb(void 0)):e("playing"),n=Ve(r,"volumechange").pipe(wt(()=>({muted:r.muted,volume:r.volume}))),o=Ve(r,"ratechange").pipe(wt(()=>r.playbackRate)),u=Ve(r,"error").pipe(ub(()=>!!(r.error||r.played.length)),wt(()=>{let x=r.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:qA.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:r.error??void 0}})),l=Ve(r,"timeupdate").pipe(wt(()=>r.currentTime)),d=new _A,c=.3,p;l.subscribe(x=>{r.loop&&ob(p)&&ob(x)&&p>=r.duration-c&&x<=c&&d.next(p),p=x});let m=e("pause").pipe(ub(()=>!r.error&&p!==r.duration)),f=Ve(r,"enterpictureinpicture"),b=Ve(r,"leavepictureinpicture"),g=new cb(ab(r));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new cb(Iu(r));return Ve(r,"fullscreenchange").pipe(wt(()=>Iu(r))).subscribe(S),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ve(r,"durationchange").pipe(wt(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b}};import{VideoQuality as At}from"@vkontakte/videoplayer-shared";var Lt=r=>{switch(r){case"mobile":return At.Q_144P;case"lowest":return At.Q_240P;case"low":return At.Q_360P;case"sd":case"medium":return At.Q_480P;case"hd":case"high":return At.Q_720P;case"fullhd":case"full":return At.Q_1080P;case"quadhd":case"quad":return At.Q_1440P;case"ultrahd":case"ultra":return At.Q_2160P}};var $t=M(Rt(),1),kb=M(je(),1),Ls=M(ki(),1);import{isNonNullable as we,isNullable as Ib,now as wb,isHigher as Eb,isHigherOrEqual as ku,isInvariantQuality as xb,isLowerOrEqual as wu,videoSizeToQuality as ZA,assertNotEmptyArray as Ab,assertNonNullable as eL}from"@vkontakte/videoplayer-shared";var Eu=!1,ht={},gb=r=>{Eu=r},vb=()=>{ht={}},Sb=r=>{r(ht)},kr=(r,e)=>{Eu&&(ht.meta=ht.meta??{},ht.meta[r]=e)},le=class{constructor(e){this.name=e}next(e){if(!Eu)return;ht.series=ht.series??{};let t=ht.series[this.name]??[];t.push([Date.now(),e]),ht.series[this.name]=t}};import{isHigher as XA,isHigherOrEqual as RO,isLower as yb,isLowerOrEqual as $O,isNonNullable as ws,isNullable as JA,videoHeightToQuality as As}from"@vkontakte/videoplayer-shared";function xu({limits:r,highQualityLimit:e,trafficSavingLimit:t}){return!r.max&&r.min===e?"high_quality":!r.min&&r.max===t?"traffic_saving":"unknown"}function Pu({limits:r,highQualityLimit:e,trafficSavingLimit:t}){return!!r&&xu({limits:r,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function wr({limits:r,highestAvailableQuality:e,lowestAvailableQuality:t}){return JA(r)||ws(r.min)&&ws(r.max)&&yb(r.max,r.min)||ws(r.min)&&e&&XA(r.min,e)||ws(r.max)&&t&&yb(r.max,t)}function Tb({limits:r,highestAvailableHeight:e,lowestAvailableHeight:t}){return wr({limits:{max:r?.max?As(r.max):void 0,min:r?.min?As(r.min):void 0},highestAvailableQuality:e?As(e):void 0,lowestAvailableQuality:t?As(t):void 0})}var tL=new le("best_bitrate"),Lb=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var Au=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),Ar=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=wb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Rb='Assertion "ABR Tracks is empty array" failed',Rs=(r,e,t,i)=>{let a=[...e].sort(Au(1)),s=[...t].sort(Au(1)),n=s.filter(u=>we(u.bitrate)&&we(r.bitrate)?r.bitrate/u.bitrate>i:!0),o=(0,$t.default)(s,Math.round(s.length*a.indexOf(r)/(a.length+1)))??(0,$t.default)(s,-1);return o&&(0,kb.default)(n,o)?o:n.length?(0,$t.default)(n,-1):(0,$t.default)(s,0)},Pb=r=>"quality"in r,$b=(r,e,t,i)=>{let a=we(i?.last?.bitrate)&&we(t?.bitrate)&&i.last.bitrate<t.bitrate?r.trackCooldownIncreaseQuality:r.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&wb()-i.history[t.id]<=a&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=Pb(n)?"video":"audio",u=Pb(n)?n.quality:n.bitrate;return e({message:`
|
|
8
8
|
[last ${o} selected] ${u}
|
|
9
|
-
`}),n}return i?.recordSwitch(t),t},iL=(r,e)=>Math.log(e)/Math.log(r),rL=({tuning:r,container:e,limits:t})=>{let i=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let a=window.devicePixelRatio;if(r.pixelRatioMultiplier)i*=r.pixelRatioMultiplier*(a-1)+1;else{let s=r.pixelRatioLogBase,[n=0,o=0,u=0]=r.pixelRatioLogCoefficients,l=iL(s,n*a+o)+u;Number.isFinite(l)&&(i*=l)}}return Pu({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:t})&&(i*=2),{containerSizeLimit:r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*i,height:e.height*i}:void 0,containerSizeFactor:i}},Mt=(r,{container:e,estimatedThroughput:t,tuning:i,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:m,abrLogger:f})=>{Ab(r,Rb);let{containerSizeFactor:b,containerSizeLimit:g}=rL({container:e,tuning:i,limits:a}),S=i.considerPlaybackRate&&
|
|
9
|
+
`}),n}return i?.recordSwitch(t),t},iL=(r,e)=>Math.log(e)/Math.log(r),rL=({tuning:r,container:e,limits:t})=>{let i=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let a=window.devicePixelRatio;if(r.pixelRatioMultiplier)i*=r.pixelRatioMultiplier*(a-1)+1;else{let s=r.pixelRatioLogBase,[n=0,o=0,u=0]=r.pixelRatioLogCoefficients,l=iL(s,n*a+o)+u;Number.isFinite(l)&&(i*=l)}}return Pu({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:t})&&(i*=2),{containerSizeLimit:r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*i,height:e.height*i}:void 0,containerSizeFactor:i}},Mt=(r,{container:e,estimatedThroughput:t,tuning:i,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:m,abrLogger:f})=>{Ab(r,Rb);let{containerSizeFactor:b,containerSizeLimit:g}=rL({container:e,tuning:i,limits:a}),S=i.considerPlaybackRate&&we(o)?o:1,k=r.filter(v=>!xb(v.quality)).sort((v,P)=>Eb(v.quality,P.quality)?-1:1),x=(0,$t.default)(k,-1)?.quality,R=(0,$t.default)(k,0)?.quality,y=wr({limits:a,lowestAvailableQuality:x,highestAvailableQuality:R}),I=S*Lb(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},F=k.filter(v=>{let P=!0;if(g)if(v.size)P=v.size.width<=g.width&&v.size.height<=g.height;else{let $e=g&&ZA(g);P=$e?wu(v.quality,$e):!0}if(!P)return L[v.quality]="FitsContainer",!1;let U=m||t,Le=we(U)&&isFinite(U)&&we(v.bitrate)?U-s>=v.bitrate*I:!0,Re=Pu({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:a})&&a?.min===v.quality;if(!Le&&!Re)return L[v.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&we(i.minBufferToSwitchUp)&&u&&!xb(u.quality)&&(n??0)<i.minBufferToSwitchUp&&Eb(v.quality,u.quality))return L[v.quality]="Buffer",!1;if(!!c&&ku(v.quality,c)&&!Re)return L[v.quality]="DroppedFramesLimit",!1;if(!!p&&ku(v.quality,p)&&!Re)return L[v.quality]="StallsLimit",!1;let w=y||(Ib(a?.max)||wu(v.quality,a.max))&&(Ib(a?.min)||ku(v.quality,a.min)),H=we(d)&&!d?wu(v.quality,i.backgroundVideoQualityLimit):!0;return!w||!H?(L[v.quality]="FitsQualityLimits",!1):!0})[0];F&&F.bitrate&&tL.next(F.bitrate);let q=F??(0,$t.default)(k,-1)??r[0];return q.quality!==l?.last?.quality&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
12
|
${r.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.bitrate}, size: ${v.size?.width}:${v.size?.height} }`).join(`
|
|
@@ -39,14 +39,14 @@ var Ey=Object.create;var ql=Object.defineProperty;var xy=Object.getOwnPropertyDe
|
|
|
39
39
|
|
|
40
40
|
[best video track] ${F?.quality}
|
|
41
41
|
[selected video track] ${q?.quality}
|
|
42
|
-
`}),$b(i,f,q,l)},Mb=(r,e,t,{estimatedThroughput:i,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Ab(t,Rb);let d=a.considerPlaybackRate&&
|
|
42
|
+
`}),$b(i,f,q,l)},Mb=(r,e,t,{estimatedThroughput:i,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Ab(t,Rb);let d=a.considerPlaybackRate&&we(s)?s:1,c=[...t].sort(Au(-1)),p=r.bitrate;eL(p);let m=d*Lb(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f,b=Rs(r,e,t,a.minVideoAudioRatio),g=l||i;return we(g)&&isFinite(g)&&(f=c.find(S=>we(S.bitrate)&&we(b?.bitrate)?g-p>=S.bitrate*m&&S.bitrate>=b.bitrate:!1)),f||(f=b),f?.bitrate!==o?.last?.bitrate&&u({message:`
|
|
43
43
|
[AUDIO TRACKS ABR]
|
|
44
44
|
[available audio tracks]
|
|
45
45
|
${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,Ls.default)(a??{}).map(([S,
|
|
49
|
+
${(0,Ls.default)(a??{}).map(([S,k])=>`${S}: ${k}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
@@ -60,14 +60,14 @@ var Ey=Object.create;var ql=Object.defineProperty;var xy=Object.getOwnPropertyDe
|
|
|
60
60
|
minBufferToSwitchUp: ${a.minBufferToSwitchUp},
|
|
61
61
|
|
|
62
62
|
[selected audio track] ${f?.id}
|
|
63
|
-
`}),f&&$b(a,u,f,o)};var Z=r=>new URL(r).hostname;import{assertNever as Hb,assertNonNullable as jb,combine as xL,debounce as PL,ErrorCategory as Qb,filter as Gb,filterChanged as wL,isNonNullable as Du,map as Vs,merge as Wb,observableFrom as kL,once as AL,Subscription as LL,ValueSubject as Cu,videoQualityToHeight as Yb,videoSizeToQuality as RL}from"@vkontakte/videoplayer-shared";var Nb=M(Rt(),1);var Cb=M(je(),1),Db=r=>{if(r instanceof DOMException&&(0,Cb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))},ve=async(r,e)=>{let t=r.muted;try{await r.play()}catch(i){if(!Db(i))return!1;if(e&&e(),t)return console.warn(i),!1;r.muted=!0;try{await r.play()}catch(a){return Db(a)&&(r.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as Ms,isNullable as nL,assertNonNullable as $r}from"@vkontakte/videoplayer-shared";var Bb=M(Oi(),1);import{isNonNullable as Vb,assertNonNullable as $s,now as aL}from"@vkontakte/videoplayer-shared";function ee(){return aL()}function Lu(r){return ee()-r}function Ru(r){let e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=n=>i.test(n);return{resolve:(n,o,u=!1)=>{a(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 Ob(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Ni(r,e,t,i){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,m="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;$s(d);let P=Lu(d),U;if(P<b){U=b-P,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,I()},S=P=>(s=P,v),w=P=>(c=P,v),x=()=>(m="json",v),R=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},y=P=>(p=P,v),I=()=>{d=ee(),n=new a,n.open("get",r);let P=0,U,Le=0,Re=()=>($s(d),Math.max(d,Math.max(U||0,Le||0)));if(s&&n.addEventListener("progress",A=>{let C=ee();s.updateChunk&&A.loaded>P&&(s.updateChunk(Re(),A.loaded-P),P=A.loaded,U=C)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>R())),n.addEventListener("load",()=>{if(u)return;$s(n);let A=n.status;if(A>=200&&A<300){let{response:C,responseType:_}=n,k=C?.byteLength;if(typeof k=="number"&&s){let H=k-P;H&&s.updateChunk&&s.updateChunk(Re(),H)}_==="json"&&(!C||!(0,Bb.default)(C).length)?R():(c&&c(),e(C))}else R()}),n.addEventListener("error",()=>{R()}),p){let A=()=>{$s(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Le=ee(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=m,n.send(),v},v={withBitrateReporting:S,withParallel:y,withJSONResponse:x,withRetryCount:P=>(l=P,v),withRetryInterval:(P,U)=>(Vb(P)&&(b=P),Vb(U)&&(f=U),v),withTimeout:P=>(o=P,v),withFinally:w,send:I,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return v}var Lr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&i>0){let s=a*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var _b=M(Oi(),1);var Rr=class{constructor(e,t,i,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ee(),a=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=ee()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ni(t,s,()=>a("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=ee()}_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=ee();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,_b.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as oL}from"@vkontakte/videoplayer-shared";var Ds=1e4,$u=3;var uL=6e4,lL=10,cL=1,dL=500,Mr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new oL,this.chunkRateEstimator=new Lr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ru(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Ru(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,i,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Tb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Nb.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return a||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ms(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ob(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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 Rr($u,Ds,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let R=s&&(!d||d===this.rep);return R||t("Not running!"),R},p=(R,y,I)=>{u&&u.abort(),u=Ni(this.urlResolver.resolve(R,!1),y,I,()=>this._retryCallback()).withTimeout(Ds).withBitrateReporting(this.bitrateSwitcher).withRetryCount($u).withFinally(()=>{u=null}).send()},m=(R,y,I)=>{$r(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(R,!1),y,I,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=R=>{let y=i.playbackRate;i.playbackRate!==R&&(t(`Playback rate switch: ${y}=>${R}`),i.playbackRate=R)},b=R=>{this.lowLatency=R,t(`lowLatency changed to ${R}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let R=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let I=ee()-1e4,L=0;for(let F=0;F<this.bufferStates.length;F++){let q=this.bufferStates[F];R=Math.min(R,q.buf),q.ts<I&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${R} drop=${L} jitter=${this.sourceJitter}`);let G=R-cL;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)}},S=R=>{let y,I=()=>y&&y.start?y.start.length:0,L=A=>y.start[A]/1e3,G=A=>y.dur[A]/1e3,F=A=>y.fragIndex+A,q=(A,C)=>({chunkIdx:F(A),startTS:L(A),dur:G(A),discontinuity:C}),v=()=>{let A=0;if(y&&y.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,_=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,k=C;this.sourceJitter>1&&(k+=this.sourceJitter-1);let H=y.dur.length-1;for(;H>=0&&(k-=y.dur[H],!(k<=0));--H);A=Math.min(H,y.dur.length-1-_),A=Math.max(A,0)}return q(A,!0)},P=A=>{let C=I();if(!(C<=0)){if(Ms(A)){for(let _=0;_<C;_++)if(L(_)>A)return q(_)}return v()}},U=A=>{let C=I(),_=A?A.chunkIdx+1:0,k=_-y.fragIndex;if(!(C<=0)){if(!A||k<0||k-C>lL)return t(`Resync: offset=${k} bChunks=${C} chunk=`+JSON.stringify(A)),v();if(!(k>=C))return q(_-y.fragIndex,!1)}},Le=(A,C,_)=>{l&&l.abort(),l=Ni(this.urlResolver.resolve(A,!0,this.lowLatency),C,_,()=>this._retryCallback()).withTimeout(Ds).withRetryCount($u).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,C)=>{Le(R,_=>{if(!c())return;y=_;let k=!!y.lowLatency;k!==this.lowLatency&&b(k);let H=0;for(let $e=0;$e<y.dur.length;++$e)H+=y.dur[$e];H>0&&($r(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(H/y.dur.length)),a({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,A(P(C))},()=>this._handleNetworkError())},nextChunk:U}},w=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),$r(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:R=>{let{videoElement:y,logger:I}=this.params,L=S(e.jidxUrl),G,F,q,v,P=0,U,Le,Re,A=()=>{U&&(clearTimeout(U),U=void 0);let V=Math.max(dL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),te=P+V,oe=ee(),X=Math.min(1e4,te-oe);P=oe;let Ke=()=>{l||c()&&L.seek(()=>{c()&&(P=ee(),C(),A())})};X>0?U=window.setTimeout(()=>{this.paused?A():Ke()},X):Ke()},C=()=>{let V;for(;V=L.nextChunk(v);)v=V,di(V);let te=L.nextChunk(q);if(te){if(q&&te.discontinuity){I("Detected discontinuity; restarting playback"),this.paused?A():(w(),this._initPlayerWith(e));return}$e(te)}else A()},_=(V,te)=>{if(!c()||!this.sourceBuffer)return;let oe,X,Ke,Oe=_e=>{window.setTimeout(()=>{c()&&_(V,te)},_e)};if(this.sourceBuffer.updating)I("Source buffer is updating; delaying appendBuffer"),Oe(100);else{let _e=ee(),nt=y.currentTime;!this.paused&&y.buffered.length>1&&Le===nt&&_e-Re>500&&(I("Stall suspected; trying to fix"),this._fixupStall()),Le!==nt&&(Le=nt,Re=_e);let St=this._getBufferSizeSec();if(St>30)I(`Buffered ${St} seconds; delaying appendBuffer`),Oe(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:_e,buf:St}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),te&&te()}catch(ot){if(ot.name==="QuotaExceededError")I("QuotaExceededError; delaying appendBuffer"),Ke=this.sourceBuffer.buffered.length,Ke!==0&&(oe=this.sourceBuffer.buffered.start(0),X=nt,X-oe>4&&this.sourceBuffer.remove(oe,X-3)),Oe(1e3);else throw ot}}},k=()=>{F&&G&&(I([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(q)]),_(F,function(){F=null,C()}))},H=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),$e=V=>{c()&&m(H(V),(te,oe)=>{if(c()){if(oe/=1e3,F=te,q=V,n=V.startTS,oe){let X=Math.min(10,V.dur/oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*X:X}k()}},()=>this._handleNetworkError())},di=V=>{c()&&($r(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(H(V),!1)))},ze=V=>{c()&&(e.cachedHeader=V,_(V,()=>{G=!0,k()}))};s=!0,L.seek(V=>{if(c()){if(P=ee(),!V){A();return}v=V,!nL(R)||V.startTS>R?$e(V):(q=V,C())}},R),e.cachedHeader?ze(e.cachedHeader):p(e.headerUrl,ze,()=>this._handleNetworkError())},stop:w,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Ms(a)&&(a+=.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,$r(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ms(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(m=this._getBufferSizeSec(),f=c/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,m)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,m)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Lu(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let m=s.updateChunk(c,p);return m&&l(),m},notifySwitch:c=>{let p=ee();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ni(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ds).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;ve(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&a.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):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},uL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ub=M(wi(),1);import{debounce as pL,filter as Fb,fromEvent as hL,interval as mL,isHigher as fL,isInvariantQuality as bL,isLower as gL,merge as vL,Subject as qb,Subscription as SL}from"@vkontakte/videoplayer-shared";var Mu=class{constructor(){this.onDroopedVideoFramesLimit$=new qb;this.subscription=new SL;this.playing=!1;this.tracks=[];this.forceChecker$=new qb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!bL(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(i-a)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&fL(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(hL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=mL(this.droppedFramesChecker.checkTime).pipe(Fb(()=>this.playing),Fb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(pL(this.droppedFramesChecker.checkTime)),i=vL(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,Ub.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>gL(i,a)?-1:1)?.[0]?.[0];return 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}},Cs=Mu;import{map as yL,Observable as TL}from"@vkontakte/videoplayer-shared";import{fromEvent as IL}from"@vkontakte/videoplayer-shared";var Dr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var EL=(r,e)=>new TL(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Dr()))},{...i,...e});a.observe(r);let s=IL(document,"visibilitychange").pipe(yL(n=>!document.hidden||Dr())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe}}),Be=EL;var $L=["paused","playing","ready"],ML=["paused","playing","ready"],Cr=class{constructor(e){this.subscription=new LL;this.videoState=new $("stopped");this.representations$=new Cu([]);this.droppedFramesManager=new Cs;this.maxSeekBackTime$=new Cu(1/0);this.zeroTime$=new Cu(void 0);this.liveOffset=new pt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Qb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let a of t){let s=a.name??a.index.toString(10),n=Lt(a.name)??RL(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};i.push({track:l,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Du(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Vu.default)(ML,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Vu.default)($L,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ae(this.params.source.url,u))}return;default:return Hb(e)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Qb.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Wb(this.videoState.stateChangeStarted$.pipe(Vs(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Vs(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=me(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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=ge(this.video);this.subscription.add(this.representations$.pipe(Vs(a=>a.map(({track:s})=>s)),Gb(a=>!!a.length),AL()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:a}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(wL(),Vs(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(xL({zeroTime:this.zeroTime$.pipe(Gb(Du)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(be(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a,min:s}})=>{this.dash.setAutoQualityLimits({max:a&&Yb(a),min:s&&Yb(s)}),this.params.output.autoVideoTrackLimits$.next({max:a,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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":this.params.desiredState.playbackState.getTransition()?.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 Hb(a.to)}},t)).add(Wb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,kL(["init"])).pipe(PL(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),fe(this.video)}createLiveDashPlayer(){let e=new Mr({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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&Du(t)?t:Mt(e.map(({track:l})=>l),{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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:d})=>d.id===s)?.representation;jb(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;jb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ae(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var zb=Cr;var ES=M(je(),1);var rt=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){let a=r.start(i)*1e3,s=r.end(i)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as yM,assertNonNullable as TM,debounce as IM,ErrorCategory as SS,filter as yS,filterChanged as Ea,fromEvent as EM,isNonNullable as TS,map as Il,merge as rn,observableFrom as El,once as IS,Subscription as xM}from"@vkontakte/videoplayer-shared";var Bs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let a=0,s=i.length;a<s;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let a=0,s=i.length;a<s;a++){let n=i[a];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}},Fi=class extends Bs{constructor(){super(),this.listeners||Bs.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)}},Vr=class{constructor(){Object.defineProperty(this,"signal",{value:new Fi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Vr.prototype[Symbol.toStringTag]="AbortController",Fi.prototype[Symbol.toStringTag]="AbortSignal");function Os(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function Bu(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!Os({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((m,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Br=Os({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Kb=Br?Bu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ge=Br?Kb.fetch:window.fetch,aN=Br?Kb.Request:window.Request,se=Br?Vr:window.AbortController,sN=Br?Fi:window.AbortSignal;var vl=M(_u(),1);var Fs=M(Rt(),1);var mt=()=>window.ManagedMediaSource||window.MediaSource,_s=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),bg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),gg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Hs,clientChecker as qs}from"@vkontakte/videoplayer-shared";var Us=document.createElement("video"),rR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',aR='video/mp4; codecs="hev1.1.6.L93.B0"',vg='video/webm; codecs="vp09.00.10.08"',Sg='video/webm; codecs="av01.0.00M.08"',sR='audio/mp4; codecs="mp4a.40.2"',nR='audio/webm; codecs="opus"',Or={mms:_s(),mse:bg(),hls:!!(Us.canPlayType?.("application/x-mpegurl")||Us.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Se={mp4:!!Us.canPlayType?.("video/mp4"),webm:!!Us.canPlayType?.("video/webm"),cmaf:!0},ye={h264:!!mt()?.isTypeSupported?.(rR),h265:!!mt()?.isTypeSupported?.(aR),vp9:!!mt()?.isTypeSupported?.(vg),av1:!!mt()?.isTypeSupported?.(Sg),aac:!!mt()?.isTypeSupported?.(sR),opus:!!mt()?.isTypeSupported?.(nR)},qi=(ye.h264||ye.h265)&&ye.aac,ei,oR=async()=>{if(!window.navigator.mediaCapabilities)return;let r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:Sg}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:vg}})]);ei={DASH_WEBM_AV1:e,DASH_WEBM:t}};oR().catch(r=>{console.error(r)});var Ui=Or.hls&&Se.mp4,yg=()=>Object.keys(ye).filter(r=>ye[r]),Tg=(r,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let a=Or.mse&&(!i||!!window.MediaStreamTrack)||Or.mms&&t;return r.filter(s=>{switch(s){case"DASH_SEP":return a&&Se.mp4&&qi;case"DASH_WEBM":return a&&Se.webm&&ye.vp9&&ye.opus;case"DASH_WEBM_AV1":return a&&Se.webm&&ye.av1&&ye.opus;case"DASH_STREAMS":return a&&(Se.mp4&&qi||Se.webm&&(ye.vp9||ye.av1)&&(ye.opus||ye.aac));case"DASH_LIVE":return a&&Se.mp4&&qi;case"DASH_LIVE_CMAF":return a&&Se.mp4&&qi&&Se.cmaf;case"DASH_ONDEMAND":return a&&Se.mp4&&qi;case"HLS":case"HLS_ONDEMAND":return Ui||e&&a&&Se.mp4&&qi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Ui;case"MPEG":return Se.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Or.webrtc&&Or.ws&&ye.h264&&(Se.mp4||Se.webm);default:return Hs(s)}})},Ns=r=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(r){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return ei?ei[t].smooth?[t,e]:ei[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ei?ei[t].powerEfficient?[t,e]:ei[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Hs(r)}return[e,t]},Ig=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Ns(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(qs.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...Ns(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ns(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ns(r),...a,"HLS","HLS_ONDEMAND"];default:Hs(e)}return Ui?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Eg=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...a],n=[...a,...i],o,u=qs.isMac&&qs.isSafari;if(qs.isAndroid)switch(r){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Hs(r)}else Ui&&!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"]},Nu=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],xg=r=>{if(r.size===0)return;if(r.size===1){let t=r.values().next();return(0,Fs.default)(t.value.split("."),0)}for(let t of r){let i=(0,Fs.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=r.values().next();return(0,Fs.default)(e.value.split("."),0)};var Qg=M(jg(),1);import{ErrorCategory as Nr}from"@vkontakte/videoplayer-shared";var Gg=r=>{if(!r)return{id:"EmptyResponse",category:Nr.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:Nr.NETWORK,message:`UV Error ${r}`};let e=(0,Qg.default)(r).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Nr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(r,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Nr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Nr.PARSER,message:"Response is valid XML, but parser failed"}};var Dt=(r,e,t=0)=>{for(let i=0;i<r.length;i++)if(r.start(i)*1e3-t<=e&&r.end(i)*1e3+t>e)return!0;return!1};import{abortable as fl,assertNonNullable as ni,clientChecker as eM,combine as oi,ErrorCategory as at,filter as ya,filterChanged as bl,flattenObject as Ta,fromEvent as ui,getTraceSubscriptionMethod as tM,interval as gl,isNonNullable as dS,map as Yi,merge as li,now as iM,Subject as pS,Subscription as hS,tap as rM,throttle as aM,ValueSubject as z}from"@vkontakte/videoplayer-shared";var Qs=M(je(),1),Gi=M(Rt(),1),Gs=M(_u(),1);var xR=(r,e={})=>{let i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},PR=r=>window.clearTimeout(r),Wg=r=>typeof r=="function"&&r?.toString().endsWith("{ [native code] }"),Yg=!Wg(window.requestIdleCallback)||!Wg(window.cancelIdleCallback),ju=Yg?xR:window.requestIdleCallback,Fr=Yg?PR:window.cancelIdleCallback;var rS=M(Es(),1);import{assertNever as wR,ErrorCategory as zg,clientChecker as Qu,Subject as Kg}from"@vkontakte/videoplayer-shared";var kR=18,Xg=!1;try{Xg=Qu.isSafari&&!!Qu.macVersion&&Qu.macVersion<=kR}catch(r){console.error(r)}var Gu=class{constructor(e){this.bufferFull$=new Kg;this.error$=new Kg;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:zg.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,a=s=>{this.abortRequested=!1,t(s)};Xg&&e?i={operation:"safariAbort",init:e,callback:a}:i={operation:"abort",callback:a};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:zg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:wR(t)}}},Jg=Gu;var Wu=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};import{abortable as Vt,assertNonNullable as Te,clientChecker as H$,ErrorCategory as gt,fromEvent as cl,getExponentialDelay as dl,isNonNullable as Qi,isNullable as ne,now as js,once as j$,Subject as Q$,Subscription as G$,ValueSubject as ri}from"@vkontakte/videoplayer-shared";var B=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let a=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,a)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 Hi=class extends B{};var qr=class extends B{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let a=this.content.byteOffset,s=a+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(a,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Ur=class extends B{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let a=this.readString(4);this.compatibleBrands.push(a),i-=4}}};var Hr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Q=class extends B{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var jr=class extends Q{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 Qr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gr=class extends B{constructor(e,t){super(e,t),this.data=this.content}};var ti=class extends Q{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Wr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zr=class extends Q{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 Kr=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Xr=class extends Q{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Jr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zr=class extends Q{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 ea=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ta=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ia=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ra=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var aa=class extends Q{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var sa=class extends Q{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var na=class extends Q{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)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 oa=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends Q{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var la=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var LR={ftyp:Ur,moov:Hr,mvhd:jr,moof:Qr,mdat:Gr,sidx:ti,trak:Wr,mdia:Jr,mfhd:ia,tkhd:Zr,traf:ra,tfhd:aa,tfdt:sa,trun:na,minf:ea,sv3d:Yr,st3d:zr,prhd:Kr,proj:ta,equi:Xr,uuid:qr,stbl:oa,stsd:ua,avc1:la,unknown:Hi},ft=class r{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=LR[e];return i?new i(t,new r):new Hi(t,new r)}};var Ct=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],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 $R=new TextDecoder("ascii"),MR=r=>$R.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",DR=r=>{let e=new ti(r,new ft),t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},CR=(r,e)=>{let i=new ft().parse(r),a=new Ct(i),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(r.buffer,l,c)},VR=r=>{let t=new ft().parse(r),i=new Ct(t),a={},s=i.findAll("uuid");return s.length?s[s.length-1]:a},BR=r=>{let t=new ft().parse(r);return new Ct(t).find("sidx")?.timescale},OR=(r,e)=>{let i=new ft().parse(r),s=new Ct(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},_R=r=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new ft().parse(r),a=new Ct(i);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.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},Zg={validateData:MR,parseInit:_R,getIndexRange:()=>{},parseSegments:DR,parseFeedableSegmentChunk:CR,getChunkEndTime:OR,getServerLatencyTimestamps:VR,getTimescaleFromIndex:BR};var da=M(je(),1);import{assertNonNullable as zu,isNonNullable as rv,isNullable as FR}from"@vkontakte/videoplayer-shared";import{assertNever as NR}from"@vkontakte/videoplayer-shared";var ev={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"}},tv=r=>{let e=r.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ca(r,t),a=i in ev,s=a?ev[i].type:"binary",n=r.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(r.buffer,r.byteOffset+t+1,o-1),l=n&255>>o,d=ca(u),c=l*2**((o-1)*8)+d,p=t+o,m;return p+c>r.byteLength?m=new DataView(r.buffer,r.byteOffset+p):m=new DataView(r.buffer,r.byteOffset+p,c),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:m,valueSize:c}},ca=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{let t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},We=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return ca(r);case"float":return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case"string":return new TextDecoder("ascii").decode(r);case"utf8":return new TextDecoder("utf-8").decode(r);case"date":return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case"master":return r;case"binary":return r;default:NR(e)}},ii=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=tv(i);if(!e(a))return;a.type==="master"&&ii(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},iv=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=tv(r);return ii(a.value,({tag:s,type:n,value:o})=>(s===17143?e=We(o,n):s===17026?t=We(o,n):s===17029&&(i=We(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var av=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],qR=[231,22612,22743,167,171,163,160,175],UR=r=>{let e,t,i,a,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return ii(r,({tag:p,type:m,value:f,valueSize:b})=>{if(p===21419){let g=We(f,m);l=ca(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=We(f,m):p===17545?a=We(f,m):p===21420&&l===475249515?u=We(f,m):p===374648427?ii(f,({tag:g,type:S,value:w})=>g===30321?(d=We(w,S)===1,!1):!0):s&&n&&(0,da.default)(av,p)&&(o=!0),!o}),zu(e,"Failed to parse webm Segment start"),zu(t,"Failed to parse webm Segment end"),zu(a,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},HR=r=>{if(FR(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},jR=(r,e)=>{let t=!1,i=!1,a=o=>rv(o.time)&&rv(o.position),s=[],n;return ii(r,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=We(l,u));break;case 183:break;case 241:n&&(n.position=We(l,u));break;default:t&&(0,da.default)(av,o)&&(i=!0)}return!(t&&i)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},QR=r=>{let e=0,t=!1;try{ii(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,da.default)(qR,i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=(0,da.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},sv={validateData:iv,parseInit:UR,getIndexRange:HR,parseSegments:jR,parseFeedableSegmentChunk:QR};var pa=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return sv;case"mp4":return Zg}}throw new ReferenceError(`Unsupported mime type ${r}`)};var ol=M(Pv(),1),Xv=M(wi(),1),Jv=M(qv(),1),Zv=M(Rt(),1),ul=M(Oi(),1);var Uv=M(je(),1),tl=r=>{let e=r.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=i;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=i[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return(0,Uv.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as U$,isNullable as zv}from"@vkontakte/videoplayer-shared";var Hv=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var jv=r=>{try{let e=F$(),t=r.match(e),{groups:i}=t??{};if(i){let a={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function F$(){let r="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
63
|
+
`}),f&&$b(a,u,f,o)};var Z=r=>new URL(r).hostname;import{assertNever as Hb,assertNonNullable as jb,combine as xL,debounce as PL,ErrorCategory as Qb,filter as Gb,filterChanged as kL,isNonNullable as Du,map as Vs,merge as Wb,observableFrom as wL,once as AL,Subscription as LL,ValueSubject as Cu,videoQualityToHeight as Yb,videoSizeToQuality as RL}from"@vkontakte/videoplayer-shared";var Nb=M(Rt(),1);var Cb=M(je(),1),Db=r=>{if(r instanceof DOMException&&(0,Cb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))},ve=async(r,e)=>{let t=r.muted;try{await r.play()}catch(i){if(!Db(i))return!1;if(e&&e(),t)return console.warn(i),!1;r.muted=!0;try{await r.play()}catch(a){return Db(a)&&(r.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as Ms,isNullable as nL,assertNonNullable as $r}from"@vkontakte/videoplayer-shared";var Bb=M(Oi(),1);import{isNonNullable as Vb,assertNonNullable as $s,now as aL}from"@vkontakte/videoplayer-shared";function ee(){return aL()}function Lu(r){return ee()-r}function Ru(r){let e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=n=>i.test(n);return{resolve:(n,o,u=!1)=>{a(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 Ob(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function Ni(r,e,t,i){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,m="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;$s(d);let P=Lu(d),U;if(P<b){U=b-P,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,I()},S=P=>(s=P,v),k=P=>(c=P,v),x=()=>(m="json",v),R=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},y=P=>(p=P,v),I=()=>{d=ee(),n=new a,n.open("get",r);let P=0,U,Le=0,Re=()=>($s(d),Math.max(d,Math.max(U||0,Le||0)));if(s&&n.addEventListener("progress",A=>{let C=ee();s.updateChunk&&A.loaded>P&&(s.updateChunk(Re(),A.loaded-P),P=A.loaded,U=C)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>R())),n.addEventListener("load",()=>{if(u)return;$s(n);let A=n.status;if(A>=200&&A<300){let{response:C,responseType:_}=n,w=C?.byteLength;if(typeof w=="number"&&s){let H=w-P;H&&s.updateChunk&&s.updateChunk(Re(),H)}_==="json"&&(!C||!(0,Bb.default)(C).length)?R():(c&&c(),e(C))}else R()}),n.addEventListener("error",()=>{R()}),p){let A=()=>{$s(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Le=ee(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=m,n.send(),v},v={withBitrateReporting:S,withParallel:y,withJSONResponse:x,withRetryCount:P=>(l=P,v),withRetryInterval:(P,U)=>(Vb(P)&&(b=P),Vb(U)&&(f=U),v),withTimeout:P=>(o=P,v),withFinally:k,send:I,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return v}var Lr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&i>0){let s=a*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var _b=M(Oi(),1);var Rr=class{constructor(e,t,i,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ee(),a=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=ee()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ni(t,s,()=>a("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=ee()}_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=ee();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,_b.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as oL}from"@vkontakte/videoplayer-shared";var Ds=1e4,$u=3;var uL=6e4,lL=10,cL=1,dL=500,Mr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new oL,this.chunkRateEstimator=new Lr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ru(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Ru(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,i,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Tb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Nb.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return a||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ms(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ob(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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 Rr($u,Ds,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let R=s&&(!d||d===this.rep);return R||t("Not running!"),R},p=(R,y,I)=>{u&&u.abort(),u=Ni(this.urlResolver.resolve(R,!1),y,I,()=>this._retryCallback()).withTimeout(Ds).withBitrateReporting(this.bitrateSwitcher).withRetryCount($u).withFinally(()=>{u=null}).send()},m=(R,y,I)=>{$r(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(R,!1),y,I,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=R=>{let y=i.playbackRate;i.playbackRate!==R&&(t(`Playback rate switch: ${y}=>${R}`),i.playbackRate=R)},b=R=>{this.lowLatency=R,t(`lowLatency changed to ${R}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let R=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let I=ee()-1e4,L=0;for(let F=0;F<this.bufferStates.length;F++){let q=this.bufferStates[F];R=Math.min(R,q.buf),q.ts<I&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${R} drop=${L} jitter=${this.sourceJitter}`);let G=R-cL;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)}},S=R=>{let y,I=()=>y&&y.start?y.start.length:0,L=A=>y.start[A]/1e3,G=A=>y.dur[A]/1e3,F=A=>y.fragIndex+A,q=(A,C)=>({chunkIdx:F(A),startTS:L(A),dur:G(A),discontinuity:C}),v=()=>{let A=0;if(y&&y.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,_=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,w=C;this.sourceJitter>1&&(w+=this.sourceJitter-1);let H=y.dur.length-1;for(;H>=0&&(w-=y.dur[H],!(w<=0));--H);A=Math.min(H,y.dur.length-1-_),A=Math.max(A,0)}return q(A,!0)},P=A=>{let C=I();if(!(C<=0)){if(Ms(A)){for(let _=0;_<C;_++)if(L(_)>A)return q(_)}return v()}},U=A=>{let C=I(),_=A?A.chunkIdx+1:0,w=_-y.fragIndex;if(!(C<=0)){if(!A||w<0||w-C>lL)return t(`Resync: offset=${w} bChunks=${C} chunk=`+JSON.stringify(A)),v();if(!(w>=C))return q(_-y.fragIndex,!1)}},Le=(A,C,_)=>{l&&l.abort(),l=Ni(this.urlResolver.resolve(A,!0,this.lowLatency),C,_,()=>this._retryCallback()).withTimeout(Ds).withRetryCount($u).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,C)=>{Le(R,_=>{if(!c())return;y=_;let w=!!y.lowLatency;w!==this.lowLatency&&b(w);let H=0;for(let $e=0;$e<y.dur.length;++$e)H+=y.dur[$e];H>0&&($r(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(H/y.dur.length)),a({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,A(P(C))},()=>this._handleNetworkError())},nextChunk:U}},k=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),$r(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:R=>{let{videoElement:y,logger:I}=this.params,L=S(e.jidxUrl),G,F,q,v,P=0,U,Le,Re,A=()=>{U&&(clearTimeout(U),U=void 0);let V=Math.max(dL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),te=P+V,oe=ee(),X=Math.min(1e4,te-oe);P=oe;let Ke=()=>{l||c()&&L.seek(()=>{c()&&(P=ee(),C(),A())})};X>0?U=window.setTimeout(()=>{this.paused?A():Ke()},X):Ke()},C=()=>{let V;for(;V=L.nextChunk(v);)v=V,di(V);let te=L.nextChunk(q);if(te){if(q&&te.discontinuity){I("Detected discontinuity; restarting playback"),this.paused?A():(k(),this._initPlayerWith(e));return}$e(te)}else A()},_=(V,te)=>{if(!c()||!this.sourceBuffer)return;let oe,X,Ke,Oe=_e=>{window.setTimeout(()=>{c()&&_(V,te)},_e)};if(this.sourceBuffer.updating)I("Source buffer is updating; delaying appendBuffer"),Oe(100);else{let _e=ee(),nt=y.currentTime;!this.paused&&y.buffered.length>1&&Le===nt&&_e-Re>500&&(I("Stall suspected; trying to fix"),this._fixupStall()),Le!==nt&&(Le=nt,Re=_e);let St=this._getBufferSizeSec();if(St>30)I(`Buffered ${St} seconds; delaying appendBuffer`),Oe(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:_e,buf:St}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),te&&te()}catch(ot){if(ot.name==="QuotaExceededError")I("QuotaExceededError; delaying appendBuffer"),Ke=this.sourceBuffer.buffered.length,Ke!==0&&(oe=this.sourceBuffer.buffered.start(0),X=nt,X-oe>4&&this.sourceBuffer.remove(oe,X-3)),Oe(1e3);else throw ot}}},w=()=>{F&&G&&(I([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(q)]),_(F,function(){F=null,C()}))},H=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),$e=V=>{c()&&m(H(V),(te,oe)=>{if(c()){if(oe/=1e3,F=te,q=V,n=V.startTS,oe){let X=Math.min(10,V.dur/oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*X:X}w()}},()=>this._handleNetworkError())},di=V=>{c()&&($r(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(H(V),!1)))},ze=V=>{c()&&(e.cachedHeader=V,_(V,()=>{G=!0,w()}))};s=!0,L.seek(V=>{if(c()){if(P=ee(),!V){A();return}v=V,!nL(R)||V.startTS>R?$e(V):(q=V,C())}},R),e.cachedHeader?ze(e.cachedHeader):p(e.headerUrl,ze,()=>this._handleNetworkError())},stop:k,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Ms(a)&&(a+=.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,$r(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ms(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(m=this._getBufferSizeSec(),f=c/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,m)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,m)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Lu(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let m=s.updateChunk(c,p);return m&&l(),m},notifySwitch:c=>{let p=ee();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ni(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ds).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;ve(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&a.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):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},uL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ub=M(ki(),1);import{debounce as pL,filter as Fb,fromEvent as hL,interval as mL,isHigher as fL,isInvariantQuality as bL,isLower as gL,merge as vL,Subject as qb,Subscription as SL}from"@vkontakte/videoplayer-shared";var Mu=class{constructor(){this.onDroopedVideoFramesLimit$=new qb;this.subscription=new SL;this.playing=!1;this.tracks=[];this.forceChecker$=new qb;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!bL(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(i-a)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&fL(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(hL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=mL(this.droppedFramesChecker.checkTime).pipe(Fb(()=>this.playing),Fb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(pL(this.droppedFramesChecker.checkTime)),i=vL(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,Ub.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>gL(i,a)?-1:1)?.[0]?.[0];return 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}},Cs=Mu;import{map as yL,Observable as TL}from"@vkontakte/videoplayer-shared";import{fromEvent as IL}from"@vkontakte/videoplayer-shared";var Dr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var EL=(r,e)=>new TL(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Dr()))},{...i,...e});a.observe(r);let s=IL(document,"visibilitychange").pipe(yL(n=>!document.hidden||Dr())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe}}),Be=EL;var $L=["paused","playing","ready"],ML=["paused","playing","ready"],Cr=class{constructor(e){this.subscription=new LL;this.videoState=new $("stopped");this.representations$=new Cu([]);this.droppedFramesManager=new Cs;this.maxSeekBackTime$=new Cu(1/0);this.zeroTime$=new Cu(void 0);this.liveOffset=new pt;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Qb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let a of t){let s=a.name??a.index.toString(10),n=Lt(a.name)??RL(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};i.push({track:l,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Du(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Vu.default)(ML,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Vu.default)($L,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ae(this.params.source.url,u))}return;default:return Hb(e)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Qb.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Wb(this.videoState.stateChangeStarted$.pipe(Vs(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Vs(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=me(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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=ge(this.video);this.subscription.add(this.representations$.pipe(Vs(a=>a.map(({track:s})=>s)),Gb(a=>!!a.length),AL()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:a}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(kL(),Vs(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(xL({zeroTime:this.zeroTime$.pipe(Gb(Du)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(be(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a,min:s}})=>{this.dash.setAutoQualityLimits({max:a&&Yb(a),min:s&&Yb(s)}),this.params.output.autoVideoTrackLimits$.next({max:a,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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":this.params.desiredState.playbackState.getTransition()?.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 Hb(a.to)}},t)).add(Wb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,wL(["init"])).pipe(PL(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),fe(this.video)}createLiveDashPlayer(){let e=new Mr({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(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!i&&Du(t)?t:Mt(e.map(({track:l})=>l),{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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:d})=>d.id===s)?.representation;jb(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;jb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ae(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var zb=Cr;var ES=M(je(),1);var rt=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){let a=r.start(i)*1e3,s=r.end(i)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as yM,assertNonNullable as TM,debounce as IM,ErrorCategory as SS,filter as yS,filterChanged as Ea,fromEvent as EM,isNonNullable as TS,map as Il,merge as rn,observableFrom as El,once as IS,Subscription as xM}from"@vkontakte/videoplayer-shared";var Bs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let a=0,s=i.length;a<s;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let a=0,s=i.length;a<s;a++){let n=i[a];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}},Fi=class extends Bs{constructor(){super(),this.listeners||Bs.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)}},Vr=class{constructor(){Object.defineProperty(this,"signal",{value:new Fi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Vr.prototype[Symbol.toStringTag]="AbortController",Fi.prototype[Symbol.toStringTag]="AbortSignal");function Os(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function Bu(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!Os({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((m,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Br=Os({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Kb=Br?Bu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ge=Br?Kb.fetch:window.fetch,aN=Br?Kb.Request:window.Request,se=Br?Vr:window.AbortController,sN=Br?Fi:window.AbortSignal;var vl=M(_u(),1);var Fs=M(Rt(),1);var mt=()=>window.ManagedMediaSource||window.MediaSource,_s=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),bg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),gg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Hs,clientChecker as qs}from"@vkontakte/videoplayer-shared";var Us=document.createElement("video"),rR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',aR='video/mp4; codecs="hev1.1.6.L93.B0"',vg='video/webm; codecs="vp09.00.10.08"',Sg='video/webm; codecs="av01.0.00M.08"',sR='audio/mp4; codecs="mp4a.40.2"',nR='audio/webm; codecs="opus"',Or={mms:_s(),mse:bg(),hls:!!(Us.canPlayType?.("application/x-mpegurl")||Us.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Se={mp4:!!Us.canPlayType?.("video/mp4"),webm:!!Us.canPlayType?.("video/webm"),cmaf:!0},ye={h264:!!mt()?.isTypeSupported?.(rR),h265:!!mt()?.isTypeSupported?.(aR),vp9:!!mt()?.isTypeSupported?.(vg),av1:!!mt()?.isTypeSupported?.(Sg),aac:!!mt()?.isTypeSupported?.(sR),opus:!!mt()?.isTypeSupported?.(nR)},qi=(ye.h264||ye.h265)&&ye.aac,ei,oR=async()=>{if(!window.navigator.mediaCapabilities)return;let r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:Sg}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:vg}})]);ei={DASH_WEBM_AV1:e,DASH_WEBM:t}};oR().catch(r=>{console.error(r)});var Ui=Or.hls&&Se.mp4,yg=()=>Object.keys(ye).filter(r=>ye[r]),Tg=(r,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let a=Or.mse&&(!i||!!window.MediaStreamTrack)||Or.mms&&t;return r.filter(s=>{switch(s){case"DASH_SEP":return a&&Se.mp4&&qi;case"DASH_WEBM":return a&&Se.webm&&ye.vp9&&ye.opus;case"DASH_WEBM_AV1":return a&&Se.webm&&ye.av1&&ye.opus;case"DASH_STREAMS":return a&&(Se.mp4&&qi||Se.webm&&(ye.vp9||ye.av1)&&(ye.opus||ye.aac));case"DASH_LIVE":return a&&Se.mp4&&qi;case"DASH_LIVE_CMAF":return a&&Se.mp4&&qi&&Se.cmaf;case"DASH_ONDEMAND":return a&&Se.mp4&&qi;case"HLS":case"HLS_ONDEMAND":return Ui||e&&a&&Se.mp4&&qi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Ui;case"MPEG":return Se.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Or.webrtc&&Or.ws&&ye.h264&&(Se.mp4||Se.webm);default:return Hs(s)}})},Ns=r=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(r){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return ei?ei[t].smooth?[t,e]:ei[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ei?ei[t].powerEfficient?[t,e]:ei[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Hs(r)}return[e,t]},Ig=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Ns(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(qs.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...Ns(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ns(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ns(r),...a,"HLS","HLS_ONDEMAND"];default:Hs(e)}return Ui?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Eg=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...a],n=[...a,...i],o,u=qs.isMac&&qs.isSafari;if(qs.isAndroid)switch(r){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Hs(r)}else Ui&&!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"]},Nu=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],xg=r=>{if(r.size===0)return;if(r.size===1){let t=r.values().next();return(0,Fs.default)(t.value.split("."),0)}for(let t of r){let i=(0,Fs.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=r.values().next();return(0,Fs.default)(e.value.split("."),0)};var Qg=M(jg(),1);import{ErrorCategory as Nr}from"@vkontakte/videoplayer-shared";var Gg=r=>{if(!r)return{id:"EmptyResponse",category:Nr.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:Nr.NETWORK,message:`UV Error ${r}`};let e=(0,Qg.default)(r).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Nr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(r,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Nr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Nr.PARSER,message:"Response is valid XML, but parser failed"}};var Dt=(r,e,t=0)=>{for(let i=0;i<r.length;i++)if(r.start(i)*1e3-t<=e&&r.end(i)*1e3+t>e)return!0;return!1};import{abortable as fl,assertNonNullable as ni,clientChecker as eM,combine as oi,ErrorCategory as at,filter as ya,filterChanged as bl,flattenObject as Ta,fromEvent as ui,getTraceSubscriptionMethod as tM,interval as gl,isNonNullable as dS,map as Yi,merge as li,now as iM,Subject as pS,Subscription as hS,tap as rM,throttle as aM,ValueSubject as z}from"@vkontakte/videoplayer-shared";var Qs=M(je(),1),Gi=M(Rt(),1),Gs=M(_u(),1);var xR=(r,e={})=>{let i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},PR=r=>window.clearTimeout(r),Wg=r=>typeof r=="function"&&r?.toString().endsWith("{ [native code] }"),Yg=!Wg(window.requestIdleCallback)||!Wg(window.cancelIdleCallback),ju=Yg?xR:window.requestIdleCallback,Fr=Yg?PR:window.cancelIdleCallback;var rS=M(Es(),1);import{assertNever as kR,ErrorCategory as zg,clientChecker as Qu,Subject as Kg}from"@vkontakte/videoplayer-shared";var wR=18,Xg=!1;try{Xg=Qu.isSafari&&!!Qu.macVersion&&Qu.macVersion<=wR}catch(r){console.error(r)}var Gu=class{constructor(e){this.bufferFull$=new Kg;this.error$=new Kg;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:zg.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,a=s=>{this.abortRequested=!1,t(s)};Xg&&e?i={operation:"safariAbort",init:e,callback:a}:i={operation:"abort",callback:a};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:zg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:kR(t)}}},Jg=Gu;var Wu=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};import{abortable as Vt,assertNonNullable as Te,clientChecker as H$,ErrorCategory as gt,fromEvent as cl,getExponentialDelay as dl,isNonNullable as Qi,isNullable as ne,now as js,once as j$,Subject as Q$,Subscription as G$,ValueSubject as ri}from"@vkontakte/videoplayer-shared";var B=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let a=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,a)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 Hi=class extends B{};var qr=class extends B{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let a=this.content.byteOffset,s=a+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(a,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Ur=class extends B{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let a=this.readString(4);this.compatibleBrands.push(a),i-=4}}};var Hr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Q=class extends B{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var jr=class extends Q{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 Qr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gr=class extends B{constructor(e,t){super(e,t),this.data=this.content}};var ti=class extends Q{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Wr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zr=class extends Q{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 Kr=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Xr=class extends Q{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Jr=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zr=class extends Q{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 ea=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ta=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ia=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ra=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var aa=class extends Q{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var sa=class extends Q{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var na=class extends Q{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)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 oa=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends Q{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var la=class extends B{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var LR={ftyp:Ur,moov:Hr,mvhd:jr,moof:Qr,mdat:Gr,sidx:ti,trak:Wr,mdia:Jr,mfhd:ia,tkhd:Zr,traf:ra,tfhd:aa,tfdt:sa,trun:na,minf:ea,sv3d:Yr,st3d:zr,prhd:Kr,proj:ta,equi:Xr,uuid:qr,stbl:oa,stsd:ua,avc1:la,unknown:Hi},ft=class r{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=LR[e];return i?new i(t,new r):new Hi(t,new r)}};var Ct=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],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 $R=new TextDecoder("ascii"),MR=r=>$R.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",DR=r=>{let e=new ti(r,new ft),t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},CR=(r,e)=>{let i=new ft().parse(r),a=new Ct(i),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(r.buffer,l,c)},VR=r=>{let t=new ft().parse(r),i=new Ct(t),a={},s=i.findAll("uuid");return s.length?s[s.length-1]:a},BR=r=>{let t=new ft().parse(r);return new Ct(t).find("sidx")?.timescale},OR=(r,e)=>{let i=new ft().parse(r),s=new Ct(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},_R=r=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new ft().parse(r),a=new Ct(i);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.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},Zg={validateData:MR,parseInit:_R,getIndexRange:()=>{},parseSegments:DR,parseFeedableSegmentChunk:CR,getChunkEndTime:OR,getServerLatencyTimestamps:VR,getTimescaleFromIndex:BR};var da=M(je(),1);import{assertNonNullable as zu,isNonNullable as rv,isNullable as FR}from"@vkontakte/videoplayer-shared";import{assertNever as NR}from"@vkontakte/videoplayer-shared";var ev={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"}},tv=r=>{let e=r.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ca(r,t),a=i in ev,s=a?ev[i].type:"binary",n=r.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(r.buffer,r.byteOffset+t+1,o-1),l=n&255>>o,d=ca(u),c=l*2**((o-1)*8)+d,p=t+o,m;return p+c>r.byteLength?m=new DataView(r.buffer,r.byteOffset+p):m=new DataView(r.buffer,r.byteOffset+p,c),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:m,valueSize:c}},ca=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{let t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},We=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return ca(r);case"float":return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case"string":return new TextDecoder("ascii").decode(r);case"utf8":return new TextDecoder("utf-8").decode(r);case"date":return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case"master":return r;case"binary":return r;default:NR(e)}},ii=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=tv(i);if(!e(a))return;a.type==="master"&&ii(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},iv=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=tv(r);return ii(a.value,({tag:s,type:n,value:o})=>(s===17143?e=We(o,n):s===17026?t=We(o,n):s===17029&&(i=We(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var av=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],qR=[231,22612,22743,167,171,163,160,175],UR=r=>{let e,t,i,a,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return ii(r,({tag:p,type:m,value:f,valueSize:b})=>{if(p===21419){let g=We(f,m);l=ca(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=We(f,m):p===17545?a=We(f,m):p===21420&&l===475249515?u=We(f,m):p===374648427?ii(f,({tag:g,type:S,value:k})=>g===30321?(d=We(k,S)===1,!1):!0):s&&n&&(0,da.default)(av,p)&&(o=!0),!o}),zu(e,"Failed to parse webm Segment start"),zu(t,"Failed to parse webm Segment end"),zu(a,"Failed to parse webm Segment duration"),i=i??1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},HR=r=>{if(FR(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},jR=(r,e)=>{let t=!1,i=!1,a=o=>rv(o.time)&&rv(o.position),s=[],n;return ii(r,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=We(l,u));break;case 183:break;case 241:n&&(n.position=We(l,u));break;default:t&&(0,da.default)(av,o)&&(i=!0)}return!(t&&i)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},QR=r=>{let e=0,t=!1;try{ii(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,da.default)(qR,i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=(0,da.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},sv={validateData:iv,parseInit:UR,getIndexRange:HR,parseSegments:jR,parseFeedableSegmentChunk:QR};var pa=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return sv;case"mp4":return Zg}}throw new ReferenceError(`Unsupported mime type ${r}`)};var ol=M(Pv(),1),Xv=M(ki(),1),Jv=M(qv(),1),Zv=M(Rt(),1),ul=M(Oi(),1);var Uv=M(je(),1),tl=r=>{let e=r.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=i;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=i[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return(0,Uv.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as U$,isNullable as zv}from"@vkontakte/videoplayer-shared";var Hv=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var jv=r=>{try{let e=F$(),t=r.match(e),{groups:i}=t??{};if(i){let a={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function F$(){let r="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
64
64
|
(?<language>${`(?:[a-z]{2,3}(?:-${r})?|[a-z]{4}|[a-z]{5,8})`})
|
|
65
65
|
(-(?<script>[a-z]{4}))?
|
|
66
66
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
67
67
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
68
68
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
69
69
|
(?:-(?<privateuse>(?:${e})))?
|
|
70
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var rl=M(Rt(),1);import{videoSizeToQuality as q$}from"@vkontakte/videoplayer-shared";var Qv=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s,streamId:n})=>{let o=(s?Lt(s):void 0)??q$({width:e,height:t});return o&&{id:r,quality:o,bitrate:i,size:{width:e,height:t},fps:a,streamId:n}},Gv=({id:r,bitrate:e})=>({id:r,bitrate:e}),Wv=({language:r,label:e},{id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Yv=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),al=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,rl.default)(i.split("."),0),isDefault:a}),sl=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,rl.default)(a.split("."),0)}),nl=r=>"url"in r,ce=r=>r.type==="template",ha=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var Kv=r=>{if(!r?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),a=i?.[1]==="-"?-1:1,s={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},bt=(r,e)=>{let t=r;t=(0,ol.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,Xv.default)(i)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,ol.default)(t,n,(o,u)=>zv(s)?o:zv(u)?s:(0,Jv.default)(s,parseInt(u,10),"0"))}return t},eS=(r,e)=>{let i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(y=>y.textContent?.trim()??""),o=(0,Zv.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,c,p=s.getAttribute("mediaPresentationDuration"),f=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((y,I)=>({...y,[I.id]:I.children}),{}),S=b.reduce((y,I)=>({...y,[I.id]:I.getAttribute("duration")}),{});p?c=Kv(p):(0,ul.default)(S).filter(y=>y).length&&!u?c=(0,ul.default)(S).reduce((y,I)=>y+(Kv(I)??0),0):f&&(c=parseInt(f,10));let w=0,x=s.getAttribute("profiles")?.split(",")??[];for(let y of b.map(I=>I.id))for(let I of g[y]){let L=I.getAttribute("id")??"id"+(w++).toString(10),G=I.getAttribute("mimeType")??"",F=I.getAttribute("codecs")??"",q=I.getAttribute("contentType")??G?.split("/")[0],v=I.getAttribute("profiles")?.split(",")??[],P=jv(I.getAttribute("lang")??"")??{},U=I.querySelector("Label")?.textContent?.trim()??void 0,Le=I.querySelectorAll("Representation"),Re=I.querySelector("SegmentTemplate"),A=I.querySelector("Role")?.getAttribute("value")??void 0,C=q,_={id:L,language:P.language,isDefault:A==="main",label:U,codecs:F,hdr:C==="video"&&tl(F),mime:G,representations:[]};for(let k of Le){let H=k.getAttribute("lang")??void 0,$e=U??I.getAttribute("label")??k.getAttribute("label")??void 0,di=k.querySelector("BaseURL")?.textContent?.trim()??"",ze=new URL(di||o,e).toString(),V=k.getAttribute("mimeType")??G,te=k.getAttribute("codecs")??F??"",oe;if(q==="text"){let X=k.getAttribute("id")||"",Ke=P.privateuse?.includes("x-auto")||X.includes("_auto"),Oe=k.querySelector("SegmentTemplate");if(Oe){let _e={representationId:k.getAttribute("id")??void 0,bandwidth:k.getAttribute("bandwidth")??void 0},nt=parseInt(k.getAttribute("bandwidth")??"",10)/1e3,St=parseInt(Oe.getAttribute("startNumber")??"",10)??1,ot=parseInt(Oe.getAttribute("timescale")??"",10),Sn=Oe.querySelectorAll("SegmentTimeline S")??[],pi=Oe.getAttribute("media");if(!pi)continue;let Ba=[],Oa=0,_a="",hi=0,Xi=St,ue=0;for(let Ne of Sn){let Ft=parseInt(Ne.getAttribute("d")??"",10),Me=parseInt(Ne.getAttribute("r")??"",10)||0,yt=parseInt(Ne.getAttribute("t")??"",10);ue=Number.isFinite(yt)?yt:ue;let qt=Ft/ot*1e3,mi=ue/ot*1e3;for(let Xe=0;Xe<Me+1;Xe++){let Tt=bt(pi,{..._e,segmentNumber:Xi.toString(10),segmentTime:(ue+Xe*Ft).toString(10)}),fi=(mi??0)+Xe*qt,Zi=fi+qt;Xi++,Ba.push({time:{from:fi,to:Zi},url:Tt})}ue+=(Me+1)*Ft,Oa+=(Me+1)*qt}hi=ue/ot*1e3,_a=bt(pi,{..._e,segmentNumber:Xi.toString(10),segmentTime:ue.toString(10)});let Ji={time:{from:hi,to:1/0},url:_a},ut={type:"template",baseUrl:ze,segmentTemplateUrl:pi,initUrl:"",totalSegmentsDurationMs:Oa,segments:Ba,nextSegmentBeyondManifest:Ji,timescale:ot};oe={id:X,kind:"text",segmentReference:ut,profiles:[],duration:c,bitrate:nt,mime:"",codecs:"",width:0,height:0,isAuto:Ke}}else oe={id:X,isAuto:Ke,kind:"text",url:ze}}else{let X=k.getAttribute("contentType")??V?.split("/")[0]??q,Ke=I.getAttribute("profiles")?.split(",")??[],Oe=parseInt(k.getAttribute("width")??"",10),_e=parseInt(k.getAttribute("height")??"",10),nt=parseInt(k.getAttribute("bandwidth")??"",10)/1e3,St=k.getAttribute("frameRate")??"",ot=k.getAttribute("quality")??void 0,Sn=St?Hv(St):void 0,pi=k.getAttribute("id")??"id"+(w++).toString(10),Ba=X==="video"?`${_e}p`:X==="audio"?`${nt}Kbps`:te,Oa=`${pi}@${Ba}`,_a=[...x,...v,...Ke],hi,Xi=k.querySelector("SegmentBase"),ue=k.querySelector("SegmentTemplate")??Re;if(Xi){let ut=k.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,Ft]=ut.split("-").map(Tt=>parseInt(Tt,10)),Me={from:Ne,to:Ft},yt=k.querySelector("SegmentBase")?.getAttribute("indexRange"),[qt,mi]=yt?yt.split("-").map(Tt=>parseInt(Tt,10)):[],Xe=yt?{from:qt,to:mi}:void 0;hi={type:"byteRange",url:ze,initRange:Me,indexRange:Xe}}else if(ue){let ut={representationId:k.getAttribute("id")??void 0,bandwidth:k.getAttribute("bandwidth")??void 0},Ne=parseInt(ue.getAttribute("timescale")??"",10),Ft=ue.getAttribute("initialization")??"",Me=ue.getAttribute("media"),yt=parseInt(ue.getAttribute("startNumber")??"",10)??1,qt=bt(Ft,ut);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let mi=ue.querySelectorAll("SegmentTimeline S")??[],Xe=[],Tt=0,fi="",Zi=0;if(mi.length){let Na=yt,Fe=0;for(let bi of mi){let Je=parseInt(bi.getAttribute("d")??"",10),Ut=parseInt(bi.getAttribute("r")??"",10)||0,Fa=parseInt(bi.getAttribute("t")??"",10);Fe=Number.isFinite(Fa)?Fa:Fe;let yn=Je/Ne*1e3,yy=Fe/Ne*1e3;for(let qa=0;qa<Ut+1;qa++){let Ty=bt(Me,{...ut,segmentNumber:Na.toString(10),segmentTime:(Fe+qa*Je).toString(10)}),Fl=(yy??0)+qa*yn,Iy=Fl+yn;Na++,Xe.push({time:{from:Fl,to:Iy},url:Ty})}Fe+=(Ut+1)*Je,Tt+=(Ut+1)*yn}Zi=Fe/Ne*1e3,fi=bt(Me,{...ut,segmentNumber:Na.toString(10),segmentTime:Fe.toString(10)})}else if(U$(c)){let Fe=parseInt(ue.getAttribute("duration")??"",10)/Ne*1e3,bi=Math.ceil(c/Fe),Je=0;for(let Ut=1;Ut<bi;Ut++){let Fa=bt(Me,{...ut,segmentNumber:Ut.toString(10),segmentTime:Je.toString(10)});Xe.push({time:{from:Je,to:Je+Fe},url:Fa}),Je+=Fe}Zi=Je,fi=bt(Me,{...ut,segmentNumber:bi.toString(10),segmentTime:Je.toString(10)})}let Sy={time:{from:Zi,to:1/0},url:fi};hi={type:"template",baseUrl:ze,segmentTemplateUrl:Me,initUrl:qt,totalSegmentsDurationMs:Tt,segments:Xe,nextSegmentBeyondManifest:Sy,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!X||!V)continue;let Ji={video:"video",audio:"audio",text:"text"}[X];if(!Ji)continue;C||=Ji,oe={id:Oa,kind:Ji,segmentReference:hi,profiles:_a,duration:c,bitrate:nt,mime:V,codecs:te,width:Oe,height:_e,fps:Sn,quality:ot}}_.language||=H,_.label||=$e,_.mime||=V,_.codecs||=te,_.hdr||=C==="video"&&tl(te),_.representations.push(oe)}if(C){let k=a[C].find(H=>H.id===_.id);if(k&&_.representations.every(H=>ce(H.segmentReference)))for(let H of k.representations){let di=_.representations.find(V=>V.id===H.id)?.segmentReference,ze=H.segmentReference;ze.segments.push(...di.segments),ze.nextSegmentBeyondManifest=di.nextSegmentBeyondManifest}else a[C].push(_)}}return{dynamic:u,liveAvailabilityStartTime:d,duration:c,streams:a,baseUrls:n}};var iS=M(je(),1);import{isNonNullable as tS}from"@vkontakte/videoplayer-shared";var de=(r,e)=>tS(r)&&tS(e)&&r.readyState==="open"&&(0,iS.default)([...r.activeSourceBuffers],e);var ma=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ri(0);this.currentLowLatencySegmentLength$=new ri(0);this.currentSegmentLength$=new ri(0);this.onLastSegment$=new ri(!1);this.fullyBuffered$=new ri(!1);this.playingRepresentation$=new ri(void 0);this.playingRepresentationInit$=new ri(void 0);this.error$=new Q$;this.gaps=[];this.subscription=new G$;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new se;this.switchAbortController=new se;this.destroyAbortController=new se;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=Vt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Te(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Jg(this.sourceBuffer),this.subscription.add(cl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(cl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:gt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!de(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Wu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=rt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Te(i,"No init buffer for starting representation"),Te(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Vt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Te(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Te(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Qi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Vt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Te(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Te(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Qi(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=Vt(this.destroyAbortController.signal,async function*(e){let t=(0,Gs.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!ce(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);Te(a);let s=this.segments.get(i);Te(s,"No segments for starting representation");let n=this.initData.get(i);if(Te(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new se,Vt(this.switchAbortController.signal,async function*(i,a=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Te(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ne(o)||ne(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Te(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Qi(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ne(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new se,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ne(e)||ne(this.downloadingRepresentationId)||ne(this.playingRepresentationId)||ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer)||Qi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Te(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let a=i.find(l=>e>=l.time.from&&e<l.time.to);Qi(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=rt(this.sourceBuffer.buffered,e),c=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=c)}if(isFinite(this.bufferLimit)&&Wu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=rt(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if((0,Qs.default)(o,a))l="high";else{let d=(0,Gi.default)(o,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&rt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Gi.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+a}),i=s.time.to;Qi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=(0,Gs.default)(e?.streams[this.kind],a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Gs.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!ce(i.segmentReference))return;let a=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,Gi.default)(n,-1)?.time.to??0,u=a?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=a.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Te(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let a=i.segmentReference;if(!ce(a))return;let s=this.segments.get(i.id)??[],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,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*a.timescale/1e3).toString(10),l=bt(a.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&Fr&&Fr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Fr&&Fr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let a=e.findIndex(({status:c,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),w=this.preloadOnly&&p<=i+S||m<=i+S;return(c==="none"||c==="partially_ejected"&&g&&w&&this.sourceBuffer&&de(this.mediaSource,this.sourceBuffer)&&!(Dt(this.sourceBuffer.buffered,p)&&Dt(this.sourceBuffer.buffered,m)))&&g&&w});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=a;c<s.length&&(n<=l||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){ce(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Vt(o,async function*(){let d=dl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=js(),!d)return;let c=new DataView(d),p=pa(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(c,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:m,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);m&&f&&this.currentLiveSegmentServerLatency$.next(f-m),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ha(d)||(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())ce(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Vt(n,async function*(){let u=dl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),cl(window,"online").pipe(j$()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=js(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ha(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ce(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,Gi.default)(e,0).byte.from,to:(0,Gi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=js(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ce(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let a=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=js();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Qs.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:a,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){a();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=pa(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,m=d<a,f=c<=a;if(!m)continue;let b=pa(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer))){!this.isLive&&H$.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Dt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Dt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:gt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",nl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let a of this.segments.get(i.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ju(()=>(0,rS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Vt(this.destroyAbortController.signal,async function*(){let o=dl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,pa(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&ce(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:gt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ne(e))return!1;let a=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],m=l[l.length-1];m.to>=c?m.to=Math.max(m.to,p):l.push(u[d])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=nl(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let m of p)(0,Qs.default)(["none","partially_ejected"],m.status)&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(a.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ne(e)?0:rt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let a={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){a=void 0;break}o>i.time.from&&o<i.time.to&&(a.from=o),n<i.time.to&&n>i.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=ju(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:gt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer)||ne(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let a=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:s})}let t=100;for(let i of this.segments.values())for(let a of i){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:gt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var fa=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var aS=r=>{let e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}};import{abortable as ba,assertNever as nS,fromEvent as oS,merge as W$,now as ga,Subscription as Y$,ValueSubject as pl,flattenObject as Wi}from"@vkontakte/videoplayer-shared";var sS=r=>{let e=new URL(r);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Ws=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new pl(void 0);this.lastConnectionReused$=new pl(void 0);this.lastRequestFirstBytes$=new pl(void 0);this.abortAllController=new se;this.subscription=new Y$;this.fetchManifest=ba(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=fa(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=sS(i));let a=yield Ge(i,{signal:this.abortAllController.signal}).catch(va);return a?(t.log("success",Wi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Wi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ba(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(l,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),l=v.toString();break}default:nS(t)}this.requestQuic&&(l=fa(l));let p=this.abortAllController.signal,m;if(n){let v=new se;if(m=W$(oS(this.abortAllController.signal,"abort"),oS(n,"abort")).subscribe(()=>{try{v.abort()}catch(P){va(P)}}),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(P){va(P)}p=v.signal}let f=ga();c.log("startRequest",Wi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield Ge(l,{priority:s,headers:d,signal:p}).catch(va),g=ga();if(!b)return c.error("error",{message:"No response in request"}),c.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){m?.unsubscribe();let v=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:v}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){m?.unsubscribe();let v=ga(),P={requestStartedAt:f,requestEndedAt:v,duration:v-f};return c.log("endRequest",Wi(P)),c.end(),b.arrayBuffer()}let[S,w]=b.body.tee(),x=S.getReader();o&&this.throughputEstimator?.trackStream(w,u);let R=0,y=new Uint8Array(0),I=!1,L=v=>{m?.unsubscribe(),I=!0,va(v)},G=ba(p,async function*({done:v,value:P}){if(R===0&&this.lastRequestFirstBytes$.next(ga()-f),p.aborted){m?.unsubscribe();return}if(!v&&P){let U=new Uint8Array(y.length+P.length);U.set(y),U.set(P,y.length),y=U,R+=P.byteLength,a?.(new DataView(y.buffer),R),yield x?.read().then(G,L)}}.bind(this));yield x?.read().then(G,L),m?.unsubscribe();let F=ga(),q={failed:I,requestStartedAt:f,requestEndedAt:F,duration:F-f};return I?(c.error("endRequest",Wi(q)),c.end(),null):(c.log("endRequest",Wi(q)),c.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=ba(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let m=t.parseInit(p),f=e.indexRange??t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,m,f);return{init:m,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=ba(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=aS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:nS(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},va=r=>{if(!ha(r))throw r};var ai=(r,e,t)=>t*e+(1-t)*r,hl=(r,e)=>r.reduce((t,i)=>t+i,0)/e,uS=(r,e,t,i)=>{let a=0,s=t,n=hl(r,e),o=e<i?e:i;for(let u=0;u<o;u++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};import{isNullable as z$,ValueSubject as lS}from"@vkontakte/videoplayer-shared";var Bt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new lS(e.initial),this.debounced$=new lS(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new le(`raw_${t}`),this.smoothedSeries$=new le(`smoothed_${t}`),this.reportedSeries$=new le(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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)&&(z$(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 Ys=class extends Bt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ai(this.slow,e,this.params.emaAlphaSlow),this.fast=ai(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var zs=class extends Bt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=hl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ai(this.emaSmoothed,e,this.params.emaAlpha);let i=uS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ks=class extends Bt{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?ai(this.smoothed,t,this.params.emaAlpha):t}};var si=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ys({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new zs({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Ks({initial:e,label:"liveEdgeDelay",...t})}};var ml=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};import{isNullable as K$,ValueSubject as X$}from"@vkontakte/videoplayer-shared";var Sa=class r{constructor(e,t){this.currentRepresentation$=new X$(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!K$(e))for(let t of this.representations)for(let i of t){let a=i.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=r.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>r.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&ce(t.segmentReference))}};var sM=["timeupdate","progress","play","seeked","stalled","waiting"],nM=["timeupdate","progress","loadeddata","playing","seeked"];var Xs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new hS;this.representationSubscription=new hS;this.state$=new $("none");this.currentVideoRepresentation$=new z(void 0);this.currentVideoRepresentationInit$=new z(void 0);this.currentAudioRepresentation$=new z(void 0);this.currentVideoSegmentLength$=new z(0);this.currentAudioSegmentLength$=new z(0);this.error$=new pS;this.lastConnectionType$=new z(void 0);this.lastConnectionReused$=new z(void 0);this.lastRequestFirstBytes$=new z(void 0);this.currentLiveTextRepresentation$=new z(null);this.isLive$=new z(!1);this.isActiveLive$=new z(!1);this.isLowLatency$=new z(!1);this.liveDuration$=new z(0);this.liveAvailabilityStartTime$=new z(void 0);this.bufferLength$=new z(0);this.liveLatency$=new z(void 0);this.liveLoadBufferLength$=new z(0);this.livePositionFromPlayer$=new z(0);this.currentStallDuration$=new z(0);this.videoLastDataObtainedTimestamp$=new z(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new pS;this.gapWatchdogActive=!1;this.destroyController=new se;this.initManifest=fl(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:at.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=fl(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:at.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=eS(e??"",this.manifestUrlString)}catch(n){let o=Gg(e)??{id:"ManifestParsing",category:at.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&mt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let n=(t.duration??0)/1e3;this.liveDuration$.next(-1*n)}let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=xg(l);if(d&&(a[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),m=a.video.some(f=>!f.hdr);eM.isHDR&&c&&p?a.video=a.video.filter(f=>f.hdr):m&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",Ta(s)),s}.bind(this));this.initRepresentations=fl(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ta({initialVideo:e,initialAudio:t,sourceHls:i})),ni(this.manifest),ni(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=c=>{this.representationSubscription.add(ui(c,"error").pipe(ya(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:at.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?gg():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&_s())if(i){let c=document.createElement("source");a(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],dS(t)){let c=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new ma("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}Sa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Sa(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(gl(1e3).subscribe(c=>{if(this.element?.paused){let p=xs(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,p+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(li(...nM.map(c=>ui(this.element,c))).pipe(Yi(c=>this.element?rt(this.element.buffered,this.element.currentTime*1e3):0),bl(),rM(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(li(ui(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(oi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Yi(({isActiveLive:p,isLowLatency:m})=>p&&m),bl()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||ml(this.element,1)})),this.representationSubscription.add(oi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ya(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(oi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$,currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(ya(({isActiveLive:p,isLowLatency:m,currentLowLatencySegmentLength:f})=>p&&m&&!!f)).subscribe(({currentLowLatencySegmentLength:p})=>{let m=this.liveDuration$.getValue()-p/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(oi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ya(({isLive:p})=>p),Yi(p=>({...p})),bl((p,m)=>m.bufferLength<p.bufferLength),Yi(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=xs(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(oi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=p-b;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(w)>g&&(x=1+Math.sign(w)*S),ml(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(oi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(aM(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(ni(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=xs(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,R=isFinite(p)?p:m,y=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),I=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLive$.next(I);let L="none";if(y?L="active_low_latency":this.isLowLatency$.getValue()&&I?(this.bufferManagers.forEach(G=>G.proceedLowLatencyLive()),L="active_low_latency"):b!==0&&R<S?L="live_forward_buffering":R<S+x&&(L="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),L==="live_forward_buffering"||L==="live_with_target_offset"){let G=c-(S+w),F=this.normolizeLiveOffset(Math.trunc(b+G/f)),q=Math.abs(F-b),v;!p||q<=this.tuning.dashCmafLive.offsetCalculationError?v=b:F>0&&q>this.tuning.dashCmafLive.offsetCalculationError?v=F:v=0,this.manifestUrlString=ae(this.manifestUrlString,v,2)}L!=="none"&&L!=="active_low_latency"&&(c=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:at.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=li(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Yi(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),d=li(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Yi(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));if(this.representationSubscription.add(li(this.forceEnded$,oi({allBuffersFull:l,someBufferEnded:d}).pipe(ya(({allBuffersFull:c,someBufferEnded:p})=>c&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream(),this.bufferManagers.forEach(c=>c.warmUpMediaSource())}catch(c){this.error$.next({id:"EndOfStream",category:at.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(li(...this.bufferManagers.map(c=>c.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(c=>this.source?.addEventListener("sourceopen",c))),!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,vl.default)((0,vl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),ce(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&dS(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=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=gl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:at.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ws({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=si.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){ni(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLive$.next(t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){ni(this.element),this.state$.setState("running"),this.subscription.add(li(...sM.map(e=>ui(this.element,e)),ui(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:at.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ui(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ui(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Dt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},a=iM(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,d=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset).catch(p=>{this.error$.next({id:"stallIntervalCallback",category:at.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:p})}),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",Ta(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=gl(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:at.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let a={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?a?.switchToWithPreviousAbort(t,i):a?.switchTo(t,i):a?.switchToOld(t,i)}async seek(e,t){ni(this.element),ni(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Dt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ta({requestedPosition:e,forcePrecise:t,position:i}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=tM(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=a&&u.to+n>a&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ta(i)))}}};var Js=class{constructor(e,t){this.fov=e,this.orientation=t}};var Zs=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var mS=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var rl=M(Rt(),1);import{videoSizeToQuality as q$}from"@vkontakte/videoplayer-shared";var Qv=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s,streamId:n})=>{let o=(s?Lt(s):void 0)??q$({width:e,height:t});return o&&{id:r,quality:o,bitrate:i,size:{width:e,height:t},fps:a,streamId:n}},Gv=({id:r,bitrate:e})=>({id:r,bitrate:e}),Wv=({language:r,label:e},{id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Yv=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),al=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,rl.default)(i.split("."),0),isDefault:a}),sl=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,rl.default)(a.split("."),0)}),nl=r=>"url"in r,ce=r=>r.type==="template",ha=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var Kv=r=>{if(!r?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),a=i?.[1]==="-"?-1:1,s={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},bt=(r,e)=>{let t=r;t=(0,ol.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,Xv.default)(i)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,ol.default)(t,n,(o,u)=>zv(s)?o:zv(u)?s:(0,Jv.default)(s,parseInt(u,10),"0"))}return t},eS=(r,e)=>{let i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(y=>y.textContent?.trim()??""),o=(0,Zv.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,c,p=s.getAttribute("mediaPresentationDuration"),f=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((y,I)=>({...y,[I.id]:I.children}),{}),S=b.reduce((y,I)=>({...y,[I.id]:I.getAttribute("duration")}),{});p?c=Kv(p):(0,ul.default)(S).filter(y=>y).length&&!u?c=(0,ul.default)(S).reduce((y,I)=>y+(Kv(I)??0),0):f&&(c=parseInt(f,10));let k=0,x=s.getAttribute("profiles")?.split(",")??[];for(let y of b.map(I=>I.id))for(let I of g[y]){let L=I.getAttribute("id")??"id"+(k++).toString(10),G=I.getAttribute("mimeType")??"",F=I.getAttribute("codecs")??"",q=I.getAttribute("contentType")??G?.split("/")[0],v=I.getAttribute("profiles")?.split(",")??[],P=jv(I.getAttribute("lang")??"")??{},U=I.querySelector("Label")?.textContent?.trim()??void 0,Le=I.querySelectorAll("Representation"),Re=I.querySelector("SegmentTemplate"),A=I.querySelector("Role")?.getAttribute("value")??void 0,C=q,_={id:L,language:P.language,isDefault:A==="main",label:U,codecs:F,hdr:C==="video"&&tl(F),mime:G,representations:[]};for(let w of Le){let H=w.getAttribute("lang")??void 0,$e=U??I.getAttribute("label")??w.getAttribute("label")??void 0,di=w.querySelector("BaseURL")?.textContent?.trim()??"",ze=new URL(di||o,e).toString(),V=w.getAttribute("mimeType")??G,te=w.getAttribute("codecs")??F??"",oe;if(q==="text"){let X=w.getAttribute("id")||"",Ke=P.privateuse?.includes("x-auto")||X.includes("_auto"),Oe=w.querySelector("SegmentTemplate");if(Oe){let _e={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},nt=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,St=parseInt(Oe.getAttribute("startNumber")??"",10)??1,ot=parseInt(Oe.getAttribute("timescale")??"",10),Sn=Oe.querySelectorAll("SegmentTimeline S")??[],pi=Oe.getAttribute("media");if(!pi)continue;let Ba=[],Oa=0,_a="",hi=0,Xi=St,ue=0;for(let Ne of Sn){let Ft=parseInt(Ne.getAttribute("d")??"",10),Me=parseInt(Ne.getAttribute("r")??"",10)||0,yt=parseInt(Ne.getAttribute("t")??"",10);ue=Number.isFinite(yt)?yt:ue;let qt=Ft/ot*1e3,mi=ue/ot*1e3;for(let Xe=0;Xe<Me+1;Xe++){let Tt=bt(pi,{..._e,segmentNumber:Xi.toString(10),segmentTime:(ue+Xe*Ft).toString(10)}),fi=(mi??0)+Xe*qt,Zi=fi+qt;Xi++,Ba.push({time:{from:fi,to:Zi},url:Tt})}ue+=(Me+1)*Ft,Oa+=(Me+1)*qt}hi=ue/ot*1e3,_a=bt(pi,{..._e,segmentNumber:Xi.toString(10),segmentTime:ue.toString(10)});let Ji={time:{from:hi,to:1/0},url:_a},ut={type:"template",baseUrl:ze,segmentTemplateUrl:pi,initUrl:"",totalSegmentsDurationMs:Oa,segments:Ba,nextSegmentBeyondManifest:Ji,timescale:ot};oe={id:X,kind:"text",segmentReference:ut,profiles:[],duration:c,bitrate:nt,mime:"",codecs:"",width:0,height:0,isAuto:Ke}}else oe={id:X,isAuto:Ke,kind:"text",url:ze}}else{let X=w.getAttribute("contentType")??V?.split("/")[0]??q,Ke=I.getAttribute("profiles")?.split(",")??[],Oe=parseInt(w.getAttribute("width")??"",10),_e=parseInt(w.getAttribute("height")??"",10),nt=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,St=w.getAttribute("frameRate")??"",ot=w.getAttribute("quality")??void 0,Sn=St?Hv(St):void 0,pi=w.getAttribute("id")??"id"+(k++).toString(10),Ba=X==="video"?`${_e}p`:X==="audio"?`${nt}Kbps`:te,Oa=`${pi}@${Ba}`,_a=[...x,...v,...Ke],hi,Xi=w.querySelector("SegmentBase"),ue=w.querySelector("SegmentTemplate")??Re;if(Xi){let ut=w.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,Ft]=ut.split("-").map(Tt=>parseInt(Tt,10)),Me={from:Ne,to:Ft},yt=w.querySelector("SegmentBase")?.getAttribute("indexRange"),[qt,mi]=yt?yt.split("-").map(Tt=>parseInt(Tt,10)):[],Xe=yt?{from:qt,to:mi}:void 0;hi={type:"byteRange",url:ze,initRange:Me,indexRange:Xe}}else if(ue){let ut={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},Ne=parseInt(ue.getAttribute("timescale")??"",10),Ft=ue.getAttribute("initialization")??"",Me=ue.getAttribute("media"),yt=parseInt(ue.getAttribute("startNumber")??"",10)??1,qt=bt(Ft,ut);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let mi=ue.querySelectorAll("SegmentTimeline S")??[],Xe=[],Tt=0,fi="",Zi=0;if(mi.length){let Na=yt,Fe=0;for(let bi of mi){let Je=parseInt(bi.getAttribute("d")??"",10),Ut=parseInt(bi.getAttribute("r")??"",10)||0,Fa=parseInt(bi.getAttribute("t")??"",10);Fe=Number.isFinite(Fa)?Fa:Fe;let yn=Je/Ne*1e3,yy=Fe/Ne*1e3;for(let qa=0;qa<Ut+1;qa++){let Ty=bt(Me,{...ut,segmentNumber:Na.toString(10),segmentTime:(Fe+qa*Je).toString(10)}),Fl=(yy??0)+qa*yn,Iy=Fl+yn;Na++,Xe.push({time:{from:Fl,to:Iy},url:Ty})}Fe+=(Ut+1)*Je,Tt+=(Ut+1)*yn}Zi=Fe/Ne*1e3,fi=bt(Me,{...ut,segmentNumber:Na.toString(10),segmentTime:Fe.toString(10)})}else if(U$(c)){let Fe=parseInt(ue.getAttribute("duration")??"",10)/Ne*1e3,bi=Math.ceil(c/Fe),Je=0;for(let Ut=1;Ut<bi;Ut++){let Fa=bt(Me,{...ut,segmentNumber:Ut.toString(10),segmentTime:Je.toString(10)});Xe.push({time:{from:Je,to:Je+Fe},url:Fa}),Je+=Fe}Zi=Je,fi=bt(Me,{...ut,segmentNumber:bi.toString(10),segmentTime:Je.toString(10)})}let Sy={time:{from:Zi,to:1/0},url:fi};hi={type:"template",baseUrl:ze,segmentTemplateUrl:Me,initUrl:qt,totalSegmentsDurationMs:Tt,segments:Xe,nextSegmentBeyondManifest:Sy,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!X||!V)continue;let Ji={video:"video",audio:"audio",text:"text"}[X];if(!Ji)continue;C||=Ji,oe={id:Oa,kind:Ji,segmentReference:hi,profiles:_a,duration:c,bitrate:nt,mime:V,codecs:te,width:Oe,height:_e,fps:Sn,quality:ot}}_.language||=H,_.label||=$e,_.mime||=V,_.codecs||=te,_.hdr||=C==="video"&&tl(te),_.representations.push(oe)}if(C){let w=a[C].find(H=>H.id===_.id);if(w&&_.representations.every(H=>ce(H.segmentReference)))for(let H of w.representations){let di=_.representations.find(V=>V.id===H.id)?.segmentReference,ze=H.segmentReference;ze.segments.push(...di.segments),ze.nextSegmentBeyondManifest=di.nextSegmentBeyondManifest}else a[C].push(_)}}return{dynamic:u,liveAvailabilityStartTime:d,duration:c,streams:a,baseUrls:n}};var iS=M(je(),1);import{isNonNullable as tS}from"@vkontakte/videoplayer-shared";var de=(r,e)=>tS(r)&&tS(e)&&r.readyState==="open"&&(0,iS.default)([...r.activeSourceBuffers],e);var ma=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ri(0);this.currentLowLatencySegmentLength$=new ri(0);this.currentSegmentLength$=new ri(0);this.onLastSegment$=new ri(!1);this.fullyBuffered$=new ri(!1);this.playingRepresentation$=new ri(void 0);this.playingRepresentationInit$=new ri(void 0);this.error$=new Q$;this.gaps=[];this.subscription=new G$;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new se;this.switchAbortController=new se;this.destroyAbortController=new se;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=Vt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Te(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Jg(this.sourceBuffer),this.subscription.add(cl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:gt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(cl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:gt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!de(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Wu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=rt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Te(i,"No init buffer for starting representation"),Te(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Vt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Te(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Te(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Qi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Vt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Te(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Te(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Qi(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=Vt(this.destroyAbortController.signal,async function*(e){let t=(0,Gs.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let d=this.representations.get(u);if(!d||!ce(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);Te(a);let s=this.segments.get(i);Te(s,"No segments for starting representation");let n=this.initData.get(i);if(Te(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new se,Vt(this.switchAbortController.signal,async function*(i,a=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Te(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ne(o)||ne(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Te(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Qi(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ne(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new se,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ne(e)||ne(this.downloadingRepresentationId)||ne(this.playingRepresentationId)||ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer)||Qi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Te(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let a=i.find(l=>e>=l.time.from&&e<l.time.to);Qi(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=rt(this.sourceBuffer.buffered,e),c=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=c)}if(isFinite(this.bufferLimit)&&Wu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=rt(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if((0,Qs.default)(o,a))l="high";else{let d=(0,Gi.default)(o,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&rt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Gi.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+a}),i=s.time.to;Qi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=(0,Gs.default)(e?.streams[this.kind],a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,Gs.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!ce(i.segmentReference))return;let a=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,Gi.default)(n,-1)?.time.to??0,u=a?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=a.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Te(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let a=i.segmentReference;if(!ce(a))return;let s=this.segments.get(i.id)??[],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,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*a.timescale/1e3).toString(10),l=bt(a.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&Fr&&Fr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Fr&&Fr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let a=e.findIndex(({status:c,time:{from:p,to:m}},f)=>{let b=p<=i&&m>=i,g=p>i||b||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&p<=i+S||m<=i+S;return(c==="none"||c==="partially_ejected"&&g&&k&&this.sourceBuffer&&de(this.mediaSource,this.sourceBuffer)&&!(Dt(this.sourceBuffer.buffered,p)&&Dt(this.sourceBuffer.buffered,m)))&&g&&k});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=a;c<s.length&&(n<=l||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){ce(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Vt(o,async function*(){let d=dl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=js(),!d)return;let c=new DataView(d),p=pa(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(c,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:m,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);m&&f&&this.currentLiveSegmentServerLatency$.next(f-m),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ha(d)||(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())ce(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Vt(n,async function*(){let u=dl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),cl(window,"online").pipe(j$()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=js(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ha(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ce(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,Gi.default)(e,0).byte.from,to:(0,Gi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=js(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ce(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let a=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=js();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:gt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Qs.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:a,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){a();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=pa(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,m=d<a,f=c<=a;if(!m)continue;let b=pa(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer))){!this.isLive&&H$.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Dt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Dt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:gt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",nl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let a of this.segments.get(i.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ju(()=>(0,rS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Vt(this.destroyAbortController.signal,async function*(){let o=dl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,pa(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&ce(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:gt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ne(e))return!1;let a=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],m=l[l.length-1];m.to>=c?m.to=Math.max(m.to,p):l.push(u[d])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=nl(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let m of p)(0,Qs.default)(["none","partially_ejected"],m.status)&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(a.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ne(e)?0:rt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let a={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){a=void 0;break}o>i.time.from&&o<i.time.to&&(a.from=o),n<i.time.to&&n>i.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=ju(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:gt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer)||ne(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let a=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:s})}let t=100;for(let i of this.segments.values())for(let a of i){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:gt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var fa=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var aS=r=>{let e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}};import{abortable as ba,assertNever as nS,fromEvent as oS,merge as W$,now as ga,Subscription as Y$,ValueSubject as pl,flattenObject as Wi}from"@vkontakte/videoplayer-shared";var sS=r=>{let e=new URL(r);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Ws=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new pl(void 0);this.lastConnectionReused$=new pl(void 0);this.lastRequestFirstBytes$=new pl(void 0);this.abortAllController=new se;this.subscription=new Y$;this.fetchManifest=ba(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=fa(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=sS(i));let a=yield Ge(i,{signal:this.abortAllController.signal}).catch(va);return a?(t.log("success",Wi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Wi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ba(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(l,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),l=v.toString();break}default:nS(t)}this.requestQuic&&(l=fa(l));let p=this.abortAllController.signal,m;if(n){let v=new se;if(m=W$(oS(this.abortAllController.signal,"abort"),oS(n,"abort")).subscribe(()=>{try{v.abort()}catch(P){va(P)}}),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(P){va(P)}p=v.signal}let f=ga();c.log("startRequest",Wi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let b=yield Ge(l,{priority:s,headers:d,signal:p}).catch(va),g=ga();if(!b)return c.error("error",{message:"No response in request"}),c.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){m?.unsubscribe();let v=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:v}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){m?.unsubscribe();let v=ga(),P={requestStartedAt:f,requestEndedAt:v,duration:v-f};return c.log("endRequest",Wi(P)),c.end(),b.arrayBuffer()}let[S,k]=b.body.tee(),x=S.getReader();o&&this.throughputEstimator?.trackStream(k,u);let R=0,y=new Uint8Array(0),I=!1,L=v=>{m?.unsubscribe(),I=!0,va(v)},G=ba(p,async function*({done:v,value:P}){if(R===0&&this.lastRequestFirstBytes$.next(ga()-f),p.aborted){m?.unsubscribe();return}if(!v&&P){let U=new Uint8Array(y.length+P.length);U.set(y),U.set(P,y.length),y=U,R+=P.byteLength,a?.(new DataView(y.buffer),R),yield x?.read().then(G,L)}}.bind(this));yield x?.read().then(G,L),m?.unsubscribe();let F=ga(),q={failed:I,requestStartedAt:f,requestEndedAt:F,duration:F-f};return I?(c.error("endRequest",Wi(q)),c.end(),null):(c.log("endRequest",Wi(q)),c.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=ba(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let m=t.parseInit(p),f=e.indexRange??t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,m,f);return{init:m,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=ba(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=aS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:nS(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},va=r=>{if(!ha(r))throw r};var ai=(r,e,t)=>t*e+(1-t)*r,hl=(r,e)=>r.reduce((t,i)=>t+i,0)/e,uS=(r,e,t,i)=>{let a=0,s=t,n=hl(r,e),o=e<i?e:i;for(let u=0;u<o;u++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};import{isNullable as z$,ValueSubject as lS}from"@vkontakte/videoplayer-shared";var Bt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new lS(e.initial),this.debounced$=new lS(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new le(`raw_${t}`),this.smoothedSeries$=new le(`smoothed_${t}`),this.reportedSeries$=new le(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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)&&(z$(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 Ys=class extends Bt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ai(this.slow,e,this.params.emaAlphaSlow),this.fast=ai(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var zs=class extends Bt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=hl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ai(this.emaSmoothed,e,this.params.emaAlpha);let i=uS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ks=class extends Bt{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?ai(this.smoothed,t,this.params.emaAlpha):t}};var si=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ys({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new zs({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Ks({initial:e,label:"liveEdgeDelay",...t})}};var ml=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};import{isNullable as K$,ValueSubject as X$}from"@vkontakte/videoplayer-shared";var Sa=class r{constructor(e,t){this.currentRepresentation$=new X$(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!K$(e))for(let t of this.representations)for(let i of t){let a=i.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=r.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>r.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&ce(t.segmentReference))}};var sM=["timeupdate","progress","play","seeked","stalled","waiting"],nM=["timeupdate","progress","loadeddata","playing","seeked"];var Xs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new hS;this.representationSubscription=new hS;this.state$=new $("none");this.currentVideoRepresentation$=new z(void 0);this.currentVideoRepresentationInit$=new z(void 0);this.currentAudioRepresentation$=new z(void 0);this.currentVideoSegmentLength$=new z(0);this.currentAudioSegmentLength$=new z(0);this.error$=new pS;this.lastConnectionType$=new z(void 0);this.lastConnectionReused$=new z(void 0);this.lastRequestFirstBytes$=new z(void 0);this.currentLiveTextRepresentation$=new z(null);this.isLive$=new z(!1);this.isActiveLive$=new z(!1);this.isLowLatency$=new z(!1);this.liveDuration$=new z(0);this.liveAvailabilityStartTime$=new z(void 0);this.bufferLength$=new z(0);this.liveLatency$=new z(void 0);this.liveLoadBufferLength$=new z(0);this.livePositionFromPlayer$=new z(0);this.currentStallDuration$=new z(0);this.videoLastDataObtainedTimestamp$=new z(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new pS;this.gapWatchdogActive=!1;this.destroyController=new se;this.initManifest=fl(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:at.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=fl(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:at.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=eS(e??"",this.manifestUrlString)}catch(n){let o=Gg(e)??{id:"ManifestParsing",category:at.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&mt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let n=(t.duration??0)/1e3;this.liveDuration$.next(-1*n)}let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:p})=>i(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=xg(l);if(d&&(a[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),m=a.video.some(f=>!f.hdr);eM.isHDR&&c&&p?a.video=a.video.filter(f=>f.hdr):m&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",Ta(s)),s}.bind(this));this.initRepresentations=fl(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",Ta({initialVideo:e,initialAudio:t,sourceHls:i})),ni(this.manifest),ni(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=c=>{this.representationSubscription.add(ui(c,"error").pipe(ya(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:at.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?gg():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&_s())if(i){let c=document.createElement("source");a(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],dS(t)){let c=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new ma("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}Sa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Sa(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(gl(1e3).subscribe(c=>{if(this.element?.paused){let p=xs(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,p+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(li(...nM.map(c=>ui(this.element,c))).pipe(Yi(c=>this.element?rt(this.element.buffered,this.element.currentTime*1e3):0),bl(),rM(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(li(ui(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(oi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Yi(({isActiveLive:p,isLowLatency:m})=>p&&m),bl()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||ml(this.element,1)})),this.representationSubscription.add(oi({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ya(({bufferLength:p,isActiveLive:m,isLowLatency:f})=>m&&f&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(oi({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$,currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(ya(({isActiveLive:p,isLowLatency:m,currentLowLatencySegmentLength:f})=>p&&m&&!!f)).subscribe(({currentLowLatencySegmentLength:p})=>{let m=this.liveDuration$.getValue()-p/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(oi({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(ya(({isLive:p})=>p),Yi(p=>({...p})),bl((p,m)=>m.bufferLength<p.bufferLength),Yi(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=xs(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(oi({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:p,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,k=p-b;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(k)>g&&(x=1+Math.sign(k)*S),ml(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(oi({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(aM(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(ni(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=xs(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),k=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,R=isFinite(p)?p:m,y=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),I=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLive$.next(I);let L="none";if(y?L="active_low_latency":this.isLowLatency$.getValue()&&I?(this.bufferManagers.forEach(G=>G.proceedLowLatencyLive()),L="active_low_latency"):b!==0&&R<S?L="live_forward_buffering":R<S+x&&(L="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),L==="live_forward_buffering"||L==="live_with_target_offset"){let G=c-(S+k),F=this.normolizeLiveOffset(Math.trunc(b+G/f)),q=Math.abs(F-b),v;!p||q<=this.tuning.dashCmafLive.offsetCalculationError?v=b:F>0&&q>this.tuning.dashCmafLive.offsetCalculationError?v=F:v=0,this.manifestUrlString=ae(this.manifestUrlString,v,2)}L!=="none"&&L!=="active_low_latency"&&(c=0,await this.updateLive())},p=>{this.error$.next({id:"updateLive",category:at.VIDEO_PIPELINE,thrown:p,message:"Failed to update live with subscription"})}))}let l=li(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(Yi(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),d=li(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(Yi(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));if(this.representationSubscription.add(li(this.forceEnded$,oi({allBuffersFull:l,someBufferEnded:d}).pipe(ya(({allBuffersFull:c,someBufferEnded:p})=>c&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream(),this.bufferManagers.forEach(c=>c.warmUpMediaSource())}catch(c){this.error$.next({id:"EndOfStream",category:at.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(li(...this.bufferManagers.map(c=>c.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(c=>this.source?.addEventListener("sourceopen",c))),!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,vl.default)((0,vl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),ce(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&dS(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=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=gl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:at.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ws({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=si.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){ni(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLive$.next(t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){ni(this.element),this.state$.setState("running"),this.subscription.add(li(...sM.map(e=>ui(this.element,e)),ui(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:at.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ui(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ui(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Dt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},a=iM(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,d=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset).catch(p=>{this.error$.next({id:"stallIntervalCallback",category:at.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:p})}),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",Ta(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=gl(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:at.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let a={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?a?.switchToWithPreviousAbort(t,i):a?.switchTo(t,i):a?.switchToOld(t,i)}async seek(e,t){ni(this.element),ni(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),Dt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ta({requestedPosition:e,forcePrecise:t,position:i}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=tM(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=a&&u.to+n>a&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ta(i)))}}};var Js=class{constructor(e,t){this.fov=e,this.orientation=t}};var Zs=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var mS=`attribute vec2 a_vertex;
|
|
71
71
|
attribute vec2 a_texel;
|
|
72
72
|
|
|
73
73
|
varying vec2 v_texel;
|
|
@@ -121,6 +121,6 @@ void main(void) {
|
|
|
121
121
|
// sample using new coordinates
|
|
122
122
|
gl_FragColor = texture2D(u_texture, tc);
|
|
123
123
|
}
|
|
124
|
-
`;var en=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Js(this.params.fov,this.params.orientation),this.cameraRotationManager=new Zs(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(mS,this.gl.VERTEX_SHADER),i=this.createShader(fS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-i,n=t-a,o=e+i,u=t-a,l=e+i,d=t+a,c=e-i,p=t+a;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as lM,now as bS,Subscription as cM,filter as dM,combine as gS,ValueSubject as Sl,isNonNullable as pM}from"@vkontakte/videoplayer-shared";var yl=class{constructor(){this.isSeeked$=new Sl(!1);this.isBuffering$=new Sl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new cM;this.severeStallOccurred$=new Sl(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(gS({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(dM(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(gS({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(lM(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:a,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=bS(),d=a&&this.currentStallsCount>=a,c=i&&l-this.lastUniqueVideoTrackSelectedTimestamp>=i+n&&l-u>=i+n&&t>=i;(d||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,pM(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=bS(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},vS=yl;import{combine as hM,map as mM,observeElementSize as fM,Subscription as bM,ValueSubject as Tl,noop as gM}from"@vkontakte/videoplayer-shared";var tn=class{constructor(){this.subscription=new bM;this.pipSize$=new Tl(void 0);this.videoSize$=new Tl(void 0);this.elementSize$=new Tl(void 0);this.pictureInPictureWindowRemoveEventListener=gM}connect({observableVideo:e,video:t}){let i=a=>{let s=a.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(fM(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:a})=>{this.pipSize$.next({width:a.width,height:a.height}),a.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{a.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(hM({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(mM(({videoSize:a,inPip:s,pipSize:n})=>s?n:a)).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 ci=class{constructor(e){this.subscription=new xM;this.videoState=new $("stopped");this.droppedFramesManager=new Cs;this.stallsManager=new vS;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 Ar;this.audioTrackSwitchHistory=new Ar;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(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"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&T(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&T(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()):i?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return yM(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new en(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=me(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(Z(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 Xs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=ge(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:SS.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(yS(l=>!!l.length),IS()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Il(l=>l.to.state!=="none"),Ea());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ea()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(yS(TS),IS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Il(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(tt(this.video,t.isLooped,a)),this.subscription.add(be(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,a)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(TM(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let m of d.audio){p.push(al(m));let f=[];for(let b of m.representations){let g=Gv(b);f.push(g),this.audioTracksMap.set(g,{stream:m,representation:b})}this.audioStreamsMap.set(m,f)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of d.video){c.push(sl(p));let m=[];for(let f of p.representations){let b=Qv({...f,streamId:p.id});b&&(m.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,m)}this.params.output.availableVideoStreams$.next(c);for(let p of d.text)for(let m of p.representations){let f=Wv(p,m);this.textTracksMap.set(f,{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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a)),this.subscription.add(rn(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,EM(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,ES.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[p,m]=c,f=[...this.videoTracksMap.keys()].find(g=>this.videoTracksMap.get(g)?.representation.id===p.id);TS(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ea()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{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(c),e.currentVideoStream$.next(sl(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ea()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{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(al(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Il(({to:l})=>l==="ready"),Ea());this.subscription.add(rn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,El(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(rn(o,this.player.state$.stateChangeEnded$,El(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=rn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,El(["init"])).pipe(IM(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:L})=>L===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:L})=>L===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=rt(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(c/Math.min(p,m||1/0),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:L})=>L===b?.id)??this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!i){let L=Rs(n,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,L?.bitrate??-1/0)}if(o){let L=Rs(o,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,L?.bitrate??-1/0)}}let w=Mt(d,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),x=i?w??n:n??w,R=g&&Mb(x,d,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),y=this.videoTracksMap.get(x)?.representation,I=R&&this.audioTracksMap.get(R)?.representation;if(y&&I)return[y,I];if(y&&!I&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:SS.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),fe(this.video),this.tracer.end()}};var xa=class extends ci{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as xS,interval as PM,map as PS}from"@vkontakte/videoplayer-shared";var Pa=class extends ci{constructor(e){super(e),this.liveOffset=new pt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(t.timeUpdate$,e.liveBufferTime$),a(this.player.liveDuration$,e.duration$),a(this.player.liveLatency$,e.liveLatency$),this.subscription.add(i.isLowLatency.stateChangeEnded$.pipe(PS(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(xS({interval:PM(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(s-1);n<=0&&e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(xS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(PS(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Yv(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var kS=M(Es(),1);import{assertNever as wa,assertNonNullable as wS,debounce as wM,ErrorCategory as an,filter as kM,isNonNullable as AM,isNullable as LM,map as sn,merge as RM,Observable as $M,observableFrom as MM,Subscription as DM,videoSizeToQuality as CM}from"@vkontakte/videoplayer-shared";var Ye={};var zi=(r,e)=>new $M(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),ka=class{constructor(e){this.subscription=new DM;this.videoState=new $("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:wa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:wa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:wa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:wa(e)}break;default:wa(t)}};this.textTracksManager=new Ce(e.source.url),this.video=me(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(Z(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),fe(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:an.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,kS.default)(import("hls.js").then(a=>{e||(Ye.Hls=a.default,Ye.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){wS(Ye.Hls,"hls.js not loaded"),this.hls=new Ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){wS(Ye.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:an.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=ge(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,i));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(tt(this.video,e.isLooped,i)),this.subscription.add(be(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(De(this.video,e.playbackRate,a.playbackRateState$,i)),s(Be(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(sn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(zi(this.hls,Ye.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:an.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(e.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(e.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(zi(this.hls,Ye.Events.MANIFEST_PARSED).pipe(sn(({levels:l})=>l.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:m,height:f}=c,b=Lt(c.attrs.QUALITY??"")??CM({width:m,height:f});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:m,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:c}),d.push(S),d},[]))),t.availableVideoTracks$),s(zi(this.hls,Ye.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,m=c.attrs.URI||"",f=c.lang;d.push({id:p,url:m,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(zi(this.hls,Ye.Events.LEVEL_LOADING).pipe(sn(({url:l})=>Z(l))),t.hostname$),s(zi(this.hls,Ye.Events.FRAG_CHANGED),l=>{let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??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:i}));let n=l=>Array.from(this.trackLevels.values()).find(({level:d})=>d===l)?.track,o=zi(this.hls,Ye.Events.LEVEL_SWITCHED).pipe(sn(({level:l})=>n(this.hls.levels[l])));o.pipe(kM(AM)).subscribe(t.currentVideoTrack$,i),this.subscription.add(wt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(LM(l))return;let d=this.trackLevels.get(l.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,m=this.hls.levels[p];!m||d.bitrate>m.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=RM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,MM(["init"])).pipe(wM(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:an.DOM,thrown:t}))||(this.videoState.setState("paused"),T(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"),T(this.params.desiredState.playbackState,"stopped",!0)}};var AS="X-Playback-Duration",xl=async r=>{let e=await Ge(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(AS)?parseInt(e.headers.get(AS),10):void 0};import{assertNever as QM,combine as GM,debounce as WM,ErrorCategory as un,filter as YM,filterChanged as zM,isNonNullable as $S,isNullable as ln,map as MS,merge as KM,observableFrom as XM,Subscription as JM,ValueSubject as kl,VideoQuality as ZM}from"@vkontakte/videoplayer-shared";var wl=M(Lo(),1);import{videoSizeToQuality as VM,getExponentialDelay as BM}from"@vkontakte/videoplayer-shared";var OM=r=>{let e=null;if(r.QUALITY&&(e=Lt(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=VM({width:t,height:i})}return e??null},_M=(r,e)=>{let t=r.split(`
|
|
125
|
-
`),i=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,
|
|
126
|
-
`),s=0;for(let n=0;n<a.length;++n){let o=a[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=a[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(FM(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:a}=t[t.length-1].time;if(e<i||e>a)return;a-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new se;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:jM.WTF,thrown:t,message:e})}};var Aa=class{constructor(e){this.subscription=new JM;this.videoState=new $("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new kl([]);this.liveOffset=new pt;this.manifestStartTime$=new kl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),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(a?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?T(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return QM(t)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ZM.INVARIANT,url:this.params.source.url};let t=(i,a)=>nn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new on(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ce(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:a})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:un.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:un.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new kl(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ge(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(be(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(zM(),MS(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&$S(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(m=>m.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(GM({startTime:this.manifestStartTime$.pipe(YM($S)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(MS(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=KM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XM(["init"])).pipe(WM(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){let e=this.selectManifest();if(ln(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&a.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(a.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),xl(n).then(o=>{if(!ln(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(ln(u)||!isFinite(u))&&Ge(n).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,n).toString();xl(c).then(p=>{ln(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:un.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ae(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as eD,debounce as tD,ErrorCategory as Al,fromEvent as Ll,isNonNullable as iD,isNullable as rD,map as DS,merge as CS,observableFrom as VS,Subscription as aD,ValueSubject as sD,VideoQuality as nD,clientChecker as oD}from"@vkontakte/videoplayer-shared";var La=class{constructor(e){this.subscription=new aD;this.videoState=new $("stopped");this.manifests$=new sD([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?T(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return eD(t)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:nD.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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),nn(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Al.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!a||!a.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Al.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ge(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(DS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(be(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&iD(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===m);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Z(f.url)))}let c=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(DS(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!oD.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(CS(Ll(o,"addtrack"),Ll(o,"removetrack"),Ll(o,"change"),VS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=CS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,VS(["init"])).pipe(tD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){let e=this.selectManifest();if(rD(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Al.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var _S=M(wi(),1),Rl=M(Oi(),1),NS=M(Rt(),1);import{assertNever as uD,assertNonNullable as BS,debounce as lD,ErrorCategory as OS,isHigherOrEqual as cD,isLowerOrEqual as dD,isNonNullable as pD,merge as hD,observableFrom as mD,Subscription as fD,map as bD}from"@vkontakte/videoplayer-shared";var Ra=class{constructor(e){this.subscription=new fD;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Ce;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return uD(e)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),(0,_S.default)(this.params.source).reverse().forEach(([t,i],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Rl.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:OS.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ge(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(bD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(be(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&pD(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=hD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,mD(["init"])).pipe(lD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),fe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;BS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];BS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=fa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:OS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let d=Mt(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(d)},a=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Rl.default)(this.trackUrls).map(l=>l.track);if(!a||!s||kr({limits:e,lowestAvailableQuality:(0,NS.default)(n,-1)?.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?dD(a,e.max):!0,u=e.min?cD(a,e.min):!0;o&&u||i(e)}};import{assertNever as qS,debounce as yD,merge as US,observableFrom as TD,Subscription as ID,map as HS,ValueSubject as ED,ErrorCategory as Ml,VideoQuality as xD}from"@vkontakte/videoplayer-shared";import{ErrorCategory as gD}from"@vkontakte/videoplayer-shared";var FS=["stun:videostun.mycdn.me:80"],vD=1e3,SD=3,$l=()=>null,cn=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=$l;this.externalStopCallback=$l;this.externalErrorCallback=$l;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:FS}]};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:gD.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{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),vD)}normalizeOptions(e={}){let t={stunServerList:FS,maxRetryNumber:SD,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 ED(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(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"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return qS(e)}};this.subscription=new ID,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=me(e.container,e.tuning),this.liveStreamClient=new cn(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),fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ml.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};US(this.videoState.stateChangeStarted$.pipe(HS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(HS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ge(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Be(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(be(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return qS(n.to)}},i)).add(US(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,TD(["init"])).pipe(yD(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Z(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:xD.INVARIANT}),this.video.srcObject=e,T(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:Ml.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ml.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ma=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 Da,assertNonNullable as Ot,ErrorCategory as dn,filter as zS,isNonNullable as KS,isNullable as MD,map as DD,merge as CD,once as VD,Subject as Ie,Subscription as XS,ValueSubject as D,flattenObject as JS}from"@vkontakte/videoplayer-shared";import{Observable as PD,map as jS,Subscription as wD,Subject as kD}from"@vkontakte/videoplayer-shared";var QS=r=>new PD(e=>{let t=new wD,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(jS(({from:l,to:d})=>`${l}-${d}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe(jS(({type:l})=>l!==void 0)),n=new kD,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),r.maxTransitionInterval)})),t.add(a.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),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as AD,Subscription as LD,combine as RD,filter as WS,once as YS}from"@vkontakte/videoplayer-shared";function GS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as $D}from"@vkontakte/videoplayer-shared";var Ki=class r{constructor(e,t,i,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.destroyController=new se;this.subscriptions=new LD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(WS(s=>!!s.type),YS()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$D.isSafari&&e!=="MPEG"||this.subscriptions.add(RD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(WS(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),YS()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=GS();this.audioContext=i;let a=i.createGain();if(this.gainNode=a,a.gain.value=t,a.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(a),!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){this.volumeMultiplierError$.next({id:r.errorId,category:AD.VIDEO_PIPELINE,message:e?.message??`${r.errorId} exception`,thrown:e})}};var BD={chunkDuration:5e3,maxParallelRequests:5},Ca=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new Ie;this.noAvailableProvidersError$=new Ie;this.volumeMultiplierError$=new Ie;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 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 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(""),getCurrentTime$:new D(null)};this.subscription=new XS;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=Tg([...Eg(this.params.tuning),...Ig(this.params.tuning)],this.params.tuning).filter(l=>KS(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]:a.length?s=[...t.filter(l=>!(0,Dl.default)(a,l)),...t.filter(l=>(0,Dl.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",JS(s)),this.screenFormatsIterator=new Ma(s);let n=[...Nu(!0),...Nu(!1)];this.chromecastFormatsIterator=new Ma(n.filter(l=>KS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ki.isSupported()&&(this.volumeMultiplierManager=new Ki(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(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(MD(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:dn.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Da(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:a}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:a,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 Ot(o),new xa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Pa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ot(o),Ui||!this.params.tuning.useHlsJs?new La({...n,source:o}):new ka({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Aa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Ra({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new zb({...n,source:o,config:{...BD,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new $a({container:i,source:o,desiredState:a,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 Da(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ot(o),new Er({connection:o,meta:s,container:i,source:t,format:e,desiredState:a,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 Da(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Da(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 Da(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,ey.default)((0,ZS.default)(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new XS,t=!1,i=0;return e.add(CD(this.providerOutput.error$.pipe(zS(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),QS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(DD(a=>({id:`ProviderHangup:${a}`,category:dn.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(zS(({to:s})=>s==="playing"),VD()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===dn.NETWORK,u=a.category===dn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",JS(n))})),e}};import{fromEvent as pn,once as OD,combine as _D,Subscription as ty,ValueSubject as Cl,map as ND,filter as FD,isNonNullable as hn,now as Ae,safeStorage as Vl}from"@vkontakte/videoplayer-shared";var qD=5e3,iy="one_video_throughput",ry="one_video_rtt",Va=window.navigator.connection,ay=()=>{let r=Va?.downlink;if(hn(r)&&r!==10)return r*1e3},sy=()=>{let r=Va?.rtt;if(hn(r)&&r!==3e3)return r},ny=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},Bl=class r{constructor(e){this.subscription=new ty;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load(iy)||(e.useBrowserEstimation?ay():void 0)||qD,i=r.load(ry)??(e.useBrowserEstimation?sy():void 0)??0;if(this.throughput$=new Cl(t),this.rtt$=new Cl(i),this.rttAdjustedThroughput$=new Cl(ny(t,i,e.rttPenaltyRequestSize)),this.throughput=si.getSmoothedValue(t,-1,e),this.rtt=si.getSmoothedValue(i,1,e),e.useBrowserEstimation){let a=()=>{let n=ay();n&&this.throughput.next(n);let o=sy();hn(o)&&this.rtt.next(o)};Va&&"onchange"in Va&&this.subscription.add(pn(Va,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Vl.set(iy,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Vl.set(ry,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(_D({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(ND(({throughput:a,rtt:s})=>ny(a,s,e.rttPenaltyRequestSize)),FD(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Ae(),a=new ty;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(pn(e,"progress").pipe(OD()).subscribe(s=>{t=s.loaded,i=Ae()}));break;case 1:case 0:a.add(pn(e,"loadstart").subscribe(()=>{t=0,i=Ae()}));break}a.add(pn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ae(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,s=Ae(),n=0,o=Ae(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(a,Ae()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=Ae();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,s=Ae()}else n+=c.byteLength;o=Ae()}else a+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ae()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ae()-o,this.concurrentDownloads.size),n=0,o=Ae());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,a=!1){if(r.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Vl.get(e);if(hn(t))return parseInt(t,10)??void 0}},oy=Bl;import{fillWithDefault as UD,VideoQuality as mn}from"@vkontakte/videoplayer-shared";var uy={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit: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:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1},ly=r=>({...UD(r,uy),configName:[...r.configName??[],...uy.configName]});import{assertNonNullable as fn,combine as vt,ErrorCategory as bn,filter as pe,filterChanged as N,fromEvent as _l,isNonNullable as zD,isNullable as KD,Logger as XD,map as O,mapTo as hy,merge as _t,now as gn,once as st,Subject as j,Subscription as my,tap as fy,ValueSubject as E,isHigher as JD,isInvariantQuality as by,flattenObject as Nt,throttle as Nl,getTraceSubscriptionMethod as gy,Tracer as ZD,InternalsExposure as e0}from"@vkontakte/videoplayer-shared";import{merge as HD,map as jD,filter as cy,isNonNullable as QD}from"@vkontakte/videoplayer-shared";var Ol=({seekState:r,position$:e})=>HD(r.stateChangeEnded$.pipe(jD(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),cy(QD)),e.pipe(cy(()=>r.getState().state==="none")));import{assertNonNullable as GD}from"@vkontakte/videoplayer-shared";var dy=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return GD(e,`Wrong container or containerId {${r.container}}`),e};import{filter as WD,once as YD}from"@vkontakte/videoplayer-shared";var py=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(WD(a=>a.length>0),YD()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};var vn=class{constructor(e={configName:[]},t=ZD.createRootTracer(!1)){this.subscription=new my;this.logger=new XD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!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 E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),predefinedQualityLimitType$:new E("unknown"),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),liveLatency$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(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 E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:Sb,getCurrentTime$:new E(null)};if(this.initLogs(),this.tuning=ly(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new za({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new oy(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new e0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,a,s)=>{let n=Reflect.get(i,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(m,f)=>{let b=typeof f;return(0,vy.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),d=`Player.${String(a)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:bn.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",Nt(i)),this.domContainer=dy(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ca({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.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&&!Dr()?(this.tracer.log("request play from hidden tab"),_l(document,"visibilitychange").pipe(st()).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 i=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=i&&!a&&(s=i-.2),this.tracer.log("seekTime",{duration:i,isLive:a,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){fn(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(pe(i=>i.length>0),st()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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:i}=this.tuning.autoTrackSelection,a;switch(e){case"high_quality":a={min:t,max:void 0};break;case"traffic_saving":a={max:i,min:void 0};break;default:a={max:void 0,min:void 0}}return this.setAutoQualityLimits(a),this}setPlaybackRate(e){fn(this.providerContainer);let t=this.providerContainer?.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){return py(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.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(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.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 i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let a=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.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(KD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return zD(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||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(O(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(xu({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pe(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=gn(),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:bn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(st()).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(O(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(O(n=>n.destination),N()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(vt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(O(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>by(u)?1:by(l)?-1:JD(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?.quality),this.info.videoBitrate$.next(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??{})})).add(e.providerOutput.currentBuffer$.pipe(O(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(vt({hasLiveOffsetByPaused:_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(n=>n.to),N(),O(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(vt({atLiveEdge:vt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ol({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(O(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),N(),fy(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(O(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(vt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(O(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),N(),fy(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(O(n=>n.muted),N()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(O(n=>n.volume),N()).subscribe(this.info.volume$)).add(Ol({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(_t(e.providerOutput.endedEvent$.pipe(hy(!0)),e.providerOutput.seekedEvent$.pipe(hy(!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(O(n=>({id:n?`No${n}`:"NoProviders",category:bn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(st(),O(n=>n??gn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),O(()=>gn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),O(()=>gn()-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 E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(pe(({to:n})=>n==="playing"),st()).subscribe(()=>i.next(!1)));let a=0,s=_t(e.providerOutput.isBuffering$,t,i).pipe(O(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),N());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),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?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height: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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(O(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new my;this.subscription.add(t),this.subscription.add(e.current$.pipe(N((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pe(i=>i.length>0),st()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),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(_t(this.desiredState.videoTrack.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(O(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(){let e=this.providerContainer?.providerOutput;fn(this.providerContainer),fn(e),vb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>gb(t)),this.providerContainer.current$.subscribe(({type:t})=>wr("provider",t)),e.duration$.subscribe(t=>wr("duration",t)),e.availableVideoTracks$.pipe(pe(t=>!!t.length),st()).subscribe(t=>wr("tracks",t)),this.events.fatalError$.subscribe(new le("fatalError")),this.events.managedError$.subscribe(new le("managedError")),e.position$.subscribe(new le("position")),e.currentVideoTrack$.pipe(O(t=>t?.quality)).subscribe(new le("quality")),this.info.currentBuffer$.subscribe(new le("buffer")),e.isBuffering$.subscribe(new le("isBuffering"))].forEach(t=>this.subscription.add(t)),wr("codecs",yg())}initTracerSubscription(){let e=gy(this.tracer.log.bind(this.tracer)),t=gy(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(vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(pe(({currentQuality:i,videoBitrate:a})=>!!i&&!!a),N((i,a)=>i.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(pe(i=>i>0),N()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(pe(i=>i>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(vt({currentBuffer:this.info.currentBuffer$.pipe(pe(i=>i.end>0),N((i,a)=>i.end===a.end&&i.start===a.start)),position:this.info.position$.pipe(N())}).pipe(Nl(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(vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(pe(({liveTime:i,liveBufferTime:a})=>!!i&&!!a),Nl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(N(),pe(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(N(),pe(i=>i===!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(),pe(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(pe(({throughputEstimation:i,rtt:a})=>!!i&&!!a),Nl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(N(),pe(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:bn.DOM,message:String(a)})})};this.subscription.add(_t(_l(document,"visibilitychange"),_l(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",Nt({quality:t,availableTracks:Nt(e),track:Nt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as rz,Observable as az,Subject as sz,ValueSubject as nz,VideoQuality as oz}from"@vkontakte/videoplayer-shared";var uz=`@vkontakte/videoplayer-core@${Ul}`;export{Ua as ChromecastState,Tn as HttpConnectionType,az as Observable,he as PlaybackState,vn as Player,Ha as PredefinedQualityLimits,uz as SDK_VERSION,sz as Subject,rz as Subscription,In as Surface,Ul as VERSION,nz as ValueSubject,It as VideoFormat,oz as VideoQuality};
|
|
124
|
+
`;var en=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Js(this.params.fov,this.params.orientation),this.cameraRotationManager=new Zs(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(mS,this.gl.VERTEX_SHADER),i=this.createShader(fS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-i,n=t-a,o=e+i,u=t-a,l=e+i,d=t+a,c=e-i,p=t+a;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as lM,now as bS,Subscription as cM,filter as dM,combine as gS,ValueSubject as Sl,isNonNullable as pM}from"@vkontakte/videoplayer-shared";var yl=class{constructor(){this.isSeeked$=new Sl(!1);this.isBuffering$=new Sl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new cM;this.severeStallOccurred$=new Sl(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(gS({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(dM(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(gS({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(lM(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:a,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=bS(),d=a&&this.currentStallsCount>=a,c=i&&l-this.lastUniqueVideoTrackSelectedTimestamp>=i+n&&l-u>=i+n&&t>=i;(d||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,pM(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=bS(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},vS=yl;import{combine as hM,map as mM,observeElementSize as fM,Subscription as bM,ValueSubject as Tl,noop as gM}from"@vkontakte/videoplayer-shared";var tn=class{constructor(){this.subscription=new bM;this.pipSize$=new Tl(void 0);this.videoSize$=new Tl(void 0);this.elementSize$=new Tl(void 0);this.pictureInPictureWindowRemoveEventListener=gM}connect({observableVideo:e,video:t}){let i=a=>{let s=a.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(fM(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:a})=>{this.pipSize$.next({width:a.width,height:a.height}),a.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{a.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(hM({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(mM(({videoSize:a,inPip:s,pipSize:n})=>s?n:a)).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 ci=class{constructor(e){this.subscription=new xM;this.videoState=new $("stopped");this.droppedFramesManager=new Cs;this.stallsManager=new vS;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 Ar;this.audioTrackSwitchHistory=new Ar;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(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"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&T(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&T(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()):i?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return yM(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new en(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=me(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(Z(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 Xs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=ge(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:SS.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(yS(l=>!!l.length),IS()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Il(l=>l.to.state!=="none"),Ea());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ea()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(yS(TS),IS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Il(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(tt(this.video,t.isLooped,a)),this.subscription.add(be(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,a)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(TM(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let m of d.audio){p.push(al(m));let f=[];for(let b of m.representations){let g=Gv(b);f.push(g),this.audioTracksMap.set(g,{stream:m,representation:b})}this.audioStreamsMap.set(m,f)}this.params.output.availableAudioStreams$.next(p)}let c=[];for(let p of d.video){c.push(sl(p));let m=[];for(let f of p.representations){let b=Qv({...f,streamId:p.id});b&&(m.push(b),this.videoTracksMap.set(b,{stream:p,representation:f}))}this.videoStreamsMap.set(p,m)}this.params.output.availableVideoStreams$.next(c);for(let p of d.text)for(let m of p.representations){let f=Wv(p,m);this.textTracksMap.set(f,{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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a)),this.subscription.add(rn(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,EM(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,ES.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[p,m]=c,f=[...this.videoTracksMap.keys()].find(g=>this.videoTracksMap.get(g)?.representation.id===p.id);TS(f)&&(this.stallsManager.lastVideoTrackSelected=f);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(p.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),m){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,g)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ea()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{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(c),e.currentVideoStream$.next(sl(p))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ea()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{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(al(p))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Il(({to:l})=>l==="ready"),Ea());this.subscription.add(rn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,El(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(rn(o,this.player.state$.stateChangeEnded$,El(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=rn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,El(["init"])).pipe(IM(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:L})=>L===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:L})=>L===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=rt(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(c/Math.min(p,m||1/0),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:L})=>L===b?.id)??this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!i){let L=Rs(n,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,L?.bitrate??-1/0)}if(o){let L=Rs(o,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,L?.bitrate??-1/0)}}let k=Mt(d,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),x=i?k??n:n??k,R=g&&Mb(x,d,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),y=this.videoTracksMap.get(x)?.representation,I=R&&this.audioTracksMap.get(R)?.representation;if(y&&I)return[y,I];if(y&&!I&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:SS.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),fe(this.video),this.tracer.end()}};var xa=class extends ci{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as xS,interval as PM,map as PS}from"@vkontakte/videoplayer-shared";var Pa=class extends ci{constructor(e){super(e),this.liveOffset=new pt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(t.timeUpdate$,e.liveBufferTime$),a(this.player.liveDuration$,e.duration$),a(this.player.liveLatency$,e.liveLatency$),this.subscription.add(i.isLowLatency.stateChangeEnded$.pipe(PS(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(xS({interval:PM(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(s-1);n<=0&&e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(xS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(PS(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Yv(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var wS=M(Es(),1);import{assertNever as ka,assertNonNullable as kS,debounce as kM,ErrorCategory as an,filter as wM,isNonNullable as AM,isNullable as LM,map as sn,merge as RM,Observable as $M,observableFrom as MM,Subscription as DM,videoSizeToQuality as CM}from"@vkontakte/videoplayer-shared";var Ye={};var zi=(r,e)=>new $M(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),wa=class{constructor(e){this.subscription=new DM;this.videoState=new $("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ka(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ka(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ka(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ka(e)}break;default:ka(t)}};this.textTracksManager=new Ce(e.source.url),this.video=me(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(Z(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),fe(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:an.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,wS.default)(import("hls.js").then(a=>{e||(Ye.Hls=a.default,Ye.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){kS(Ye.Hls,"hls.js not loaded"),this.hls=new Ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){kS(Ye.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:an.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=ge(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,i));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(tt(this.video,e.isLooped,i)),this.subscription.add(be(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(De(this.video,e.playbackRate,a.playbackRateState$,i)),s(Be(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(sn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(zi(this.hls,Ye.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:an.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(e.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(e.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(zi(this.hls,Ye.Events.MANIFEST_PARSED).pipe(sn(({levels:l})=>l.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:m,height:f}=c,b=Lt(c.attrs.QUALITY??"")??CM({width:m,height:f});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:m,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:c}),d.push(S),d},[]))),t.availableVideoTracks$),s(zi(this.hls,Ye.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,m=c.attrs.URI||"",f=c.lang;d.push({id:p,url:m,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(zi(this.hls,Ye.Events.LEVEL_LOADING).pipe(sn(({url:l})=>Z(l))),t.hostname$),s(zi(this.hls,Ye.Events.FRAG_CHANGED),l=>{let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3)}),this.subscription.add(kt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>Array.from(this.trackLevels.values()).find(({level:d})=>d===l)?.track,o=zi(this.hls,Ye.Events.LEVEL_SWITCHED).pipe(sn(({level:l})=>n(this.hls.levels[l])));o.pipe(wM(AM)).subscribe(t.currentVideoTrack$,i),this.subscription.add(kt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(LM(l))return;let d=this.trackLevels.get(l.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,m=this.hls.levels[p];!m||d.bitrate>m.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=RM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,MM(["init"])).pipe(kM(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:an.DOM,thrown:t}))||(this.videoState.setState("paused"),T(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"),T(this.params.desiredState.playbackState,"stopped",!0)}};var AS="X-Playback-Duration",xl=async r=>{let e=await Ge(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(AS)?parseInt(e.headers.get(AS),10):void 0};import{assertNever as QM,combine as GM,debounce as WM,ErrorCategory as un,filter as YM,filterChanged as zM,isNonNullable as $S,isNullable as ln,map as MS,merge as KM,observableFrom as XM,Subscription as JM,ValueSubject as wl,VideoQuality as ZM}from"@vkontakte/videoplayer-shared";var kl=M(Lo(),1);import{videoSizeToQuality as VM,getExponentialDelay as BM}from"@vkontakte/videoplayer-shared";var OM=r=>{let e=null;if(r.QUALITY&&(e=Lt(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=VM({width:t,height:i})}return e??null},_M=(r,e)=>{let t=r.split(`
|
|
125
|
+
`),i=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,kl.default)(o[1].split(",").map(g=>g.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,c=OM(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(k=>parseInt(k,10));g&&S&&(f={width:g,height:S})}let b=new URL(t[++s],e).toString();c&&i.push({id:d,quality:c,url:b,bandwidth:p,size:f,fps:m})}if(u){let l=(0,kl.default)(u[1].split(",").map(m=>{let f=m.indexOf("=");return[m.substring(0,f),m.substring(f+1)]}).map(([m,f])=>[m,f.replace(/^"|"$/g,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,p=l.NAME;d&&c&&a.push({type:"internal",id:c,label:p,language:c,url:d,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},NM=r=>new Promise(e=>{setTimeout(()=>{e()},r)}),Pl=0,LS=async(r,e=r,t,i)=>{let s=await(await Ge(r,i)).text();Pl+=1;try{let{qualityManifests:n,textTracks:o}=_M(s,e);return{qualityManifests:n,textTracks:o}}catch{if(Pl<=t.manifestRetryMaxCount)return await NM(BM(Pl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),LS(r,e,t)}return{qualityManifests:[],textTracks:[]}},nn=LS;import{isNonNullable as FM,Subscription as qM,throttle as UM,ValueSubject as RS,Subject as HM,ErrorCategory as jM}from"@vkontakte/videoplayer-shared";var on=class{constructor(e,t,i,a,s){this.subscription=new qM;this.abortControllers={destroy:new se,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new RS(null);this.getCurrentTime$=new RS(null);this.error$=new HM;this.params={fetchManifestData:i,sourceUrl:a,downloadThreshold:s},this.subscription.add(e.pipe(UM(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let a=new URL(i.url,t).toString(),n=await(await Ge(a,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,a);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},a=e.split(`
|
|
126
|
+
`),s=0;for(let n=0;n<a.length;++n){let o=a[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=a[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(FM(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:a}=t[t.length-1].time;if(e<i||e>a)return;a-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new se;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:jM.WTF,thrown:t,message:e})}};var Aa=class{constructor(e){this.subscription=new JM;this.videoState=new $("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new wl([]);this.liveOffset=new pt;this.manifestStartTime$=new wl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),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(a?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?T(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return QM(t)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ZM.INVARIANT,url:this.params.source.url};let t=(i,a)=>nn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new on(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ce(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:a})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:un.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:un.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new wl(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ge(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(be(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(zM(),MS(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&$S(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(m=>m.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(GM({startTime:this.manifestStartTime$.pipe(YM($S)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(MS(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=KM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XM(["init"])).pipe(WM(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){let e=this.selectManifest();if(ln(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&a.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(a.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),xl(n).then(o=>{if(!ln(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(ln(u)||!isFinite(u))&&Ge(n).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,n).toString();xl(c).then(p=>{ln(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:un.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ae(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as eD,debounce as tD,ErrorCategory as Al,fromEvent as Ll,isNonNullable as iD,isNullable as rD,map as DS,merge as CS,observableFrom as VS,Subscription as aD,ValueSubject as sD,VideoQuality as nD,clientChecker as oD}from"@vkontakte/videoplayer-shared";var La=class{constructor(e){this.subscription=new aD;this.videoState=new $("stopped");this.manifests$=new sD([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?T(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return eD(t)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:nD.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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),nn(ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Al.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!a||!a.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Al.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ge(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(DS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(be(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&iD(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===m);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Z(f.url)))}let c=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(DS(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!oD.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(CS(Ll(o,"addtrack"),Ll(o,"removetrack"),Ll(o,"change"),VS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=CS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,VS(["init"])).pipe(tD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){let e=this.selectManifest();if(rD(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Al.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var _S=M(ki(),1),Rl=M(Oi(),1),NS=M(Rt(),1);import{assertNever as uD,assertNonNullable as BS,debounce as lD,ErrorCategory as OS,isHigherOrEqual as cD,isLowerOrEqual as dD,isNonNullable as pD,merge as hD,observableFrom as mD,Subscription as fD,map as bD}from"@vkontakte/videoplayer-shared";var Ra=class{constructor(e){this.subscription=new fD;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Ce;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return uD(e)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),(0,_S.default)(this.params.source).reverse().forEach(([t,i],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Rl.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:OS.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ge(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(bD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(be(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,i)),s(Be(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&pD(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=hD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,mD(["init"])).pipe(lD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),fe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;BS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];BS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=fa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:OS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let d=Mt(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(d)},a=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Rl.default)(this.trackUrls).map(l=>l.track);if(!a||!s||wr({limits:e,lowestAvailableQuality:(0,NS.default)(n,-1)?.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?dD(a,e.max):!0,u=e.min?cD(a,e.min):!0;o&&u||i(e)}};import{assertNever as qS,debounce as yD,merge as US,observableFrom as TD,Subscription as ID,map as HS,ValueSubject as ED,ErrorCategory as Ml,VideoQuality as xD}from"@vkontakte/videoplayer-shared";import{ErrorCategory as gD}from"@vkontakte/videoplayer-shared";var FS=["stun:videostun.mycdn.me:80"],vD=1e3,SD=3,$l=()=>null,cn=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=$l;this.externalStopCallback=$l;this.externalErrorCallback=$l;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:FS}]};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:gD.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch{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),vD)}normalizeOptions(e={}){let t={stunServerList:FS,maxRetryNumber:SD,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 ED(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(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"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return qS(e)}};this.subscription=new ID,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=me(e.container,e.tuning),this.liveStreamClient=new cn(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),fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ml.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};US(this.videoState.stateChangeStarted$.pipe(HS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(HS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ge(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Be(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(be(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return qS(n.to)}},i)).add(US(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,TD(["init"])).pipe(yD(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Z(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:xD.INVARIANT}),this.video.srcObject=e,T(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:Ml.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ml.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ma=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 Da,assertNonNullable as Ot,ErrorCategory as dn,filter as zS,isNonNullable as KS,isNullable as MD,map as DD,merge as CD,once as VD,Subject as Ie,Subscription as XS,ValueSubject as D,flattenObject as JS}from"@vkontakte/videoplayer-shared";import{Observable as PD,map as jS,Subscription as kD,Subject as wD}from"@vkontakte/videoplayer-shared";var QS=r=>new PD(e=>{let t=new kD,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(jS(({from:l,to:d})=>`${l}-${d}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe(jS(({type:l})=>l!==void 0)),n=new wD,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),r.maxTransitionInterval)})),t.add(a.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),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as AD,Subscription as LD,combine as RD,filter as WS,once as YS}from"@vkontakte/videoplayer-shared";function GS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as $D}from"@vkontakte/videoplayer-shared";var Ki=class r{constructor(e,t,i,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.destroyController=new se;this.subscriptions=new LD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(WS(s=>!!s.type),YS()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$D.isSafari&&e!=="MPEG"||this.subscriptions.add(RD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(WS(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),YS()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=GS();this.audioContext=i;let a=i.createGain();if(this.gainNode=a,a.gain.value=t,a.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(a),!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){this.volumeMultiplierError$.next({id:r.errorId,category:AD.VIDEO_PIPELINE,message:e?.message??`${r.errorId} exception`,thrown:e})}};var BD={chunkDuration:5e3,maxParallelRequests:5},Ca=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new Ie;this.noAvailableProvidersError$=new Ie;this.volumeMultiplierError$=new Ie;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 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 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(""),getCurrentTime$:new D(null)};this.subscription=new XS;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=Tg([...Eg(this.params.tuning),...Ig(this.params.tuning)],this.params.tuning).filter(l=>KS(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]:a.length?s=[...t.filter(l=>!(0,Dl.default)(a,l)),...t.filter(l=>(0,Dl.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",JS(s)),this.screenFormatsIterator=new Ma(s);let n=[...Nu(!0),...Nu(!1)];this.chromecastFormatsIterator=new Ma(n.filter(l=>KS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ki.isSupported()&&(this.volumeMultiplierManager=new Ki(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(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(MD(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:dn.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Da(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:a}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:a,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 Ot(o),new xa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Pa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ot(o),Ui||!this.params.tuning.useHlsJs?new La({...n,source:o}):new wa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Aa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Ra({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new zb({...n,source:o,config:{...BD,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new $a({container:i,source:o,desiredState:a,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 Da(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ot(o),new Er({connection:o,meta:s,container:i,source:t,format:e,desiredState:a,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 Da(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Da(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 Da(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=a=>{let s=new URL(a);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,ey.default)((0,ZS.default)(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new XS,t=!1,i=0;return e.add(CD(this.providerOutput.error$.pipe(zS(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),QS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(DD(a=>({id:`ProviderHangup:${a}`,category:dn.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(zS(({to:s})=>s==="playing"),VD()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===dn.NETWORK,u=a.category===dn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",JS(n))})),e}};import{fromEvent as pn,once as OD,combine as _D,Subscription as ty,ValueSubject as Cl,map as ND,filter as FD,isNonNullable as hn,now as Ae,safeStorage as Vl}from"@vkontakte/videoplayer-shared";var qD=5e3,iy="one_video_throughput",ry="one_video_rtt",Va=window.navigator.connection,ay=()=>{let r=Va?.downlink;if(hn(r)&&r!==10)return r*1e3},sy=()=>{let r=Va?.rtt;if(hn(r)&&r!==3e3)return r},ny=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},Bl=class r{constructor(e){this.subscription=new ty;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load(iy)||(e.useBrowserEstimation?ay():void 0)||qD,i=r.load(ry)??(e.useBrowserEstimation?sy():void 0)??0;if(this.throughput$=new Cl(t),this.rtt$=new Cl(i),this.rttAdjustedThroughput$=new Cl(ny(t,i,e.rttPenaltyRequestSize)),this.throughput=si.getSmoothedValue(t,-1,e),this.rtt=si.getSmoothedValue(i,1,e),e.useBrowserEstimation){let a=()=>{let n=ay();n&&this.throughput.next(n);let o=sy();hn(o)&&this.rtt.next(o)};Va&&"onchange"in Va&&this.subscription.add(pn(Va,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Vl.set(iy,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Vl.set(ry,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(_D({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(ND(({throughput:a,rtt:s})=>ny(a,s,e.rttPenaltyRequestSize)),FD(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Ae(),a=new ty;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(pn(e,"progress").pipe(OD()).subscribe(s=>{t=s.loaded,i=Ae()}));break;case 1:case 0:a.add(pn(e,"loadstart").subscribe(()=>{t=0,i=Ae()}));break}a.add(pn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ae(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,s=Ae(),n=0,o=Ae(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(a,Ae()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=Ae();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,s=Ae()}else n+=c.byteLength;o=Ae()}else a+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ae()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ae()-o,this.concurrentDownloads.size),n=0,o=Ae());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,a=!1){if(r.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Vl.get(e);if(hn(t))return parseInt(t,10)??void 0}},oy=Bl;import{fillWithDefault as UD,VideoQuality as mn}from"@vkontakte/videoplayer-shared";var uy={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit: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:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1},ly=r=>({...UD(r,uy),configName:[...r.configName??[],...uy.configName]});import{assertNonNullable as fn,combine as vt,ErrorCategory as bn,filter as pe,filterChanged as N,fromEvent as _l,isNonNullable as zD,isNullable as KD,Logger as XD,map as O,mapTo as hy,merge as _t,now as gn,once as st,Subject as j,Subscription as my,tap as fy,ValueSubject as E,isHigher as JD,isInvariantQuality as by,flattenObject as Nt,throttle as Nl,getTraceSubscriptionMethod as gy,Tracer as ZD,InternalsExposure as eC}from"@vkontakte/videoplayer-shared";import{merge as HD,map as jD,filter as cy,isNonNullable as QD}from"@vkontakte/videoplayer-shared";var Ol=({seekState:r,position$:e})=>HD(r.stateChangeEnded$.pipe(jD(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),cy(QD)),e.pipe(cy(()=>r.getState().state==="none")));import{assertNonNullable as GD}from"@vkontakte/videoplayer-shared";var dy=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return GD(e,`Wrong container or containerId {${r.container}}`),e};import{filter as WD,once as YD}from"@vkontakte/videoplayer-shared";var py=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(WD(a=>a.length>0),YD()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};var vn=class{constructor(e={configName:[]},t=ZD.createRootTracer(!1)){this.subscription=new my;this.logger=new XD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!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 E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),predefinedQualityLimitType$:new E("unknown"),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),liveLatency$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(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 E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:Sb,getCurrentTime$:new E(null)};if(this.initLogs(),this.tuning=ly(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new za({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new oy(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new eC("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,a,s)=>{let n=Reflect.get(i,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(m,f)=>{let b=typeof f;return(0,vy.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),d=`Player.${String(a)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:bn.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",Nt(i)),this.domContainer=dy(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ca({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.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&&!Dr()?(this.tracer.log("request play from hidden tab"),_l(document,"visibilitychange").pipe(st()).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 i=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=i&&!a&&(s=i-.2),this.tracer.log("seekTime",{duration:i,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t})),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){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){fn(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(pe(i=>i.length>0),st()).subscribe(i=>{this.setVideoTrackIdByQuality(i,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:i}=this.tuning.autoTrackSelection,a;switch(e){case"high_quality":a={min:t,max:void 0};break;case"traffic_saving":a={max:i,min:void 0};break;default:a={max:void 0,min:void 0}}return this.setAutoQualityLimits(a),this}setPlaybackRate(e){fn(this.providerContainer);let t=this.providerContainer?.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){return py(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.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(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.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 i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let a=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.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(KD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return zD(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||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(O(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(xu({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pe(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=gn(),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:bn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(st()).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(O(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(O(n=>n.destination),N()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(vt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(O(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>by(u)?1:by(l)?-1:JD(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?.quality),this.info.videoBitrate$.next(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??{})})).add(e.providerOutput.currentBuffer$.pipe(O(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(vt({hasLiveOffsetByPaused:_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(n=>n.to),N(),O(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(vt({atLiveEdge:vt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ol({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(O(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),N(),fy(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(O(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(vt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(O(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),N(),fy(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(O(n=>n.muted),N()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(O(n=>n.volume),N()).subscribe(this.info.volume$)).add(Ol({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(_t(e.providerOutput.endedEvent$.pipe(hy(!0)),e.providerOutput.seekedEvent$.pipe(hy(!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(O(n=>({id:n?`No${n}`:"NoProviders",category:bn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(st(),O(n=>n??gn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),O(()=>gn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),O(()=>gn()-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 E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(pe(({to:n})=>n==="playing"),st()).subscribe(()=>i.next(!1)));let a=0,s=_t(e.providerOutput.isBuffering$,t,i).pipe(O(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),N());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),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?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height: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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(O(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new my;this.subscription.add(t),this.subscription.add(e.current$.pipe(N((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pe(i=>i.length>0),st()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:a})=>a===i),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(_t(this.desiredState.videoTrack.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(O(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(){let e=this.providerContainer?.providerOutput;fn(this.providerContainer),fn(e),vb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>gb(t)),this.providerContainer.current$.subscribe(({type:t})=>kr("provider",t)),e.duration$.subscribe(t=>kr("duration",t)),e.availableVideoTracks$.pipe(pe(t=>!!t.length),st()).subscribe(t=>kr("tracks",t)),this.events.fatalError$.subscribe(new le("fatalError")),this.events.managedError$.subscribe(new le("managedError")),e.position$.subscribe(new le("position")),e.currentVideoTrack$.pipe(O(t=>t?.quality)).subscribe(new le("quality")),this.info.currentBuffer$.subscribe(new le("buffer")),e.isBuffering$.subscribe(new le("isBuffering"))].forEach(t=>this.subscription.add(t)),kr("codecs",yg())}initTracerSubscription(){let e=gy(this.tracer.log.bind(this.tracer)),t=gy(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(vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(pe(({currentQuality:i,videoBitrate:a})=>!!i&&!!a),N((i,a)=>i.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(pe(i=>i>0),N()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(pe(i=>i>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(vt({currentBuffer:this.info.currentBuffer$.pipe(pe(i=>i.end>0),N((i,a)=>i.end===a.end&&i.start===a.start)),position:this.info.position$.pipe(N())}).pipe(Nl(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(vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(pe(({liveTime:i,liveBufferTime:a})=>!!i&&!!a),Nl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(N(),pe(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(N(),pe(i=>i===!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(),pe(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(pe(({throughputEstimation:i,rtt:a})=>!!i&&!!a),Nl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(N(),pe(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:bn.DOM,message:String(a)})})};this.subscription.add(_t(_l(document,"visibilitychange"),_l(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",Nt({quality:t,availableTracks:Nt(e),track:Nt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as r3,Observable as a3,Subject as s3,ValueSubject as n3,VideoQuality as o3}from"@vkontakte/videoplayer-shared";var u3=`@vkontakte/videoplayer-core@${Ul}`;export{Ua as ChromecastState,Tn as HttpConnectionType,a3 as Observable,he as PlaybackState,vn as Player,Ha as PredefinedQualityLimits,u3 as SDK_VERSION,s3 as Subject,r3 as Subscription,In as Surface,Ul as VERSION,n3 as ValueSubject,It as VideoFormat,o3 as VideoQuality};
|