@vkontakte/videoplayer-core 2.0.117-dev.85ef0d1b.0 → 2.0.117-dev.8d5a23be.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,48 +1,48 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.117-dev.85ef0d1b.0
3
- * Thu, 07 Nov 2024 22:00:55 GMT
2
+ * @vkontakte/videoplayer-core v2.0.117-dev.8d5a23be.0
3
+ * Fri, 08 Nov 2024 08:52:55 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-117/doc/
5
5
  */
6
- var kv=Object.create;var kn=Object.defineProperty,Rv=Object.defineProperties,$v=Object.getOwnPropertyDescriptor,Lv=Object.getOwnPropertyDescriptors,Mv=Object.getOwnPropertyNames,Wa=Object.getOwnPropertySymbols,Cv=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty,dc=Object.prototype.propertyIsEnumerable;var Dv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var De=Math.pow,cc=(a,e,t)=>e in a?kn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,w=(a,e)=>{for(var t in e||(e={}))Rn.call(e,t)&&cc(a,t,e[t]);if(Wa)for(var t of Wa(e))dc.call(e,t)&&cc(a,t,e[t]);return a},B=(a,e)=>Rv(a,Lv(e));var pc=(a,e)=>{var t={};for(var r in a)Rn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Wa)for(var r of Wa(a))e.indexOf(r)<0&&dc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Bv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Mv(e))!Rn.call(a,i)&&i!==t&&kn(a,i,{get:()=>e[i],enumerable:!(r=$v(e,i))||r.enumerable});return a};var We=(a,e,t)=>(t=a!=null?kv(Cv(a)):{},Bv(e||!a||!a.__esModule?kn(t,"default",{value:a,enumerable:!0}):t,a));var k=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),$n=function(a,e){this[0]=a,this[1]=e},Z=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof $n,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?r(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>r("throw",p,u,l))}catch(p){l(p)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[Dv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Pe=m((VL,yc)=>{"use strict";yc.exports=function(a){try{return!!a()}catch(e){return!0}}});var ii=m((_L,Tc)=>{"use strict";var Hv=Pe();Tc.exports=!Hv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var me=m((NL,xc)=>{"use strict";var Ic=ii(),Ec=Function.prototype,Bn=Ec.call,jv=Ic&&Ec.bind.bind(Bn,Bn);xc.exports=Ic?jv:function(a){return function(){return Bn.apply(a,arguments)}}});var yr=m((FL,Ac)=>{"use strict";var Pc=me(),Gv=Pc({}.toString),Wv=Pc("".slice);Ac.exports=function(a){return Wv(Gv(a),8,-1)}});var kc=m((UL,wc)=>{"use strict";var Yv=me(),Qv=Pe(),zv=yr(),On=Object,Kv=Yv("".split);wc.exports=Qv(function(){return!On("z").propertyIsEnumerable(0)})?function(a){return zv(a)==="String"?Kv(a,""):On(a)}:On});var Tr=m((qL,Rc)=>{"use strict";Rc.exports=function(a){return a==null}});var ai=m((HL,$c)=>{"use strict";var Jv=Tr(),Xv=TypeError;$c.exports=function(a){if(Jv(a))throw new Xv("Can't call method on "+a);return a}});var Ir=m((jL,Lc)=>{"use strict";var Zv=kc(),ey=ai();Lc.exports=function(a){return Zv(ey(a))}});var Vn=m((GL,Mc)=>{"use strict";Mc.exports=function(){}});var Wt=m((WL,Cc)=>{"use strict";Cc.exports={}});var X=m((_n,Dc)=>{"use strict";var si=function(a){return a&&a.Math===Math&&a};Dc.exports=si(typeof globalThis=="object"&&globalThis)||si(typeof window=="object"&&window)||si(typeof self=="object"&&self)||si(typeof global=="object"&&global)||si(typeof _n=="object"&&_n)||function(){return this}()||Function("return this")()});var J=m((YL,Bc)=>{"use strict";var Nn=typeof document=="object"&&document.all;Bc.exports=typeof Nn=="undefined"&&Nn!==void 0?function(a){return typeof a=="function"||a===Nn}:function(a){return typeof a=="function"}});var _c=m((QL,Vc)=>{"use strict";var ty=X(),ry=J(),Oc=ty.WeakMap;Vc.exports=ry(Oc)&&/native code/.test(String(Oc))});var Be=m((zL,Nc)=>{"use strict";var iy=J();Nc.exports=function(a){return typeof a=="object"?a!==null:iy(a)}});var Oe=m((KL,Fc)=>{"use strict";var ay=Pe();Fc.exports=!ay(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ka=m((JL,qc)=>{"use strict";var sy=X(),Uc=Be(),Fn=sy.document,ny=Uc(Fn)&&Uc(Fn.createElement);qc.exports=function(a){return ny?Fn.createElement(a):{}}});var Un=m((XL,Hc)=>{"use strict";var oy=Oe(),uy=Pe(),ly=Ka();Hc.exports=!oy&&!uy(function(){return Object.defineProperty(ly("div"),"a",{get:function(){return 7}}).a!==7})});var qn=m((ZL,jc)=>{"use strict";var cy=Oe(),dy=Pe();jc.exports=cy&&dy(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var tt=m((eM,Gc)=>{"use strict";var py=Be(),hy=String,fy=TypeError;Gc.exports=function(a){if(py(a))return a;throw new fy(hy(a)+" is not an object")}});var Ae=m((tM,Wc)=>{"use strict";var my=ii(),Ja=Function.prototype.call;Wc.exports=my?Ja.bind(Ja):function(){return Ja.apply(Ja,arguments)}});var Xa=m((rM,Yc)=>{"use strict";Yc.exports={}});var ot=m((iM,zc)=>{"use strict";var Hn=Xa(),jn=X(),by=J(),Qc=function(a){return by(a)?a:void 0};zc.exports=function(a,e){return arguments.length<2?Qc(Hn[a])||Qc(jn[a]):Hn[a]&&Hn[a][e]||jn[a]&&jn[a][e]}});var ni=m((aM,Kc)=>{"use strict";var gy=me();Kc.exports=gy({}.isPrototypeOf)});var Er=m((sM,Zc)=>{"use strict";var Sy=X(),Jc=Sy.navigator,Xc=Jc&&Jc.userAgent;Zc.exports=Xc?String(Xc):""});var Wn=m((nM,sd)=>{"use strict";var ad=X(),Gn=Er(),ed=ad.process,td=ad.Deno,rd=ed&&ed.versions||td&&td.version,id=rd&&rd.v8,Ye,Za;id&&(Ye=id.split("."),Za=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!Za&&Gn&&(Ye=Gn.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=Gn.match(/Chrome\/(\d+)/),Ye&&(Za=+Ye[1])));sd.exports=Za});var Yn=m((oM,od)=>{"use strict";var nd=Wn(),vy=Pe(),yy=X(),Ty=yy.String;od.exports=!!Object.getOwnPropertySymbols&&!vy(function(){var a=Symbol("symbol detection");return!Ty(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&nd&&nd<41})});var Qn=m((uM,ud)=>{"use strict";var Iy=Yn();ud.exports=Iy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var zn=m((lM,ld)=>{"use strict";var Ey=ot(),xy=J(),Py=ni(),Ay=Qn(),wy=Object;ld.exports=Ay?function(a){return typeof a=="symbol"}:function(a){var e=Ey("Symbol");return xy(e)&&Py(e.prototype,wy(a))}});var oi=m((cM,cd)=>{"use strict";var ky=String;cd.exports=function(a){try{return ky(a)}catch(e){return"Object"}}});var ut=m((dM,dd)=>{"use strict";var Ry=J(),$y=oi(),Ly=TypeError;dd.exports=function(a){if(Ry(a))return a;throw new Ly($y(a)+" is not a function")}});var ui=m((pM,pd)=>{"use strict";var My=ut(),Cy=Tr();pd.exports=function(a,e){var t=a[e];return Cy(t)?void 0:My(t)}});var fd=m((hM,hd)=>{"use strict";var Kn=Ae(),Jn=J(),Xn=Be(),Dy=TypeError;hd.exports=function(a,e){var t,r;if(e==="string"&&Jn(t=a.toString)&&!Xn(r=Kn(t,a))||Jn(t=a.valueOf)&&!Xn(r=Kn(t,a))||e!=="string"&&Jn(t=a.toString)&&!Xn(r=Kn(t,a)))return r;throw new Dy("Can't convert object to primitive value")}});var Qe=m((fM,md)=>{"use strict";md.exports=!0});var Sd=m((mM,gd)=>{"use strict";var bd=X(),By=Object.defineProperty;gd.exports=function(a,e){try{By(bd,a,{value:e,configurable:!0,writable:!0})}catch(t){bd[a]=e}return e}});var li=m((bM,Td)=>{"use strict";var Oy=Qe(),Vy=X(),_y=Sd(),vd="__core-js_shared__",yd=Td.exports=Vy[vd]||_y(vd,{});(yd.versions||(yd.versions=[])).push({version:"3.38.0",mode:Oy?"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 Zn=m((gM,Ed)=>{"use strict";var Id=li();Ed.exports=function(a,e){return Id[a]||(Id[a]=e||{})}});var ci=m((SM,xd)=>{"use strict";var Ny=ai(),Fy=Object;xd.exports=function(a){return Fy(Ny(a))}});var ze=m((vM,Pd)=>{"use strict";var Uy=me(),qy=ci(),Hy=Uy({}.hasOwnProperty);Pd.exports=Object.hasOwn||function(e,t){return Hy(qy(e),t)}});var eo=m((yM,Ad)=>{"use strict";var jy=me(),Gy=0,Wy=Math.random(),Yy=jy(1 .toString);Ad.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Yy(++Gy+Wy,36)}});var ce=m((TM,kd)=>{"use strict";var Qy=X(),zy=Zn(),wd=ze(),Ky=eo(),Jy=Yn(),Xy=Qn(),xr=Qy.Symbol,to=zy("wks"),Zy=Xy?xr.for||xr:xr&&xr.withoutSetter||Ky;kd.exports=function(a){return wd(to,a)||(to[a]=Jy&&wd(xr,a)?xr[a]:Zy("Symbol."+a)),to[a]}});var Md=m((IM,Ld)=>{"use strict";var eT=Ae(),Rd=Be(),$d=zn(),tT=ui(),rT=fd(),iT=ce(),aT=TypeError,sT=iT("toPrimitive");Ld.exports=function(a,e){if(!Rd(a)||$d(a))return a;var t=tT(a,sT),r;if(t){if(e===void 0&&(e="default"),r=eT(t,a,e),!Rd(r)||$d(r))return r;throw new aT("Can't convert object to primitive value")}return e===void 0&&(e="number"),rT(a,e)}});var ro=m((EM,Cd)=>{"use strict";var nT=Md(),oT=zn();Cd.exports=function(a){var e=nT(a,"string");return oT(e)?e:e+""}});var Yt=m(Bd=>{"use strict";var uT=Oe(),lT=Un(),cT=qn(),es=tt(),Dd=ro(),dT=TypeError,io=Object.defineProperty,pT=Object.getOwnPropertyDescriptor,ao="enumerable",so="configurable",no="writable";Bd.f=uT?cT?function(e,t,r){if(es(e),t=Dd(t),es(r),typeof e=="function"&&t==="prototype"&&"value"in r&&no in r&&!r[no]){var i=pT(e,t);i&&i[no]&&(e[t]=r.value,r={configurable:so in r?r[so]:i[so],enumerable:ao in r?r[ao]:i[ao],writable:!1})}return io(e,t,r)}:io:function(e,t,r){if(es(e),t=Dd(t),es(r),lT)try{return io(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new dT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var di=m((PM,Od)=>{"use strict";Od.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Pr=m((AM,Vd)=>{"use strict";var hT=Oe(),fT=Yt(),mT=di();Vd.exports=hT?function(a,e,t){return fT.f(a,e,mT(1,t))}:function(a,e,t){return a[e]=t,a}});var ts=m((wM,Nd)=>{"use strict";var bT=Zn(),gT=eo(),_d=bT("keys");Nd.exports=function(a){return _d[a]||(_d[a]=gT(a))}});var rs=m((kM,Fd)=>{"use strict";Fd.exports={}});var co=m((RM,Hd)=>{"use strict";var ST=_c(),qd=X(),vT=Be(),yT=Pr(),oo=ze(),uo=li(),TT=ts(),IT=rs(),Ud="Object already initialized",lo=qd.TypeError,ET=qd.WeakMap,is,pi,as,xT=function(a){return as(a)?pi(a):is(a,{})},PT=function(a){return function(e){var t;if(!vT(e)||(t=pi(e)).type!==a)throw new lo("Incompatible receiver, "+a+" required");return t}};ST||uo.state?(Ke=uo.state||(uo.state=new ET),Ke.get=Ke.get,Ke.has=Ke.has,Ke.set=Ke.set,is=function(a,e){if(Ke.has(a))throw new lo(Ud);return e.facade=a,Ke.set(a,e),e},pi=function(a){return Ke.get(a)||{}},as=function(a){return Ke.has(a)}):(Qt=TT("state"),IT[Qt]=!0,is=function(a,e){if(oo(a,Qt))throw new lo(Ud);return e.facade=a,yT(a,Qt,e),e},pi=function(a){return oo(a,Qt)?a[Qt]:{}},as=function(a){return oo(a,Qt)});var Ke,Qt;Hd.exports={set:is,get:pi,has:as,enforce:xT,getterFor:PT}});var po=m(($M,Yd)=>{"use strict";var AT=ii(),Wd=Function.prototype,jd=Wd.apply,Gd=Wd.call;Yd.exports=typeof Reflect=="object"&&Reflect.apply||(AT?Gd.bind(jd):function(){return Gd.apply(jd,arguments)})});var ho=m((LM,Qd)=>{"use strict";var wT=yr(),kT=me();Qd.exports=function(a){if(wT(a)==="Function")return kT(a)}});var Xd=m(Jd=>{"use strict";var zd={}.propertyIsEnumerable,Kd=Object.getOwnPropertyDescriptor,RT=Kd&&!zd.call({1:2},1);Jd.f=RT?function(e){var t=Kd(this,e);return!!t&&t.enumerable}:zd});var tp=m(ep=>{"use strict";var $T=Oe(),LT=Ae(),MT=Xd(),CT=di(),DT=Ir(),BT=ro(),OT=ze(),VT=Un(),Zd=Object.getOwnPropertyDescriptor;ep.f=$T?Zd:function(e,t){if(e=DT(e),t=BT(t),VT)try{return Zd(e,t)}catch(r){}if(OT(e,t))return CT(!LT(MT.f,e,t),e[t])}});var fo=m((DM,rp)=>{"use strict";var _T=Pe(),NT=J(),FT=/#|\.prototype\./,hi=function(a,e){var t=qT[UT(a)];return t===jT?!0:t===HT?!1:NT(e)?_T(e):!!e},UT=hi.normalize=function(a){return String(a).replace(FT,".").toLowerCase()},qT=hi.data={},HT=hi.NATIVE="N",jT=hi.POLYFILL="P";rp.exports=hi});var fi=m((BM,ap)=>{"use strict";var ip=ho(),GT=ut(),WT=ii(),YT=ip(ip.bind);ap.exports=function(a,e){return GT(a),e===void 0?a:WT?YT(a,e):function(){return a.apply(e,arguments)}}});var Ve=m((OM,np)=>{"use strict";var mi=X(),QT=po(),zT=ho(),KT=J(),JT=tp().f,XT=fo(),Ar=Xa(),ZT=fi(),wr=Pr(),sp=ze();li();var eI=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return QT(a,this,arguments)};return e.prototype=a.prototype,e};np.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?mi:i?mi[t]:mi[t]&&mi[t].prototype,o=r?Ar:Ar[t]||wr(Ar,t,{})[t],u=o.prototype,l,c,d,h,p,f,b,g,v;for(h in e)l=XT(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&sp(n,h),f=o[h],c&&(a.dontCallGetSet?(v=JT(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?g=ZT(p,mi):a.wrap&&c?g=eI(p):s&&KT(p)?g=zT(p):g=p,(a.sham||p&&p.sham||f&&f.sham)&&wr(g,"sham",!0),wr(o,h,g),s&&(d=t+"Prototype",sp(Ar,d)||wr(Ar,d,{}),wr(Ar[d],h,p),a.real&&u&&(l||!u[h])&&wr(u,h,p)))}});var lp=m((VM,up)=>{"use strict";var mo=Oe(),tI=ze(),op=Function.prototype,rI=mo&&Object.getOwnPropertyDescriptor,bo=tI(op,"name"),iI=bo&&function(){}.name==="something",aI=bo&&(!mo||mo&&rI(op,"name").configurable);up.exports={EXISTS:bo,PROPER:iI,CONFIGURABLE:aI}});var dp=m((_M,cp)=>{"use strict";var sI=Math.ceil,nI=Math.floor;cp.exports=Math.trunc||function(e){var t=+e;return(t>0?nI:sI)(t)}});var ss=m((NM,pp)=>{"use strict";var oI=dp();pp.exports=function(a){var e=+a;return e!==e||e===0?0:oI(e)}});var fp=m((FM,hp)=>{"use strict";var uI=ss(),lI=Math.max,cI=Math.min;hp.exports=function(a,e){var t=uI(a);return t<0?lI(t+e,0):cI(t,e)}});var bp=m((UM,mp)=>{"use strict";var dI=ss(),pI=Math.min;mp.exports=function(a){var e=dI(a);return e>0?pI(e,9007199254740991):0}});var ns=m((qM,gp)=>{"use strict";var hI=bp();gp.exports=function(a){return hI(a.length)}});var yp=m((HM,vp)=>{"use strict";var fI=Ir(),mI=fp(),bI=ns(),Sp=function(a){return function(e,t,r){var i=fI(e),s=bI(i);if(s===0)return!a&&-1;var n=mI(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};vp.exports={includes:Sp(!0),indexOf:Sp(!1)}});var Ep=m((jM,Ip)=>{"use strict";var gI=me(),go=ze(),SI=Ir(),vI=yp().indexOf,yI=rs(),Tp=gI([].push);Ip.exports=function(a,e){var t=SI(a),r=0,i=[],s;for(s in t)!go(yI,s)&&go(t,s)&&Tp(i,s);for(;e.length>r;)go(t,s=e[r++])&&(~vI(i,s)||Tp(i,s));return i}});var So=m((GM,xp)=>{"use strict";xp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ap=m((WM,Pp)=>{"use strict";var TI=Ep(),II=So();Pp.exports=Object.keys||function(e){return TI(e,II)}});var kp=m(wp=>{"use strict";var EI=Oe(),xI=qn(),PI=Yt(),AI=tt(),wI=Ir(),kI=Ap();wp.f=EI&&!xI?Object.defineProperties:function(e,t){AI(e);for(var r=wI(t),i=kI(t),s=i.length,n=0,o;s>n;)PI.f(e,o=i[n++],r[o]);return e}});var vo=m((QM,Rp)=>{"use strict";var RI=ot();Rp.exports=RI("document","documentElement")});var Eo=m((zM,Op)=>{"use strict";var $I=tt(),LI=kp(),$p=So(),MI=rs(),CI=vo(),DI=Ka(),BI=ts(),Lp=">",Mp="<",To="prototype",Io="script",Dp=BI("IE_PROTO"),yo=function(){},Bp=function(a){return Mp+Io+Lp+a+Mp+"/"+Io+Lp},Cp=function(a){a.write(Bp("")),a.close();var e=a.parentWindow.Object;return a=null,e},OI=function(){var a=DI("iframe"),e="java"+Io+":",t;return a.style.display="none",CI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Bp("document.F=Object")),t.close(),t.F},os,us=function(){try{os=new ActiveXObject("htmlfile")}catch(e){}us=typeof document!="undefined"?document.domain&&os?Cp(os):OI():Cp(os);for(var a=$p.length;a--;)delete us[To][$p[a]];return us()};MI[Dp]=!0;Op.exports=Object.create||function(e,t){var r;return e!==null?(yo[To]=$I(e),r=new yo,yo[To]=null,r[Dp]=e):r=us(),t===void 0?r:LI.f(r,t)}});var _p=m((KM,Vp)=>{"use strict";var VI=Pe();Vp.exports=!VI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Po=m((JM,Fp)=>{"use strict";var _I=ze(),NI=J(),FI=ci(),UI=ts(),qI=_p(),Np=UI("IE_PROTO"),xo=Object,HI=xo.prototype;Fp.exports=qI?xo.getPrototypeOf:function(a){var e=FI(a);if(_I(e,Np))return e[Np];var t=e.constructor;return NI(t)&&e instanceof t?t.prototype:e instanceof xo?HI:null}});var kr=m((XM,Up)=>{"use strict";var jI=Pr();Up.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:jI(a,e,t),a}});var Ro=m((ZM,jp)=>{"use strict";var GI=Pe(),WI=J(),YI=Be(),QI=Eo(),qp=Po(),zI=kr(),KI=ce(),JI=Qe(),ko=KI("iterator"),Hp=!1,lt,Ao,wo;[].keys&&(wo=[].keys(),"next"in wo?(Ao=qp(qp(wo)),Ao!==Object.prototype&&(lt=Ao)):Hp=!0);var XI=!YI(lt)||GI(function(){var a={};return lt[ko].call(a)!==a});XI?lt={}:JI&&(lt=QI(lt));WI(lt[ko])||zI(lt,ko,function(){return this});jp.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Hp}});var ls=m((eC,Wp)=>{"use strict";var ZI=ce(),eE=ZI("toStringTag"),Gp={};Gp[eE]="z";Wp.exports=String(Gp)==="[object z]"});var bi=m((tC,Yp)=>{"use strict";var tE=ls(),rE=J(),cs=yr(),iE=ce(),aE=iE("toStringTag"),sE=Object,nE=cs(function(){return arguments}())==="Arguments",oE=function(a,e){try{return a[e]}catch(t){}};Yp.exports=tE?cs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=oE(e=sE(a),aE))=="string"?t:nE?cs(e):(r=cs(e))==="Object"&&rE(e.callee)?"Arguments":r}});var zp=m((rC,Qp)=>{"use strict";var uE=ls(),lE=bi();Qp.exports=uE?{}.toString:function(){return"[object "+lE(this)+"]"}});var gi=m((iC,Jp)=>{"use strict";var cE=ls(),dE=Yt().f,pE=Pr(),hE=ze(),fE=zp(),mE=ce(),Kp=mE("toStringTag");Jp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(hE(i,Kp)||dE(i,Kp,{configurable:!0,value:e}),r&&!cE&&pE(i,"toString",fE))}});var Zp=m((aC,Xp)=>{"use strict";var bE=Ro().IteratorPrototype,gE=Eo(),SE=di(),vE=gi(),yE=Wt(),TE=function(){return this};Xp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=gE(bE,{next:SE(+!r,t)}),vE(a,i,!1,!0),yE[i]=TE,a}});var th=m((sC,eh)=>{"use strict";var IE=me(),EE=ut();eh.exports=function(a,e,t){try{return IE(EE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var ih=m((nC,rh)=>{"use strict";var xE=Be();rh.exports=function(a){return xE(a)||a===null}});var sh=m((oC,ah)=>{"use strict";var PE=ih(),AE=String,wE=TypeError;ah.exports=function(a){if(PE(a))return a;throw new wE("Can't set "+AE(a)+" as a prototype")}});var $o=m((uC,nh)=>{"use strict";var kE=th(),RE=Be(),$E=ai(),LE=sh();nh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=kE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return $E(i),LE(s),RE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var gh=m((lC,bh)=>{"use strict";var ME=Ve(),CE=Ae(),ds=Qe(),fh=lp(),DE=J(),BE=Zp(),oh=Po(),uh=$o(),OE=gi(),VE=Pr(),Lo=kr(),_E=ce(),lh=Wt(),mh=Ro(),NE=fh.PROPER,FE=fh.CONFIGURABLE,ch=mh.IteratorPrototype,ps=mh.BUGGY_SAFARI_ITERATORS,Si=_E("iterator"),dh="keys",vi="values",ph="entries",hh=function(){return this};bh.exports=function(a,e,t,r,i,s,n){BE(t,e,r);var o=function(v){if(v===i&&h)return h;if(!ps&&v&&v in c)return c[v];switch(v){case dh:return function(){return new t(this,v)};case vi:return function(){return new t(this,v)};case ph:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Si]||c["@@iterator"]||i&&c[i],h=!ps&&d||o(i),p=e==="Array"&&c.entries||d,f,b,g;if(p&&(f=oh(p.call(new a)),f!==Object.prototype&&f.next&&(!ds&&oh(f)!==ch&&(uh?uh(f,ch):DE(f[Si])||Lo(f,Si,hh)),OE(f,u,!0,!0),ds&&(lh[u]=hh))),NE&&i===vi&&d&&d.name!==vi&&(!ds&&FE?VE(c,"name",vi):(l=!0,h=function(){return CE(d,this)})),i)if(b={values:o(vi),keys:s?h:o(dh),entries:o(ph)},n)for(g in b)(ps||l||!(g in c))&&Lo(c,g,b[g]);else ME({target:e,proto:!0,forced:ps||l},b);return(!ds||n)&&c[Si]!==h&&Lo(c,Si,h,{name:i}),lh[e]=h,b}});var vh=m((cC,Sh)=>{"use strict";Sh.exports=function(a,e){return{value:a,done:e}}});var Co=m((dC,xh)=>{"use strict";var UE=Ir(),Mo=Vn(),yh=Wt(),Ih=co(),qE=Yt().f,HE=gh(),hs=vh(),jE=Qe(),GE=Oe(),Eh="Array Iterator",WE=Ih.set,YE=Ih.getterFor(Eh);xh.exports=HE(Array,"Array",function(a,e){WE(this,{type:Eh,target:UE(a),index:0,kind:e})},function(){var a=YE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,hs(void 0,!0);switch(a.kind){case"keys":return hs(t,!1);case"values":return hs(e[t],!1)}return hs([t,e[t]],!1)},"values");var Th=yh.Arguments=yh.Array;Mo("keys");Mo("values");Mo("entries");if(!jE&&GE&&Th.name!=="values")try{qE(Th,"name",{value:"values"})}catch(a){}});var Ah=m((pC,Ph)=>{"use strict";var QE=ce(),zE=Wt(),KE=QE("iterator"),JE=Array.prototype;Ph.exports=function(a){return a!==void 0&&(zE.Array===a||JE[KE]===a)}});var Do=m((hC,kh)=>{"use strict";var XE=bi(),wh=ui(),ZE=Tr(),ex=Wt(),tx=ce(),rx=tx("iterator");kh.exports=function(a){if(!ZE(a))return wh(a,rx)||wh(a,"@@iterator")||ex[XE(a)]}});var $h=m((fC,Rh)=>{"use strict";var ix=Ae(),ax=ut(),sx=tt(),nx=oi(),ox=Do(),ux=TypeError;Rh.exports=function(a,e){var t=arguments.length<2?ox(a):e;if(ax(t))return sx(ix(t,a));throw new ux(nx(a)+" is not iterable")}});var Ch=m((mC,Mh)=>{"use strict";var lx=Ae(),Lh=tt(),cx=ui();Mh.exports=function(a,e,t){var r,i;Lh(a);try{if(r=cx(a,"return"),!r){if(e==="throw")throw t;return t}r=lx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Lh(r),t}});var ms=m((bC,Vh)=>{"use strict";var dx=fi(),px=Ae(),hx=tt(),fx=oi(),mx=Ah(),bx=ns(),Dh=ni(),gx=$h(),Sx=Do(),Bh=Ch(),vx=TypeError,fs=function(a,e){this.stopped=a,this.result=e},Oh=fs.prototype;Vh.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=dx(e,r),l,c,d,h,p,f,b,g=function(y){return l&&Bh(l,"normal",y),new fs(!0,y)},v=function(y){return i?(hx(y),o?u(y[0],y[1],g):u(y[0],y[1])):o?u(y,g):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Sx(a),!c)throw new vx(fx(a)+" is not iterable");if(mx(c)){for(d=0,h=bx(a);h>d;d++)if(p=v(a[d]),p&&Dh(Oh,p))return p;return new fs(!1)}l=gx(a,c)}for(f=s?a.next:l.next;!(b=px(f,l)).done;){try{p=v(b.value)}catch(y){Bh(l,"throw",y)}if(typeof p=="object"&&p&&Dh(Oh,p))return p}return new fs(!1)}});var Nh=m((gC,_h)=>{"use strict";var yx=Oe(),Tx=Yt(),Ix=di();_h.exports=function(a,e,t){yx?Tx.f(a,e,Ix(0,t)):a[e]=t}});var Fh=m(()=>{"use strict";var Ex=Ve(),xx=ms(),Px=Nh();Ex({target:"Object",stat:!0},{fromEntries:function(e){var t={};return xx(e,function(r,i){Px(t,r,i)},{AS_ENTRIES:!0}),t}})});var qh=m((yC,Uh)=>{"use strict";Co();Fh();var Ax=Xa();Uh.exports=Ax.Object.fromEntries});var jh=m((TC,Hh)=>{"use strict";Hh.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 Wh=m(()=>{"use strict";Co();var wx=jh(),kx=X(),Rx=gi(),Gh=Wt();for(bs in wx)Rx(kx[bs],bs),Gh[bs]=Gh.Array;var bs});var Qh=m((xC,Yh)=>{"use strict";var $x=qh();Wh();Yh.exports=$x});var Bo=m((PC,zh)=>{"use strict";var Lx=Qh();zh.exports=Lx});var Kh=m(()=>{"use strict"});var Oo=m((kC,Jh)=>{"use strict";var yi=X(),Mx=Er(),Cx=yr(),gs=function(a){return Mx.slice(0,a.length)===a};Jh.exports=function(){return gs("Bun/")?"BUN":gs("Cloudflare-Workers")?"CLOUDFLARE":gs("Deno/")?"DENO":gs("Node.js/")?"NODE":yi.Bun&&typeof Bun.version=="string"?"BUN":yi.Deno&&typeof Deno.version=="object"?"DENO":Cx(yi.process)==="process"?"NODE":yi.window&&yi.document?"BROWSER":"REST"}()});var Ss=m((RC,Xh)=>{"use strict";var Dx=Oo();Xh.exports=Dx==="NODE"});var ef=m(($C,Zh)=>{"use strict";var Bx=Yt();Zh.exports=function(a,e,t){return Bx.f(a,e,t)}});var af=m((LC,rf)=>{"use strict";var Ox=ot(),Vx=ef(),_x=ce(),Nx=Oe(),tf=_x("species");rf.exports=function(a){var e=Ox(a);Nx&&e&&!e[tf]&&Vx(e,tf,{configurable:!0,get:function(){return this}})}});var nf=m((MC,sf)=>{"use strict";var Fx=ni(),Ux=TypeError;sf.exports=function(a,e){if(Fx(e,a))return a;throw new Ux("Incorrect invocation")}});var _o=m((CC,of)=>{"use strict";var qx=me(),Hx=J(),Vo=li(),jx=qx(Function.toString);Hx(Vo.inspectSource)||(Vo.inspectSource=function(a){return jx(a)});of.exports=Vo.inspectSource});var hf=m((DC,pf)=>{"use strict";var Gx=me(),Wx=Pe(),uf=J(),Yx=bi(),Qx=ot(),zx=_o(),lf=function(){},cf=Qx("Reflect","construct"),No=/^\s*(?:class|function)\b/,Kx=Gx(No.exec),Jx=!No.test(lf),Ti=function(e){if(!uf(e))return!1;try{return cf(lf,[],e),!0}catch(t){return!1}},df=function(e){if(!uf(e))return!1;switch(Yx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jx||!!Kx(No,zx(e))}catch(t){return!0}};df.sham=!0;pf.exports=!cf||Wx(function(){var a;return Ti(Ti.call)||!Ti(Object)||!Ti(function(){a=!0})||a})?df:Ti});var mf=m((BC,ff)=>{"use strict";var Xx=hf(),Zx=oi(),eP=TypeError;ff.exports=function(a){if(Xx(a))return a;throw new eP(Zx(a)+" is not a constructor")}});var Fo=m((OC,gf)=>{"use strict";var bf=tt(),tP=mf(),rP=Tr(),iP=ce(),aP=iP("species");gf.exports=function(a,e){var t=bf(a).constructor,r;return t===void 0||rP(r=bf(t)[aP])?e:tP(r)}});var vf=m((VC,Sf)=>{"use strict";var sP=me();Sf.exports=sP([].slice)});var Tf=m((_C,yf)=>{"use strict";var nP=TypeError;yf.exports=function(a,e){if(a<e)throw new nP("Not enough arguments");return a}});var Uo=m((NC,If)=>{"use strict";var oP=Er();If.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(oP)});var Ko=m((FC,Lf)=>{"use strict";var we=X(),uP=po(),lP=fi(),Ef=J(),cP=ze(),$f=Pe(),xf=vo(),dP=vf(),Pf=Ka(),pP=Tf(),hP=Uo(),fP=Ss(),Yo=we.setImmediate,Qo=we.clearImmediate,mP=we.process,qo=we.Dispatch,bP=we.Function,Af=we.MessageChannel,gP=we.String,Ho=0,Ii={},wf="onreadystatechange",Ei,zt,jo,Go;$f(function(){Ei=we.location});var zo=function(a){if(cP(Ii,a)){var e=Ii[a];delete Ii[a],e()}},Wo=function(a){return function(){zo(a)}},kf=function(a){zo(a.data)},Rf=function(a){we.postMessage(gP(a),Ei.protocol+"//"+Ei.host)};(!Yo||!Qo)&&(Yo=function(e){pP(arguments.length,1);var t=Ef(e)?e:bP(e),r=dP(arguments,1);return Ii[++Ho]=function(){uP(t,void 0,r)},zt(Ho),Ho},Qo=function(e){delete Ii[e]},fP?zt=function(a){mP.nextTick(Wo(a))}:qo&&qo.now?zt=function(a){qo.now(Wo(a))}:Af&&!hP?(jo=new Af,Go=jo.port2,jo.port1.onmessage=kf,zt=lP(Go.postMessage,Go)):we.addEventListener&&Ef(we.postMessage)&&!we.importScripts&&Ei&&Ei.protocol!=="file:"&&!$f(Rf)?(zt=Rf,we.addEventListener("message",kf,!1)):wf in Pf("script")?zt=function(a){xf.appendChild(Pf("script"))[wf]=function(){xf.removeChild(this),zo(a)}}:zt=function(a){setTimeout(Wo(a),0)});Lf.exports={set:Yo,clear:Qo}});var Df=m((UC,Cf)=>{"use strict";var Mf=X(),SP=Oe(),vP=Object.getOwnPropertyDescriptor;Cf.exports=function(a){if(!SP)return Mf[a];var e=vP(Mf,a);return e&&e.value}});var Jo=m((qC,Of)=>{"use strict";var Bf=function(){this.head=null,this.tail=null};Bf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Of.exports=Bf});var _f=m((HC,Vf)=>{"use strict";var yP=Er();Vf.exports=/ipad|iphone|ipod/i.test(yP)&&typeof Pebble!="undefined"});var Ff=m((jC,Nf)=>{"use strict";var TP=Er();Nf.exports=/web0s(?!.*chrome)/i.test(TP)});var Yf=m((GC,Wf)=>{"use strict";var $r=X(),IP=Df(),Uf=fi(),Xo=Ko().set,EP=Jo(),xP=Uo(),PP=_f(),AP=Ff(),Zo=Ss(),qf=$r.MutationObserver||$r.WebKitMutationObserver,Hf=$r.document,jf=$r.process,vs=$r.Promise,ru=IP("queueMicrotask"),Rr,eu,tu,ys,Gf;ru||(xi=new EP,Pi=function(){var a,e;for(Zo&&(a=jf.domain)&&a.exit();e=xi.get();)try{e()}catch(t){throw xi.head&&Rr(),t}a&&a.enter()},!xP&&!Zo&&!AP&&qf&&Hf?(eu=!0,tu=Hf.createTextNode(""),new qf(Pi).observe(tu,{characterData:!0}),Rr=function(){tu.data=eu=!eu}):!PP&&vs&&vs.resolve?(ys=vs.resolve(void 0),ys.constructor=vs,Gf=Uf(ys.then,ys),Rr=function(){Gf(Pi)}):Zo?Rr=function(){jf.nextTick(Pi)}:(Xo=Uf(Xo,$r),Rr=function(){Xo(Pi)}),ru=function(a){xi.head||Rr(),xi.add(a)});var xi,Pi;Wf.exports=ru});var zf=m((WC,Qf)=>{"use strict";Qf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ts=m((YC,Kf)=>{"use strict";Kf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Kt=m((QC,Jf)=>{"use strict";var wP=X();Jf.exports=wP.Promise});var Lr=m((zC,tm)=>{"use strict";var kP=X(),Ai=Kt(),RP=J(),$P=fo(),LP=_o(),MP=ce(),Xf=Oo(),CP=Qe(),iu=Wn(),Zf=Ai&&Ai.prototype,DP=MP("species"),au=!1,em=RP(kP.PromiseRejectionEvent),BP=$P("Promise",function(){var a=LP(Ai),e=a!==String(Ai);if(!e&&iu===66||CP&&!(Zf.catch&&Zf.finally))return!0;if(!iu||iu<51||!/native code/.test(a)){var t=new Ai(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[DP]=r,au=t.then(function(){})instanceof r,!au)return!0}return!e&&(Xf==="BROWSER"||Xf==="DENO")&&!em});tm.exports={CONSTRUCTOR:BP,REJECTION_EVENT:em,SUBCLASSING:au}});var Mr=m((KC,im)=>{"use strict";var rm=ut(),OP=TypeError,VP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new OP("Bad Promise constructor");e=r,t=i}),this.resolve=rm(e),this.reject=rm(t)};im.exports.f=function(a){return new VP(a)}});var Im=m(()=>{"use strict";var _P=Ve(),NP=Qe(),Ps=Ss(),Pt=X(),Or=Ae(),am=kr(),sm=$o(),FP=gi(),UP=af(),qP=ut(),xs=J(),HP=Be(),jP=nf(),GP=Fo(),cm=Ko().set,lu=Yf(),WP=zf(),YP=Ts(),QP=Jo(),dm=co(),As=Kt(),cu=Lr(),pm=Mr(),ws="Promise",hm=cu.CONSTRUCTOR,zP=cu.REJECTION_EVENT,KP=cu.SUBCLASSING,su=dm.getterFor(ws),JP=dm.set,Cr=As&&As.prototype,Jt=As,Is=Cr,fm=Pt.TypeError,nu=Pt.document,du=Pt.process,ou=pm.f,XP=ou,ZP=!!(nu&&nu.createEvent&&Pt.dispatchEvent),mm="unhandledrejection",eA="rejectionhandled",nm=0,bm=1,tA=2,pu=1,gm=2,Es,om,rA,um,Sm=function(a){var e;return HP(a)&&xs(e=a.then)?e:!1},vm=function(a,e){var t=e.value,r=e.state===bm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===gm&&aA(e),e.rejection=pu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new fm("Promise-chain cycle")):(l=Sm(u))?Or(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},ym=function(a,e){a.notified||(a.notified=!0,lu(function(){for(var t=a.reactions,r;r=t.get();)vm(r,a);a.notified=!1,e&&!a.rejection&&iA(a)}))},Tm=function(a,e,t){var r,i;ZP?(r=nu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Pt.dispatchEvent(r)):r={promise:e,reason:t},!zP&&(i=Pt["on"+a])?i(r):a===mm&&WP("Unhandled promise rejection",t)},iA=function(a){Or(cm,Pt,function(){var e=a.facade,t=a.value,r=lm(a),i;if(r&&(i=YP(function(){Ps?du.emit("unhandledRejection",t,e):Tm(mm,e,t)}),a.rejection=Ps||lm(a)?gm:pu,i.error))throw i.value})},lm=function(a){return a.rejection!==pu&&!a.parent},aA=function(a){Or(cm,Pt,function(){var e=a.facade;Ps?du.emit("rejectionHandled",e):Tm(eA,e,a.value)})},Dr=function(a,e,t){return function(r){a(e,r,t)}},Br=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=tA,ym(a,!0))},uu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new fm("Promise can't be resolved itself");var r=Sm(e);r?lu(function(){var i={done:!1};try{Or(r,e,Dr(uu,i,a),Dr(Br,i,a))}catch(s){Br(i,s,a)}}):(a.value=e,a.state=bm,ym(a,!1))}catch(i){Br({done:!1},i,a)}}};if(hm&&(Jt=function(e){jP(this,Is),qP(e),Or(Es,this);var t=su(this);try{e(Dr(uu,t),Dr(Br,t))}catch(r){Br(t,r)}},Is=Jt.prototype,Es=function(e){JP(this,{type:ws,done:!1,notified:!1,parent:!1,reactions:new QP,rejection:!1,state:nm,value:void 0})},Es.prototype=am(Is,"then",function(e,t){var r=su(this),i=ou(GP(this,Jt));return r.parent=!0,i.ok=xs(e)?e:!0,i.fail=xs(t)&&t,i.domain=Ps?du.domain:void 0,r.state===nm?r.reactions.add(i):lu(function(){vm(i,r)}),i.promise}),om=function(){var a=new Es,e=su(a);this.promise=a,this.resolve=Dr(uu,e),this.reject=Dr(Br,e)},pm.f=ou=function(a){return a===Jt||a===rA?new om(a):XP(a)},!NP&&xs(As)&&Cr!==Object.prototype)){um=Cr.then,KP||am(Cr,"then",function(e,t){var r=this;return new Jt(function(i,s){Or(um,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Cr.constructor}catch(a){}sm&&sm(Cr,Is)}_P({global:!0,constructor:!0,wrap:!0,forced:hm},{Promise:Jt});FP(Jt,ws,!1,!0);UP(ws)});var wm=m((ZC,Am)=>{"use strict";var sA=ce(),xm=sA("iterator"),Pm=!1;try{Em=0,hu={next:function(){return{done:!!Em++}},return:function(){Pm=!0}},hu[xm]=function(){return this},Array.from(hu,function(){throw 2})}catch(a){}var Em,hu;Am.exports=function(a,e){try{if(!e&&!Pm)return!1}catch(i){return!1}var t=!1;try{var r={};r[xm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var fu=m((eD,km)=>{"use strict";var nA=Kt(),oA=wm(),uA=Lr().CONSTRUCTOR;km.exports=uA||!oA(function(a){nA.all(a).then(void 0,function(){})})});var Rm=m(()=>{"use strict";var lA=Ve(),cA=Ae(),dA=ut(),pA=Mr(),hA=Ts(),fA=ms(),mA=fu();lA({target:"Promise",stat:!0,forced:mA},{all:function(e){var t=this,r=pA.f(t),i=r.resolve,s=r.reject,n=hA(function(){var o=dA(t.resolve),u=[],l=0,c=1;fA(e,function(d){var h=l++,p=!1;c++,cA(o,t,d).then(function(f){p||(p=!0,u[h]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Lm=m(()=>{"use strict";var bA=Ve(),gA=Qe(),SA=Lr().CONSTRUCTOR,bu=Kt(),vA=ot(),yA=J(),TA=kr(),$m=bu&&bu.prototype;bA({target:"Promise",proto:!0,forced:SA,real:!0},{catch:function(a){return this.then(void 0,a)}});!gA&&yA(bu)&&(mu=vA("Promise").prototype.catch,$m.catch!==mu&&TA($m,"catch",mu,{unsafe:!0}));var mu});var Mm=m(()=>{"use strict";var IA=Ve(),EA=Ae(),xA=ut(),PA=Mr(),AA=Ts(),wA=ms(),kA=fu();IA({target:"Promise",stat:!0,forced:kA},{race:function(e){var t=this,r=PA.f(t),i=r.reject,s=AA(function(){var n=xA(t.resolve);wA(e,function(o){EA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Cm=m(()=>{"use strict";var RA=Ve(),$A=Mr(),LA=Lr().CONSTRUCTOR;RA({target:"Promise",stat:!0,forced:LA},{reject:function(e){var t=$A.f(this),r=t.reject;return r(e),t.promise}})});var gu=m((lD,Dm)=>{"use strict";var MA=tt(),CA=Be(),DA=Mr();Dm.exports=function(a,e){if(MA(a),CA(e)&&e.constructor===a)return e;var t=DA.f(a),r=t.resolve;return r(e),t.promise}});var Vm=m(()=>{"use strict";var BA=Ve(),OA=ot(),Bm=Qe(),VA=Kt(),Om=Lr().CONSTRUCTOR,_A=gu(),NA=OA("Promise"),FA=Bm&&!Om;BA({target:"Promise",stat:!0,forced:Bm||Om},{resolve:function(e){return _A(FA&&this===NA?VA:this,e)}})});var _m=m(()=>{"use strict";Im();Rm();Lm();Mm();Cm();Vm()});var qm=m(()=>{"use strict";var UA=Ve(),qA=Qe(),ks=Kt(),HA=Pe(),Fm=ot(),Um=J(),jA=Fo(),Nm=gu(),GA=kr(),vu=ks&&ks.prototype,WA=!!ks&&HA(function(){vu.finally.call({then:function(){}},function(){})});UA({target:"Promise",proto:!0,real:!0,forced:WA},{finally:function(a){var e=jA(this,Fm("Promise")),t=Um(a);return this.then(t?function(r){return Nm(e,a()).then(function(){return r})}:a,t?function(r){return Nm(e,a()).then(function(){throw r})}:a)}});!qA&&Um(ks)&&(Su=Fm("Promise").prototype.finally,vu.finally!==Su&&GA(vu,"finally",Su,{unsafe:!0}));var Su});var Rs=m((bD,Hm)=>{"use strict";var YA=ot();Hm.exports=YA});var Gm=m((gD,jm)=>{"use strict";Kh();_m();qm();var QA=Rs();jm.exports=QA("Promise","finally")});var Ym=m((SD,Wm)=>{"use strict";var zA=Gm();Wm.exports=zA});var $s=m((vD,Qm)=>{"use strict";var KA=Ym();Qm.exports=KA});var vb=m(()=>{"use strict";var Pw=Ve(),Aw=ci(),ww=ns(),kw=ss(),Rw=Vn();Pw({target:"Array",proto:!0},{at:function(e){var t=Aw(this),r=ww(t),i=kw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Rw("at")});var Tb=m((k0,yb)=>{"use strict";vb();var $w=Rs();yb.exports=$w("Array","at")});var Eb=m((R0,Ib)=>{"use strict";var Lw=Tb();Ib.exports=Lw});var Nr=m(($0,xb)=>{"use strict";var Mw=Eb();xb.exports=Mw});var $g=m(()=>{"use strict"});var Lg=m(()=>{"use strict"});var Cg=m((q_,Mg)=>{"use strict";var Fk=Be(),Uk=yr(),qk=ce(),Hk=qk("match");Mg.exports=function(a){var e;return Fk(a)&&((e=a[Hk])!==void 0?!!e:Uk(a)==="RegExp")}});var Bg=m((H_,Dg)=>{"use strict";var jk=bi(),Gk=String;Dg.exports=function(a){if(jk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Gk(a)}});var Vg=m((j_,Og)=>{"use strict";var Wk=tt();Og.exports=function(){var a=Wk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Fg=m((G_,Ng)=>{"use strict";var Yk=Ae(),Qk=ze(),zk=ni(),Kk=Vg(),_g=RegExp.prototype;Ng.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in _g)&&!Qk(a,"flags")&&zk(_g,a)?Yk(Kk,a):e}});var qg=m((W_,Ug)=>{"use strict";var zu=me(),Jk=ci(),Xk=Math.floor,Yu=zu("".charAt),Zk=zu("".replace),Qu=zu("".slice),eR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,tR=/\$([$&'`]|\d{1,2})/g;Ug.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=tR;return i!==void 0&&(i=Jk(i),u=eR),Zk(s,u,function(l,c){var d;switch(Yu(c,0)){case"$":return"$";case"&":return a;case"`":return Qu(e,0,t);case"'":return Qu(e,n);case"<":d=i[Qu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=Xk(h/10);return p===0?l:p<=o?r[p-1]===void 0?Yu(c,1):r[p-1]+Yu(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var Gg=m(()=>{"use strict";var rR=Ve(),iR=Ae(),Ju=me(),Hg=ai(),aR=J(),sR=Tr(),nR=Cg(),Gr=Bg(),oR=ui(),uR=Fg(),lR=qg(),cR=ce(),dR=Qe(),pR=cR("replace"),hR=TypeError,Ku=Ju("".indexOf),fR=Ju("".replace),jg=Ju("".slice),mR=Math.max;rR({target:"String",proto:!0},{replaceAll:function(e,t){var r=Hg(this),i,s,n,o,u,l,c,d,h,p,f=0,b="";if(!sR(e)){if(i=nR(e),i&&(s=Gr(Hg(uR(e))),!~Ku(s,"g")))throw new hR("`.replaceAll` does not allow non-global regexes");if(n=oR(e,pR),n)return iR(n,e,r,t);if(dR&&i)return fR(Gr(r),e,t)}for(o=Gr(r),u=Gr(e),l=aR(t),l||(t=Gr(t)),c=u.length,d=mR(1,c),h=Ku(o,u);h!==-1;)p=l?Gr(t(u,h,o)):lR(u,o,h,[],void 0,t),b+=jg(o,f,h)+p,f=h+c,h=h+d>o.length?-1:Ku(o,u,h+d);return f<o.length&&(b+=jg(o,f)),b}})});var Yg=m((z_,Wg)=>{"use strict";$g();Lg();Gg();var bR=Rs();Wg.exports=bR("String","replaceAll")});var zg=m((K_,Qg)=>{"use strict";var gR=Yg();Qg.exports=gR});var Jg=m((J_,Kg)=>{"use strict";var SR=zg();Kg.exports=SR});var hc="2.0.117-dev.85ef0d1b.0";var fe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(fe||{}),xt=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(xt||{});var Ya=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ya||{}),Ln=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ln||{});var Mn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Mn||{});import{assertNever as vc,assertNonNullable as Ov,isNonNullable as Qa,ValueSubject as Cn,Subject as Vv,Subscription as _v,merge as Nv,observableFrom as Fv,fromEvent as mc,map as bc,tap as gc,filterChanged as Uv,isNullable as Dn,ErrorCategory as Sc}from"@vkontakte/videoplayer-shared";var fc=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var za=class{constructor(e){this.connection$=new Cn(void 0);this.castState$=new Cn("NOT_AVAILABLE");this.errorEvent$=new Vv;this.realCastState$=new Cn("NOT_AVAILABLE");this.subscription=new _v;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Qa((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||fc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Sc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Qa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Dn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Dn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(mc(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return vc(i.sessionState)}})).add(Nv(mc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(gc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),bc(i=>i.castState)),Fv([r.getCastState()])).pipe(Uv(),bc(qv),gc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Qa(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Ov(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Dn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Qa(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Sc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},qv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return vc(a)}};var XS=We(Bo(),1);var ab=We($s(),1);import{assertNever as zm}from"@vkontakte/videoplayer-shared";var oe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:zm(t)}return a},yu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:zm(e)}};var P=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as JA,Subject as Ls,merge as Km}from"@vkontakte/videoplayer-shared";var D=class{constructor(e){this.transitionStarted$=new Ls;this.transitionEnded$=new Ls;this.transitionUpdated$=new Ls;this.forceChanged$=new Ls;this.stateChangeStarted$=Km(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Km(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||JA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as XA}from"@vkontakte/videoplayer-shared";var Jm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return XA(a)}};import{assertNever as Vr,assertNonNullable as Xt,debounce as Xm,ErrorCategory as Zm,fromEvent as Zt,isNonNullable as eb,map as tb,merge as rb,observableFrom as ZA,Subject as ew,Subscription as Tu,timeout as tw,getHighestQuality as rw}from"@vkontakte/videoplayer-shared";var iw=5,aw=5,sw=500,ib=7e3,wi=class{constructor(e){this.subscription=new Tu;this.loadMediaTimeoutSubscription=new Tu;this.videoState=new D("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Vr(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:Vr(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:Vr(e)}break}default:Vr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Jm(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 Tu;this.subscription.add(e),this.subscription.add(rb(this.videoState.stateChangeStarted$.pipe(tb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(tb(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new ew;e.add(i.pipe(Xm(sw)).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)>iw)&&i.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),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<aw&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Vr(n)}}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=rb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ZA(["init"])).pipe(Xm(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];Xt(c);let d=rw(Object.keys(c));Xt(d);let h=c[d];Xt(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Xt(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Xt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Xt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Xt(c),r=oe(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Zm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Vr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return eb(o)&&(n.metadata.title=o),eb(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(tw(ib).subscribe(()=>s(`timeout(${ib})`)))});(0,ab.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Zm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as nb}from"@vkontakte/videoplayer-shared";import{clearVideoElement as nw}from"@vkontakte/videoplayer-shared";var sb=a=>{try{a.pause(),a.playbackRate=0,nw(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as ow,Subscription as uw}from"@vkontakte/videoplayer-shared";var Iu=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)}},Eu=window.WeakMap?new WeakMap:new Iu,xu=window.WeakMap?new WeakMap:new Map,lw=(a,e=20)=>{let t=0;return ow(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},be=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?nb(t):(t=document.createElement("video"),a.appendChild(t)),Eu.set(t,r);let i=new uw;return i.add(lw(t,e)),xu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ge=a=>{let e=xu.get(a);e==null||e.unsubscribe(),xu.delete(a);let t=Eu.get(a);Eu.delete(a),t?nb(a):sb(a)};import{assertNonNullable as ki,isNonNullable as it,isNullable as pw,fromEvent as _r,merge as ob,observableFrom as ub,filterChanged as lb,map as Ri,Subject as cb,Subscription as hw,ValueSubject as fw,ErrorCategory as mw}from"@vkontakte/videoplayer-shared";import{isNonNullable as Pu,isNullable as cw,Subscription as dw}from"@vkontakte/videoplayer-shared";var Ms=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=cw(i),l=new dw;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},rt=(a,e,t)=>Ms(e,()=>a.loop,r=>{Pu(r)&&(a.loop=r)},{onError:t}),Se=(a,e,t,r)=>Ms(e,()=>({muted:a.muted,volume:a.volume}),i=>{Pu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),_e=(a,e,t,r)=>Ms(e,()=>a.playbackRate,i=>{Pu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),At=Ms;var bw=a=>["__",a.language,a.label].join("|"),gw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Au=class a{constructor(){this.available$=new cb;this.current$=new fw(void 0);this.error$=new cb;this.subscription=new hw;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:mw.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(At(t.internalTextTracks,()=>Object.values(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(Ri(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(At(t.externalTextTracks,()=>Object.values(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(Ri(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(At(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(At(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ki(this.video);let{textTracks:e}=this.video;this.subscription.add(_r(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(ob(_r(e,"addtrack"),_r(e,"removetrack"),ub(["init"])).pipe(Ri(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),lb((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(ob(_r(e,"change"),ub(["init"])).pipe(Ri(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ri(r=>r&&this.htmlTextTrackToITextTrack(r).id),lb()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(_r(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(_r(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;it(t.align)&&(i.align=t.align),it(t.position)&&(i.position=t.position),it(t.size)&&(i.size=t.size),it(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){ki(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c;let{language:t,label:r}=e,i=e.id?e.id:bw(e),s=this.externalTracks.has(i),n=(s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)||i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(l=this.externalTracks.get(i))==null?void 0:l.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(c=this.internalTracks.get(i))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){ki(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(pw(e)||!gw(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){ki(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){ki(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ne=Au;var dt=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 db=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},wu=a=>{let e=db(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},pb=a=>{let e=db(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Fe,map as wt,merge as fb,filterChanged as vw,isNonNullable as mb,Subject as yw,filter as bb,mapTo as gb,combine as Tw,once as Iw,ErrorCategory as Ew,ValueSubject as Sb,clientChecker as xw}from"@vkontakte/videoplayer-shared";var Sw=3,hb=(a,e,t=Sw)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var ve=a=>{let e=S=>Fe(a,S).pipe(gb(void 0)),r=fb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>Fe(a,S))).pipe(wt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),vw()),i=fb(Fe(a,"progress"),Fe(a,"timeupdate")).pipe(wt(()=>hb(a.buffered,a.currentTime))),s=xw.isSafari?Tw({play:e("play").pipe(Iw()),playing:e("playing")}).pipe(gb(void 0)):e("playing"),n=Fe(a,"volumechange").pipe(wt(()=>({muted:a.muted,volume:a.volume}))),o=Fe(a,"ratechange").pipe(wt(()=>a.playbackRate)),u=Fe(a,"error").pipe(bb(()=>!!(a.error||a.played.length)),wt(()=>{var T;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:Ew.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(T=a.error)!=null?T:void 0}})),l=Fe(a,"timeupdate").pipe(wt(()=>a.currentTime)),c=new yw,d=.3,h;l.subscribe(S=>{a.loop&&mb(h)&&mb(S)&&h>=a.duration-d&&S<=d&&c.next(h),h=S});let p=e("pause").pipe(bb(()=>!a.error&&h!==a.duration)),f=Fe(a,"enterpictureinpicture"),b=Fe(a,"leavepictureinpicture"),g=new Sb(pb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Sb(wu(a));return Fe(a,"fullscreenchange").pipe(wt(()=>wu(a))).subscribe(v),{playing$:s,pause$:p,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Fe(a,"durationchange").pipe(wt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as kt}from"@vkontakte/videoplayer-shared";var Rt=a=>{switch(a){case"mobile":return kt.Q_144P;case"lowest":return kt.Q_240P;case"low":return kt.Q_360P;case"sd":case"medium":return kt.Q_480P;case"hd":case"high":return kt.Q_720P;case"fullhd":case"full":return kt.Q_1080P;case"quadhd":case"quad":return kt.Q_1440P;case"ultrahd":case"ultra":return kt.Q_2160P}};var er=We(Nr(),1);import{isNonNullable as te,isNullable as Ru,now as Mb,isHigher as $u,isHigherOrEqual as kb,isInvariantQuality as Rb,isLower as $b,isLowerOrEqual as Lu,videoSizeToQuality as Cw,assertNotEmptyArray as Cb,assertNonNullable as Dw}from"@vkontakte/videoplayer-shared";var ku=!1,pt={},Pb=a=>{ku=a},Ab=()=>{pt={}},wb=a=>{a(pt)},$i=(a,e)=>{var t;ku&&(pt.meta=(t=pt.meta)!=null?t:{},pt.meta[a]=e)},de=class{constructor(e){this.name=e}next(e){var r,i;if(!ku)return;pt.series=(r=pt.series)!=null?r:{};let t=(i=pt.series[this.name])!=null?i:[];t.push([Date.now(),e]),pt.series[this.name]=t}};var Bw=new de("best_bitrate"),Db=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Mu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Li=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Mb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Bb='Assertion "ABR Tracks is empty array" failed',Cs=(a,e,t,r)=>{var u;let i=[...e].sort(Mu(1)),s=[...t].sort(Mu(1)),n=s.filter(l=>te(l.bitrate)&&te(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,er.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,er.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,er.default)(n,-1):(0,er.default)(s,0)},Lb=a=>"quality"in a,Ob=(a,e,t,r)=>{var n;let i=te((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&te(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Mb()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Lb(o)?"video":"audio",l=Lb(o)?o.quality:o.bitrate;return e({message:`
6
+ var kv=Object.create;var kn=Object.defineProperty,Rv=Object.defineProperties,$v=Object.getOwnPropertyDescriptor,Lv=Object.getOwnPropertyDescriptors,Mv=Object.getOwnPropertyNames,Wa=Object.getOwnPropertySymbols,Cv=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty,dc=Object.prototype.propertyIsEnumerable;var Dv=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var et=Math.pow,cc=(a,e,t)=>e in a?kn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,A=(a,e)=>{for(var t in e||(e={}))Rn.call(e,t)&&cc(a,t,e[t]);if(Wa)for(var t of Wa(e))dc.call(e,t)&&cc(a,t,e[t]);return a},D=(a,e)=>Rv(a,Lv(e));var pc=(a,e)=>{var t={};for(var r in a)Rn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Wa)for(var r of Wa(a))e.indexOf(r)<0&&dc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Bv=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Mv(e))!Rn.call(a,i)&&i!==t&&kn(a,i,{get:()=>e[i],enumerable:!(r=$v(e,i))||r.enumerable});return a};var Ge=(a,e,t)=>(t=a!=null?kv(Cv(a)):{},Bv(e||!a||!a.__esModule?kn(t,"default",{value:a,enumerable:!0}):t,a));var w=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),$n=function(a,e){this[0]=a,this[1]=e},Z=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof $n,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?r(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>r("throw",p,u,l))}catch(p){l(p)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[Dv("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Pe=m((VL,yc)=>{"use strict";yc.exports=function(a){try{return!!a()}catch(e){return!0}}});var ii=m((_L,Tc)=>{"use strict";var Hv=Pe();Tc.exports=!Hv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var me=m((NL,xc)=>{"use strict";var Ic=ii(),Ec=Function.prototype,Bn=Ec.call,jv=Ic&&Ec.bind.bind(Bn,Bn);xc.exports=Ic?jv:function(a){return function(){return Bn.apply(a,arguments)}}});var yr=m((FL,Ac)=>{"use strict";var Pc=me(),Gv=Pc({}.toString),Wv=Pc("".slice);Ac.exports=function(a){return Wv(Gv(a),8,-1)}});var kc=m((UL,wc)=>{"use strict";var Qv=me(),Yv=Pe(),zv=yr(),On=Object,Kv=Qv("".split);wc.exports=Yv(function(){return!On("z").propertyIsEnumerable(0)})?function(a){return zv(a)==="String"?Kv(a,""):On(a)}:On});var Tr=m((qL,Rc)=>{"use strict";Rc.exports=function(a){return a==null}});var ai=m((HL,$c)=>{"use strict";var Jv=Tr(),Xv=TypeError;$c.exports=function(a){if(Jv(a))throw new Xv("Can't call method on "+a);return a}});var Ir=m((jL,Lc)=>{"use strict";var Zv=kc(),ey=ai();Lc.exports=function(a){return Zv(ey(a))}});var Vn=m((GL,Mc)=>{"use strict";Mc.exports=function(){}});var Gt=m((WL,Cc)=>{"use strict";Cc.exports={}});var X=m((_n,Dc)=>{"use strict";var si=function(a){return a&&a.Math===Math&&a};Dc.exports=si(typeof globalThis=="object"&&globalThis)||si(typeof window=="object"&&window)||si(typeof self=="object"&&self)||si(typeof global=="object"&&global)||si(typeof _n=="object"&&_n)||function(){return this}()||Function("return this")()});var J=m((QL,Bc)=>{"use strict";var Nn=typeof document=="object"&&document.all;Bc.exports=typeof Nn=="undefined"&&Nn!==void 0?function(a){return typeof a=="function"||a===Nn}:function(a){return typeof a=="function"}});var _c=m((YL,Vc)=>{"use strict";var ty=X(),ry=J(),Oc=ty.WeakMap;Vc.exports=ry(Oc)&&/native code/.test(String(Oc))});var De=m((zL,Nc)=>{"use strict";var iy=J();Nc.exports=function(a){return typeof a=="object"?a!==null:iy(a)}});var Be=m((KL,Fc)=>{"use strict";var ay=Pe();Fc.exports=!ay(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ka=m((JL,qc)=>{"use strict";var sy=X(),Uc=De(),Fn=sy.document,ny=Uc(Fn)&&Uc(Fn.createElement);qc.exports=function(a){return ny?Fn.createElement(a):{}}});var Un=m((XL,Hc)=>{"use strict";var oy=Be(),uy=Pe(),ly=Ka();Hc.exports=!oy&&!uy(function(){return Object.defineProperty(ly("div"),"a",{get:function(){return 7}}).a!==7})});var qn=m((ZL,jc)=>{"use strict";var cy=Be(),dy=Pe();jc.exports=cy&&dy(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var tt=m((eM,Gc)=>{"use strict";var py=De(),hy=String,fy=TypeError;Gc.exports=function(a){if(py(a))return a;throw new fy(hy(a)+" is not an object")}});var Ae=m((tM,Wc)=>{"use strict";var my=ii(),Ja=Function.prototype.call;Wc.exports=my?Ja.bind(Ja):function(){return Ja.apply(Ja,arguments)}});var Xa=m((rM,Qc)=>{"use strict";Qc.exports={}});var ot=m((iM,zc)=>{"use strict";var Hn=Xa(),jn=X(),by=J(),Yc=function(a){return by(a)?a:void 0};zc.exports=function(a,e){return arguments.length<2?Yc(Hn[a])||Yc(jn[a]):Hn[a]&&Hn[a][e]||jn[a]&&jn[a][e]}});var ni=m((aM,Kc)=>{"use strict";var gy=me();Kc.exports=gy({}.isPrototypeOf)});var Er=m((sM,Zc)=>{"use strict";var Sy=X(),Jc=Sy.navigator,Xc=Jc&&Jc.userAgent;Zc.exports=Xc?String(Xc):""});var Wn=m((nM,sd)=>{"use strict";var ad=X(),Gn=Er(),ed=ad.process,td=ad.Deno,rd=ed&&ed.versions||td&&td.version,id=rd&&rd.v8,We,Za;id&&(We=id.split("."),Za=We[0]>0&&We[0]<4?1:+(We[0]+We[1]));!Za&&Gn&&(We=Gn.match(/Edge\/(\d+)/),(!We||We[1]>=74)&&(We=Gn.match(/Chrome\/(\d+)/),We&&(Za=+We[1])));sd.exports=Za});var Qn=m((oM,od)=>{"use strict";var nd=Wn(),vy=Pe(),yy=X(),Ty=yy.String;od.exports=!!Object.getOwnPropertySymbols&&!vy(function(){var a=Symbol("symbol detection");return!Ty(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&nd&&nd<41})});var Yn=m((uM,ud)=>{"use strict";var Iy=Qn();ud.exports=Iy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var zn=m((lM,ld)=>{"use strict";var Ey=ot(),xy=J(),Py=ni(),Ay=Yn(),wy=Object;ld.exports=Ay?function(a){return typeof a=="symbol"}:function(a){var e=Ey("Symbol");return xy(e)&&Py(e.prototype,wy(a))}});var oi=m((cM,cd)=>{"use strict";var ky=String;cd.exports=function(a){try{return ky(a)}catch(e){return"Object"}}});var ut=m((dM,dd)=>{"use strict";var Ry=J(),$y=oi(),Ly=TypeError;dd.exports=function(a){if(Ry(a))return a;throw new Ly($y(a)+" is not a function")}});var ui=m((pM,pd)=>{"use strict";var My=ut(),Cy=Tr();pd.exports=function(a,e){var t=a[e];return Cy(t)?void 0:My(t)}});var fd=m((hM,hd)=>{"use strict";var Kn=Ae(),Jn=J(),Xn=De(),Dy=TypeError;hd.exports=function(a,e){var t,r;if(e==="string"&&Jn(t=a.toString)&&!Xn(r=Kn(t,a))||Jn(t=a.valueOf)&&!Xn(r=Kn(t,a))||e!=="string"&&Jn(t=a.toString)&&!Xn(r=Kn(t,a)))return r;throw new Dy("Can't convert object to primitive value")}});var Qe=m((fM,md)=>{"use strict";md.exports=!0});var Sd=m((mM,gd)=>{"use strict";var bd=X(),By=Object.defineProperty;gd.exports=function(a,e){try{By(bd,a,{value:e,configurable:!0,writable:!0})}catch(t){bd[a]=e}return e}});var li=m((bM,Td)=>{"use strict";var Oy=Qe(),Vy=X(),_y=Sd(),vd="__core-js_shared__",yd=Td.exports=Vy[vd]||_y(vd,{});(yd.versions||(yd.versions=[])).push({version:"3.38.0",mode:Oy?"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 Zn=m((gM,Ed)=>{"use strict";var Id=li();Ed.exports=function(a,e){return Id[a]||(Id[a]=e||{})}});var ci=m((SM,xd)=>{"use strict";var Ny=ai(),Fy=Object;xd.exports=function(a){return Fy(Ny(a))}});var Ye=m((vM,Pd)=>{"use strict";var Uy=me(),qy=ci(),Hy=Uy({}.hasOwnProperty);Pd.exports=Object.hasOwn||function(e,t){return Hy(qy(e),t)}});var eo=m((yM,Ad)=>{"use strict";var jy=me(),Gy=0,Wy=Math.random(),Qy=jy(1 .toString);Ad.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Qy(++Gy+Wy,36)}});var ce=m((TM,kd)=>{"use strict";var Yy=X(),zy=Zn(),wd=Ye(),Ky=eo(),Jy=Qn(),Xy=Yn(),xr=Yy.Symbol,to=zy("wks"),Zy=Xy?xr.for||xr:xr&&xr.withoutSetter||Ky;kd.exports=function(a){return wd(to,a)||(to[a]=Jy&&wd(xr,a)?xr[a]:Zy("Symbol."+a)),to[a]}});var Md=m((IM,Ld)=>{"use strict";var eT=Ae(),Rd=De(),$d=zn(),tT=ui(),rT=fd(),iT=ce(),aT=TypeError,sT=iT("toPrimitive");Ld.exports=function(a,e){if(!Rd(a)||$d(a))return a;var t=tT(a,sT),r;if(t){if(e===void 0&&(e="default"),r=eT(t,a,e),!Rd(r)||$d(r))return r;throw new aT("Can't convert object to primitive value")}return e===void 0&&(e="number"),rT(a,e)}});var ro=m((EM,Cd)=>{"use strict";var nT=Md(),oT=zn();Cd.exports=function(a){var e=nT(a,"string");return oT(e)?e:e+""}});var Wt=m(Bd=>{"use strict";var uT=Be(),lT=Un(),cT=qn(),es=tt(),Dd=ro(),dT=TypeError,io=Object.defineProperty,pT=Object.getOwnPropertyDescriptor,ao="enumerable",so="configurable",no="writable";Bd.f=uT?cT?function(e,t,r){if(es(e),t=Dd(t),es(r),typeof e=="function"&&t==="prototype"&&"value"in r&&no in r&&!r[no]){var i=pT(e,t);i&&i[no]&&(e[t]=r.value,r={configurable:so in r?r[so]:i[so],enumerable:ao in r?r[ao]:i[ao],writable:!1})}return io(e,t,r)}:io:function(e,t,r){if(es(e),t=Dd(t),es(r),lT)try{return io(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new dT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var di=m((PM,Od)=>{"use strict";Od.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Pr=m((AM,Vd)=>{"use strict";var hT=Be(),fT=Wt(),mT=di();Vd.exports=hT?function(a,e,t){return fT.f(a,e,mT(1,t))}:function(a,e,t){return a[e]=t,a}});var ts=m((wM,Nd)=>{"use strict";var bT=Zn(),gT=eo(),_d=bT("keys");Nd.exports=function(a){return _d[a]||(_d[a]=gT(a))}});var rs=m((kM,Fd)=>{"use strict";Fd.exports={}});var co=m((RM,Hd)=>{"use strict";var ST=_c(),qd=X(),vT=De(),yT=Pr(),oo=Ye(),uo=li(),TT=ts(),IT=rs(),Ud="Object already initialized",lo=qd.TypeError,ET=qd.WeakMap,is,pi,as,xT=function(a){return as(a)?pi(a):is(a,{})},PT=function(a){return function(e){var t;if(!vT(e)||(t=pi(e)).type!==a)throw new lo("Incompatible receiver, "+a+" required");return t}};ST||uo.state?(ze=uo.state||(uo.state=new ET),ze.get=ze.get,ze.has=ze.has,ze.set=ze.set,is=function(a,e){if(ze.has(a))throw new lo(Ud);return e.facade=a,ze.set(a,e),e},pi=function(a){return ze.get(a)||{}},as=function(a){return ze.has(a)}):(Qt=TT("state"),IT[Qt]=!0,is=function(a,e){if(oo(a,Qt))throw new lo(Ud);return e.facade=a,yT(a,Qt,e),e},pi=function(a){return oo(a,Qt)?a[Qt]:{}},as=function(a){return oo(a,Qt)});var ze,Qt;Hd.exports={set:is,get:pi,has:as,enforce:xT,getterFor:PT}});var po=m(($M,Qd)=>{"use strict";var AT=ii(),Wd=Function.prototype,jd=Wd.apply,Gd=Wd.call;Qd.exports=typeof Reflect=="object"&&Reflect.apply||(AT?Gd.bind(jd):function(){return Gd.apply(jd,arguments)})});var ho=m((LM,Yd)=>{"use strict";var wT=yr(),kT=me();Yd.exports=function(a){if(wT(a)==="Function")return kT(a)}});var Xd=m(Jd=>{"use strict";var zd={}.propertyIsEnumerable,Kd=Object.getOwnPropertyDescriptor,RT=Kd&&!zd.call({1:2},1);Jd.f=RT?function(e){var t=Kd(this,e);return!!t&&t.enumerable}:zd});var tp=m(ep=>{"use strict";var $T=Be(),LT=Ae(),MT=Xd(),CT=di(),DT=Ir(),BT=ro(),OT=Ye(),VT=Un(),Zd=Object.getOwnPropertyDescriptor;ep.f=$T?Zd:function(e,t){if(e=DT(e),t=BT(t),VT)try{return Zd(e,t)}catch(r){}if(OT(e,t))return CT(!LT(MT.f,e,t),e[t])}});var fo=m((DM,rp)=>{"use strict";var _T=Pe(),NT=J(),FT=/#|\.prototype\./,hi=function(a,e){var t=qT[UT(a)];return t===jT?!0:t===HT?!1:NT(e)?_T(e):!!e},UT=hi.normalize=function(a){return String(a).replace(FT,".").toLowerCase()},qT=hi.data={},HT=hi.NATIVE="N",jT=hi.POLYFILL="P";rp.exports=hi});var fi=m((BM,ap)=>{"use strict";var ip=ho(),GT=ut(),WT=ii(),QT=ip(ip.bind);ap.exports=function(a,e){return GT(a),e===void 0?a:WT?QT(a,e):function(){return a.apply(e,arguments)}}});var Oe=m((OM,np)=>{"use strict";var mi=X(),YT=po(),zT=ho(),KT=J(),JT=tp().f,XT=fo(),Ar=Xa(),ZT=fi(),wr=Pr(),sp=Ye();li();var eI=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return YT(a,this,arguments)};return e.prototype=a.prototype,e};np.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?mi:i?mi[t]:mi[t]&&mi[t].prototype,o=r?Ar:Ar[t]||wr(Ar,t,{})[t],u=o.prototype,l,c,d,h,p,f,b,g,T;for(h in e)l=XT(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&sp(n,h),f=o[h],c&&(a.dontCallGetSet?(T=JT(n,h),b=T&&T.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?g=ZT(p,mi):a.wrap&&c?g=eI(p):s&&KT(p)?g=zT(p):g=p,(a.sham||p&&p.sham||f&&f.sham)&&wr(g,"sham",!0),wr(o,h,g),s&&(d=t+"Prototype",sp(Ar,d)||wr(Ar,d,{}),wr(Ar[d],h,p),a.real&&u&&(l||!u[h])&&wr(u,h,p)))}});var lp=m((VM,up)=>{"use strict";var mo=Be(),tI=Ye(),op=Function.prototype,rI=mo&&Object.getOwnPropertyDescriptor,bo=tI(op,"name"),iI=bo&&function(){}.name==="something",aI=bo&&(!mo||mo&&rI(op,"name").configurable);up.exports={EXISTS:bo,PROPER:iI,CONFIGURABLE:aI}});var dp=m((_M,cp)=>{"use strict";var sI=Math.ceil,nI=Math.floor;cp.exports=Math.trunc||function(e){var t=+e;return(t>0?nI:sI)(t)}});var ss=m((NM,pp)=>{"use strict";var oI=dp();pp.exports=function(a){var e=+a;return e!==e||e===0?0:oI(e)}});var fp=m((FM,hp)=>{"use strict";var uI=ss(),lI=Math.max,cI=Math.min;hp.exports=function(a,e){var t=uI(a);return t<0?lI(t+e,0):cI(t,e)}});var bp=m((UM,mp)=>{"use strict";var dI=ss(),pI=Math.min;mp.exports=function(a){var e=dI(a);return e>0?pI(e,9007199254740991):0}});var ns=m((qM,gp)=>{"use strict";var hI=bp();gp.exports=function(a){return hI(a.length)}});var yp=m((HM,vp)=>{"use strict";var fI=Ir(),mI=fp(),bI=ns(),Sp=function(a){return function(e,t,r){var i=fI(e),s=bI(i);if(s===0)return!a&&-1;var n=mI(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};vp.exports={includes:Sp(!0),indexOf:Sp(!1)}});var Ep=m((jM,Ip)=>{"use strict";var gI=me(),go=Ye(),SI=Ir(),vI=yp().indexOf,yI=rs(),Tp=gI([].push);Ip.exports=function(a,e){var t=SI(a),r=0,i=[],s;for(s in t)!go(yI,s)&&go(t,s)&&Tp(i,s);for(;e.length>r;)go(t,s=e[r++])&&(~vI(i,s)||Tp(i,s));return i}});var So=m((GM,xp)=>{"use strict";xp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ap=m((WM,Pp)=>{"use strict";var TI=Ep(),II=So();Pp.exports=Object.keys||function(e){return TI(e,II)}});var kp=m(wp=>{"use strict";var EI=Be(),xI=qn(),PI=Wt(),AI=tt(),wI=Ir(),kI=Ap();wp.f=EI&&!xI?Object.defineProperties:function(e,t){AI(e);for(var r=wI(t),i=kI(t),s=i.length,n=0,o;s>n;)PI.f(e,o=i[n++],r[o]);return e}});var vo=m((YM,Rp)=>{"use strict";var RI=ot();Rp.exports=RI("document","documentElement")});var Eo=m((zM,Op)=>{"use strict";var $I=tt(),LI=kp(),$p=So(),MI=rs(),CI=vo(),DI=Ka(),BI=ts(),Lp=">",Mp="<",To="prototype",Io="script",Dp=BI("IE_PROTO"),yo=function(){},Bp=function(a){return Mp+Io+Lp+a+Mp+"/"+Io+Lp},Cp=function(a){a.write(Bp("")),a.close();var e=a.parentWindow.Object;return a=null,e},OI=function(){var a=DI("iframe"),e="java"+Io+":",t;return a.style.display="none",CI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Bp("document.F=Object")),t.close(),t.F},os,us=function(){try{os=new ActiveXObject("htmlfile")}catch(e){}us=typeof document!="undefined"?document.domain&&os?Cp(os):OI():Cp(os);for(var a=$p.length;a--;)delete us[To][$p[a]];return us()};MI[Dp]=!0;Op.exports=Object.create||function(e,t){var r;return e!==null?(yo[To]=$I(e),r=new yo,yo[To]=null,r[Dp]=e):r=us(),t===void 0?r:LI.f(r,t)}});var _p=m((KM,Vp)=>{"use strict";var VI=Pe();Vp.exports=!VI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Po=m((JM,Fp)=>{"use strict";var _I=Ye(),NI=J(),FI=ci(),UI=ts(),qI=_p(),Np=UI("IE_PROTO"),xo=Object,HI=xo.prototype;Fp.exports=qI?xo.getPrototypeOf:function(a){var e=FI(a);if(_I(e,Np))return e[Np];var t=e.constructor;return NI(t)&&e instanceof t?t.prototype:e instanceof xo?HI:null}});var kr=m((XM,Up)=>{"use strict";var jI=Pr();Up.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:jI(a,e,t),a}});var Ro=m((ZM,jp)=>{"use strict";var GI=Pe(),WI=J(),QI=De(),YI=Eo(),qp=Po(),zI=kr(),KI=ce(),JI=Qe(),ko=KI("iterator"),Hp=!1,lt,Ao,wo;[].keys&&(wo=[].keys(),"next"in wo?(Ao=qp(qp(wo)),Ao!==Object.prototype&&(lt=Ao)):Hp=!0);var XI=!QI(lt)||GI(function(){var a={};return lt[ko].call(a)!==a});XI?lt={}:JI&&(lt=YI(lt));WI(lt[ko])||zI(lt,ko,function(){return this});jp.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Hp}});var ls=m((eC,Wp)=>{"use strict";var ZI=ce(),eE=ZI("toStringTag"),Gp={};Gp[eE]="z";Wp.exports=String(Gp)==="[object z]"});var bi=m((tC,Qp)=>{"use strict";var tE=ls(),rE=J(),cs=yr(),iE=ce(),aE=iE("toStringTag"),sE=Object,nE=cs(function(){return arguments}())==="Arguments",oE=function(a,e){try{return a[e]}catch(t){}};Qp.exports=tE?cs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=oE(e=sE(a),aE))=="string"?t:nE?cs(e):(r=cs(e))==="Object"&&rE(e.callee)?"Arguments":r}});var zp=m((rC,Yp)=>{"use strict";var uE=ls(),lE=bi();Yp.exports=uE?{}.toString:function(){return"[object "+lE(this)+"]"}});var gi=m((iC,Jp)=>{"use strict";var cE=ls(),dE=Wt().f,pE=Pr(),hE=Ye(),fE=zp(),mE=ce(),Kp=mE("toStringTag");Jp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(hE(i,Kp)||dE(i,Kp,{configurable:!0,value:e}),r&&!cE&&pE(i,"toString",fE))}});var Zp=m((aC,Xp)=>{"use strict";var bE=Ro().IteratorPrototype,gE=Eo(),SE=di(),vE=gi(),yE=Gt(),TE=function(){return this};Xp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=gE(bE,{next:SE(+!r,t)}),vE(a,i,!1,!0),yE[i]=TE,a}});var th=m((sC,eh)=>{"use strict";var IE=me(),EE=ut();eh.exports=function(a,e,t){try{return IE(EE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var ih=m((nC,rh)=>{"use strict";var xE=De();rh.exports=function(a){return xE(a)||a===null}});var sh=m((oC,ah)=>{"use strict";var PE=ih(),AE=String,wE=TypeError;ah.exports=function(a){if(PE(a))return a;throw new wE("Can't set "+AE(a)+" as a prototype")}});var $o=m((uC,nh)=>{"use strict";var kE=th(),RE=De(),$E=ai(),LE=sh();nh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=kE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return $E(i),LE(s),RE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var gh=m((lC,bh)=>{"use strict";var ME=Oe(),CE=Ae(),ds=Qe(),fh=lp(),DE=J(),BE=Zp(),oh=Po(),uh=$o(),OE=gi(),VE=Pr(),Lo=kr(),_E=ce(),lh=Gt(),mh=Ro(),NE=fh.PROPER,FE=fh.CONFIGURABLE,ch=mh.IteratorPrototype,ps=mh.BUGGY_SAFARI_ITERATORS,Si=_E("iterator"),dh="keys",vi="values",ph="entries",hh=function(){return this};bh.exports=function(a,e,t,r,i,s,n){BE(t,e,r);var o=function(T){if(T===i&&h)return h;if(!ps&&T&&T in c)return c[T];switch(T){case dh:return function(){return new t(this,T)};case vi:return function(){return new t(this,T)};case ph:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Si]||c["@@iterator"]||i&&c[i],h=!ps&&d||o(i),p=e==="Array"&&c.entries||d,f,b,g;if(p&&(f=oh(p.call(new a)),f!==Object.prototype&&f.next&&(!ds&&oh(f)!==ch&&(uh?uh(f,ch):DE(f[Si])||Lo(f,Si,hh)),OE(f,u,!0,!0),ds&&(lh[u]=hh))),NE&&i===vi&&d&&d.name!==vi&&(!ds&&FE?VE(c,"name",vi):(l=!0,h=function(){return CE(d,this)})),i)if(b={values:o(vi),keys:s?h:o(dh),entries:o(ph)},n)for(g in b)(ps||l||!(g in c))&&Lo(c,g,b[g]);else ME({target:e,proto:!0,forced:ps||l},b);return(!ds||n)&&c[Si]!==h&&Lo(c,Si,h,{name:i}),lh[e]=h,b}});var vh=m((cC,Sh)=>{"use strict";Sh.exports=function(a,e){return{value:a,done:e}}});var Co=m((dC,xh)=>{"use strict";var UE=Ir(),Mo=Vn(),yh=Gt(),Ih=co(),qE=Wt().f,HE=gh(),hs=vh(),jE=Qe(),GE=Be(),Eh="Array Iterator",WE=Ih.set,QE=Ih.getterFor(Eh);xh.exports=HE(Array,"Array",function(a,e){WE(this,{type:Eh,target:UE(a),index:0,kind:e})},function(){var a=QE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,hs(void 0,!0);switch(a.kind){case"keys":return hs(t,!1);case"values":return hs(e[t],!1)}return hs([t,e[t]],!1)},"values");var Th=yh.Arguments=yh.Array;Mo("keys");Mo("values");Mo("entries");if(!jE&&GE&&Th.name!=="values")try{qE(Th,"name",{value:"values"})}catch(a){}});var Ah=m((pC,Ph)=>{"use strict";var YE=ce(),zE=Gt(),KE=YE("iterator"),JE=Array.prototype;Ph.exports=function(a){return a!==void 0&&(zE.Array===a||JE[KE]===a)}});var Do=m((hC,kh)=>{"use strict";var XE=bi(),wh=ui(),ZE=Tr(),ex=Gt(),tx=ce(),rx=tx("iterator");kh.exports=function(a){if(!ZE(a))return wh(a,rx)||wh(a,"@@iterator")||ex[XE(a)]}});var $h=m((fC,Rh)=>{"use strict";var ix=Ae(),ax=ut(),sx=tt(),nx=oi(),ox=Do(),ux=TypeError;Rh.exports=function(a,e){var t=arguments.length<2?ox(a):e;if(ax(t))return sx(ix(t,a));throw new ux(nx(a)+" is not iterable")}});var Ch=m((mC,Mh)=>{"use strict";var lx=Ae(),Lh=tt(),cx=ui();Mh.exports=function(a,e,t){var r,i;Lh(a);try{if(r=cx(a,"return"),!r){if(e==="throw")throw t;return t}r=lx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Lh(r),t}});var ms=m((bC,Vh)=>{"use strict";var dx=fi(),px=Ae(),hx=tt(),fx=oi(),mx=Ah(),bx=ns(),Dh=ni(),gx=$h(),Sx=Do(),Bh=Ch(),vx=TypeError,fs=function(a,e){this.stopped=a,this.result=e},Oh=fs.prototype;Vh.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=dx(e,r),l,c,d,h,p,f,b,g=function(y){return l&&Bh(l,"normal",y),new fs(!0,y)},T=function(y){return i?(hx(y),o?u(y[0],y[1],g):u(y[0],y[1])):o?u(y,g):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Sx(a),!c)throw new vx(fx(a)+" is not iterable");if(mx(c)){for(d=0,h=bx(a);h>d;d++)if(p=T(a[d]),p&&Dh(Oh,p))return p;return new fs(!1)}l=gx(a,c)}for(f=s?a.next:l.next;!(b=px(f,l)).done;){try{p=T(b.value)}catch(y){Bh(l,"throw",y)}if(typeof p=="object"&&p&&Dh(Oh,p))return p}return new fs(!1)}});var Nh=m((gC,_h)=>{"use strict";var yx=Be(),Tx=Wt(),Ix=di();_h.exports=function(a,e,t){yx?Tx.f(a,e,Ix(0,t)):a[e]=t}});var Fh=m(()=>{"use strict";var Ex=Oe(),xx=ms(),Px=Nh();Ex({target:"Object",stat:!0},{fromEntries:function(e){var t={};return xx(e,function(r,i){Px(t,r,i)},{AS_ENTRIES:!0}),t}})});var qh=m((yC,Uh)=>{"use strict";Co();Fh();var Ax=Xa();Uh.exports=Ax.Object.fromEntries});var jh=m((TC,Hh)=>{"use strict";Hh.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 Wh=m(()=>{"use strict";Co();var wx=jh(),kx=X(),Rx=gi(),Gh=Gt();for(bs in wx)Rx(kx[bs],bs),Gh[bs]=Gh.Array;var bs});var Yh=m((xC,Qh)=>{"use strict";var $x=qh();Wh();Qh.exports=$x});var Bo=m((PC,zh)=>{"use strict";var Lx=Yh();zh.exports=Lx});var Kh=m(()=>{"use strict"});var Oo=m((kC,Jh)=>{"use strict";var yi=X(),Mx=Er(),Cx=yr(),gs=function(a){return Mx.slice(0,a.length)===a};Jh.exports=function(){return gs("Bun/")?"BUN":gs("Cloudflare-Workers")?"CLOUDFLARE":gs("Deno/")?"DENO":gs("Node.js/")?"NODE":yi.Bun&&typeof Bun.version=="string"?"BUN":yi.Deno&&typeof Deno.version=="object"?"DENO":Cx(yi.process)==="process"?"NODE":yi.window&&yi.document?"BROWSER":"REST"}()});var Ss=m((RC,Xh)=>{"use strict";var Dx=Oo();Xh.exports=Dx==="NODE"});var ef=m(($C,Zh)=>{"use strict";var Bx=Wt();Zh.exports=function(a,e,t){return Bx.f(a,e,t)}});var af=m((LC,rf)=>{"use strict";var Ox=ot(),Vx=ef(),_x=ce(),Nx=Be(),tf=_x("species");rf.exports=function(a){var e=Ox(a);Nx&&e&&!e[tf]&&Vx(e,tf,{configurable:!0,get:function(){return this}})}});var nf=m((MC,sf)=>{"use strict";var Fx=ni(),Ux=TypeError;sf.exports=function(a,e){if(Fx(e,a))return a;throw new Ux("Incorrect invocation")}});var _o=m((CC,of)=>{"use strict";var qx=me(),Hx=J(),Vo=li(),jx=qx(Function.toString);Hx(Vo.inspectSource)||(Vo.inspectSource=function(a){return jx(a)});of.exports=Vo.inspectSource});var hf=m((DC,pf)=>{"use strict";var Gx=me(),Wx=Pe(),uf=J(),Qx=bi(),Yx=ot(),zx=_o(),lf=function(){},cf=Yx("Reflect","construct"),No=/^\s*(?:class|function)\b/,Kx=Gx(No.exec),Jx=!No.test(lf),Ti=function(e){if(!uf(e))return!1;try{return cf(lf,[],e),!0}catch(t){return!1}},df=function(e){if(!uf(e))return!1;switch(Qx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Jx||!!Kx(No,zx(e))}catch(t){return!0}};df.sham=!0;pf.exports=!cf||Wx(function(){var a;return Ti(Ti.call)||!Ti(Object)||!Ti(function(){a=!0})||a})?df:Ti});var mf=m((BC,ff)=>{"use strict";var Xx=hf(),Zx=oi(),eP=TypeError;ff.exports=function(a){if(Xx(a))return a;throw new eP(Zx(a)+" is not a constructor")}});var Fo=m((OC,gf)=>{"use strict";var bf=tt(),tP=mf(),rP=Tr(),iP=ce(),aP=iP("species");gf.exports=function(a,e){var t=bf(a).constructor,r;return t===void 0||rP(r=bf(t)[aP])?e:tP(r)}});var vf=m((VC,Sf)=>{"use strict";var sP=me();Sf.exports=sP([].slice)});var Tf=m((_C,yf)=>{"use strict";var nP=TypeError;yf.exports=function(a,e){if(a<e)throw new nP("Not enough arguments");return a}});var Uo=m((NC,If)=>{"use strict";var oP=Er();If.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(oP)});var Ko=m((FC,Lf)=>{"use strict";var we=X(),uP=po(),lP=fi(),Ef=J(),cP=Ye(),$f=Pe(),xf=vo(),dP=vf(),Pf=Ka(),pP=Tf(),hP=Uo(),fP=Ss(),Qo=we.setImmediate,Yo=we.clearImmediate,mP=we.process,qo=we.Dispatch,bP=we.Function,Af=we.MessageChannel,gP=we.String,Ho=0,Ii={},wf="onreadystatechange",Ei,Yt,jo,Go;$f(function(){Ei=we.location});var zo=function(a){if(cP(Ii,a)){var e=Ii[a];delete Ii[a],e()}},Wo=function(a){return function(){zo(a)}},kf=function(a){zo(a.data)},Rf=function(a){we.postMessage(gP(a),Ei.protocol+"//"+Ei.host)};(!Qo||!Yo)&&(Qo=function(e){pP(arguments.length,1);var t=Ef(e)?e:bP(e),r=dP(arguments,1);return Ii[++Ho]=function(){uP(t,void 0,r)},Yt(Ho),Ho},Yo=function(e){delete Ii[e]},fP?Yt=function(a){mP.nextTick(Wo(a))}:qo&&qo.now?Yt=function(a){qo.now(Wo(a))}:Af&&!hP?(jo=new Af,Go=jo.port2,jo.port1.onmessage=kf,Yt=lP(Go.postMessage,Go)):we.addEventListener&&Ef(we.postMessage)&&!we.importScripts&&Ei&&Ei.protocol!=="file:"&&!$f(Rf)?(Yt=Rf,we.addEventListener("message",kf,!1)):wf in Pf("script")?Yt=function(a){xf.appendChild(Pf("script"))[wf]=function(){xf.removeChild(this),zo(a)}}:Yt=function(a){setTimeout(Wo(a),0)});Lf.exports={set:Qo,clear:Yo}});var Df=m((UC,Cf)=>{"use strict";var Mf=X(),SP=Be(),vP=Object.getOwnPropertyDescriptor;Cf.exports=function(a){if(!SP)return Mf[a];var e=vP(Mf,a);return e&&e.value}});var Jo=m((qC,Of)=>{"use strict";var Bf=function(){this.head=null,this.tail=null};Bf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Of.exports=Bf});var _f=m((HC,Vf)=>{"use strict";var yP=Er();Vf.exports=/ipad|iphone|ipod/i.test(yP)&&typeof Pebble!="undefined"});var Ff=m((jC,Nf)=>{"use strict";var TP=Er();Nf.exports=/web0s(?!.*chrome)/i.test(TP)});var Qf=m((GC,Wf)=>{"use strict";var $r=X(),IP=Df(),Uf=fi(),Xo=Ko().set,EP=Jo(),xP=Uo(),PP=_f(),AP=Ff(),Zo=Ss(),qf=$r.MutationObserver||$r.WebKitMutationObserver,Hf=$r.document,jf=$r.process,vs=$r.Promise,ru=IP("queueMicrotask"),Rr,eu,tu,ys,Gf;ru||(xi=new EP,Pi=function(){var a,e;for(Zo&&(a=jf.domain)&&a.exit();e=xi.get();)try{e()}catch(t){throw xi.head&&Rr(),t}a&&a.enter()},!xP&&!Zo&&!AP&&qf&&Hf?(eu=!0,tu=Hf.createTextNode(""),new qf(Pi).observe(tu,{characterData:!0}),Rr=function(){tu.data=eu=!eu}):!PP&&vs&&vs.resolve?(ys=vs.resolve(void 0),ys.constructor=vs,Gf=Uf(ys.then,ys),Rr=function(){Gf(Pi)}):Zo?Rr=function(){jf.nextTick(Pi)}:(Xo=Uf(Xo,$r),Rr=function(){Xo(Pi)}),ru=function(a){xi.head||Rr(),xi.add(a)});var xi,Pi;Wf.exports=ru});var zf=m((WC,Yf)=>{"use strict";Yf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ts=m((QC,Kf)=>{"use strict";Kf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var zt=m((YC,Jf)=>{"use strict";var wP=X();Jf.exports=wP.Promise});var Lr=m((zC,tm)=>{"use strict";var kP=X(),Ai=zt(),RP=J(),$P=fo(),LP=_o(),MP=ce(),Xf=Oo(),CP=Qe(),iu=Wn(),Zf=Ai&&Ai.prototype,DP=MP("species"),au=!1,em=RP(kP.PromiseRejectionEvent),BP=$P("Promise",function(){var a=LP(Ai),e=a!==String(Ai);if(!e&&iu===66||CP&&!(Zf.catch&&Zf.finally))return!0;if(!iu||iu<51||!/native code/.test(a)){var t=new Ai(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[DP]=r,au=t.then(function(){})instanceof r,!au)return!0}return!e&&(Xf==="BROWSER"||Xf==="DENO")&&!em});tm.exports={CONSTRUCTOR:BP,REJECTION_EVENT:em,SUBCLASSING:au}});var Mr=m((KC,im)=>{"use strict";var rm=ut(),OP=TypeError,VP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new OP("Bad Promise constructor");e=r,t=i}),this.resolve=rm(e),this.reject=rm(t)};im.exports.f=function(a){return new VP(a)}});var Im=m(()=>{"use strict";var _P=Oe(),NP=Qe(),Ps=Ss(),Pt=X(),Or=Ae(),am=kr(),sm=$o(),FP=gi(),UP=af(),qP=ut(),xs=J(),HP=De(),jP=nf(),GP=Fo(),cm=Ko().set,lu=Qf(),WP=zf(),QP=Ts(),YP=Jo(),dm=co(),As=zt(),cu=Lr(),pm=Mr(),ws="Promise",hm=cu.CONSTRUCTOR,zP=cu.REJECTION_EVENT,KP=cu.SUBCLASSING,su=dm.getterFor(ws),JP=dm.set,Cr=As&&As.prototype,Kt=As,Is=Cr,fm=Pt.TypeError,nu=Pt.document,du=Pt.process,ou=pm.f,XP=ou,ZP=!!(nu&&nu.createEvent&&Pt.dispatchEvent),mm="unhandledrejection",eA="rejectionhandled",nm=0,bm=1,tA=2,pu=1,gm=2,Es,om,rA,um,Sm=function(a){var e;return HP(a)&&xs(e=a.then)?e:!1},vm=function(a,e){var t=e.value,r=e.state===bm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===gm&&aA(e),e.rejection=pu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new fm("Promise-chain cycle")):(l=Sm(u))?Or(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},ym=function(a,e){a.notified||(a.notified=!0,lu(function(){for(var t=a.reactions,r;r=t.get();)vm(r,a);a.notified=!1,e&&!a.rejection&&iA(a)}))},Tm=function(a,e,t){var r,i;ZP?(r=nu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Pt.dispatchEvent(r)):r={promise:e,reason:t},!zP&&(i=Pt["on"+a])?i(r):a===mm&&WP("Unhandled promise rejection",t)},iA=function(a){Or(cm,Pt,function(){var e=a.facade,t=a.value,r=lm(a),i;if(r&&(i=QP(function(){Ps?du.emit("unhandledRejection",t,e):Tm(mm,e,t)}),a.rejection=Ps||lm(a)?gm:pu,i.error))throw i.value})},lm=function(a){return a.rejection!==pu&&!a.parent},aA=function(a){Or(cm,Pt,function(){var e=a.facade;Ps?du.emit("rejectionHandled",e):Tm(eA,e,a.value)})},Dr=function(a,e,t){return function(r){a(e,r,t)}},Br=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=tA,ym(a,!0))},uu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new fm("Promise can't be resolved itself");var r=Sm(e);r?lu(function(){var i={done:!1};try{Or(r,e,Dr(uu,i,a),Dr(Br,i,a))}catch(s){Br(i,s,a)}}):(a.value=e,a.state=bm,ym(a,!1))}catch(i){Br({done:!1},i,a)}}};if(hm&&(Kt=function(e){jP(this,Is),qP(e),Or(Es,this);var t=su(this);try{e(Dr(uu,t),Dr(Br,t))}catch(r){Br(t,r)}},Is=Kt.prototype,Es=function(e){JP(this,{type:ws,done:!1,notified:!1,parent:!1,reactions:new YP,rejection:!1,state:nm,value:void 0})},Es.prototype=am(Is,"then",function(e,t){var r=su(this),i=ou(GP(this,Kt));return r.parent=!0,i.ok=xs(e)?e:!0,i.fail=xs(t)&&t,i.domain=Ps?du.domain:void 0,r.state===nm?r.reactions.add(i):lu(function(){vm(i,r)}),i.promise}),om=function(){var a=new Es,e=su(a);this.promise=a,this.resolve=Dr(uu,e),this.reject=Dr(Br,e)},pm.f=ou=function(a){return a===Kt||a===rA?new om(a):XP(a)},!NP&&xs(As)&&Cr!==Object.prototype)){um=Cr.then,KP||am(Cr,"then",function(e,t){var r=this;return new Kt(function(i,s){Or(um,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Cr.constructor}catch(a){}sm&&sm(Cr,Is)}_P({global:!0,constructor:!0,wrap:!0,forced:hm},{Promise:Kt});FP(Kt,ws,!1,!0);UP(ws)});var wm=m((ZC,Am)=>{"use strict";var sA=ce(),xm=sA("iterator"),Pm=!1;try{Em=0,hu={next:function(){return{done:!!Em++}},return:function(){Pm=!0}},hu[xm]=function(){return this},Array.from(hu,function(){throw 2})}catch(a){}var Em,hu;Am.exports=function(a,e){try{if(!e&&!Pm)return!1}catch(i){return!1}var t=!1;try{var r={};r[xm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var fu=m((eD,km)=>{"use strict";var nA=zt(),oA=wm(),uA=Lr().CONSTRUCTOR;km.exports=uA||!oA(function(a){nA.all(a).then(void 0,function(){})})});var Rm=m(()=>{"use strict";var lA=Oe(),cA=Ae(),dA=ut(),pA=Mr(),hA=Ts(),fA=ms(),mA=fu();lA({target:"Promise",stat:!0,forced:mA},{all:function(e){var t=this,r=pA.f(t),i=r.resolve,s=r.reject,n=hA(function(){var o=dA(t.resolve),u=[],l=0,c=1;fA(e,function(d){var h=l++,p=!1;c++,cA(o,t,d).then(function(f){p||(p=!0,u[h]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Lm=m(()=>{"use strict";var bA=Oe(),gA=Qe(),SA=Lr().CONSTRUCTOR,bu=zt(),vA=ot(),yA=J(),TA=kr(),$m=bu&&bu.prototype;bA({target:"Promise",proto:!0,forced:SA,real:!0},{catch:function(a){return this.then(void 0,a)}});!gA&&yA(bu)&&(mu=vA("Promise").prototype.catch,$m.catch!==mu&&TA($m,"catch",mu,{unsafe:!0}));var mu});var Mm=m(()=>{"use strict";var IA=Oe(),EA=Ae(),xA=ut(),PA=Mr(),AA=Ts(),wA=ms(),kA=fu();IA({target:"Promise",stat:!0,forced:kA},{race:function(e){var t=this,r=PA.f(t),i=r.reject,s=AA(function(){var n=xA(t.resolve);wA(e,function(o){EA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Cm=m(()=>{"use strict";var RA=Oe(),$A=Mr(),LA=Lr().CONSTRUCTOR;RA({target:"Promise",stat:!0,forced:LA},{reject:function(e){var t=$A.f(this),r=t.reject;return r(e),t.promise}})});var gu=m((lD,Dm)=>{"use strict";var MA=tt(),CA=De(),DA=Mr();Dm.exports=function(a,e){if(MA(a),CA(e)&&e.constructor===a)return e;var t=DA.f(a),r=t.resolve;return r(e),t.promise}});var Vm=m(()=>{"use strict";var BA=Oe(),OA=ot(),Bm=Qe(),VA=zt(),Om=Lr().CONSTRUCTOR,_A=gu(),NA=OA("Promise"),FA=Bm&&!Om;BA({target:"Promise",stat:!0,forced:Bm||Om},{resolve:function(e){return _A(FA&&this===NA?VA:this,e)}})});var _m=m(()=>{"use strict";Im();Rm();Lm();Mm();Cm();Vm()});var qm=m(()=>{"use strict";var UA=Oe(),qA=Qe(),ks=zt(),HA=Pe(),Fm=ot(),Um=J(),jA=Fo(),Nm=gu(),GA=kr(),vu=ks&&ks.prototype,WA=!!ks&&HA(function(){vu.finally.call({then:function(){}},function(){})});UA({target:"Promise",proto:!0,real:!0,forced:WA},{finally:function(a){var e=jA(this,Fm("Promise")),t=Um(a);return this.then(t?function(r){return Nm(e,a()).then(function(){return r})}:a,t?function(r){return Nm(e,a()).then(function(){throw r})}:a)}});!qA&&Um(ks)&&(Su=Fm("Promise").prototype.finally,vu.finally!==Su&&GA(vu,"finally",Su,{unsafe:!0}));var Su});var Rs=m((bD,Hm)=>{"use strict";var QA=ot();Hm.exports=QA});var Gm=m((gD,jm)=>{"use strict";Kh();_m();qm();var YA=Rs();jm.exports=YA("Promise","finally")});var Qm=m((SD,Wm)=>{"use strict";var zA=Gm();Wm.exports=zA});var $s=m((vD,Ym)=>{"use strict";var KA=Qm();Ym.exports=KA});var vb=m(()=>{"use strict";var Pw=Oe(),Aw=ci(),ww=ns(),kw=ss(),Rw=Vn();Pw({target:"Array",proto:!0},{at:function(e){var t=Aw(this),r=ww(t),i=kw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Rw("at")});var Tb=m((k0,yb)=>{"use strict";vb();var $w=Rs();yb.exports=$w("Array","at")});var Eb=m((R0,Ib)=>{"use strict";var Lw=Tb();Ib.exports=Lw});var Nr=m(($0,xb)=>{"use strict";var Mw=Eb();xb.exports=Mw});var $g=m(()=>{"use strict"});var Lg=m(()=>{"use strict"});var Cg=m((U_,Mg)=>{"use strict";var Fk=De(),Uk=yr(),qk=ce(),Hk=qk("match");Mg.exports=function(a){var e;return Fk(a)&&((e=a[Hk])!==void 0?!!e:Uk(a)==="RegExp")}});var Bg=m((q_,Dg)=>{"use strict";var jk=bi(),Gk=String;Dg.exports=function(a){if(jk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Gk(a)}});var Vg=m((H_,Og)=>{"use strict";var Wk=tt();Og.exports=function(){var a=Wk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Fg=m((j_,Ng)=>{"use strict";var Qk=Ae(),Yk=Ye(),zk=ni(),Kk=Vg(),_g=RegExp.prototype;Ng.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in _g)&&!Yk(a,"flags")&&zk(_g,a)?Qk(Kk,a):e}});var qg=m((G_,Ug)=>{"use strict";var zu=me(),Jk=ci(),Xk=Math.floor,Qu=zu("".charAt),Zk=zu("".replace),Yu=zu("".slice),eR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,tR=/\$([$&'`]|\d{1,2})/g;Ug.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=tR;return i!==void 0&&(i=Jk(i),u=eR),Zk(s,u,function(l,c){var d;switch(Qu(c,0)){case"$":return"$";case"&":return a;case"`":return Yu(e,0,t);case"'":return Yu(e,n);case"<":d=i[Yu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=Xk(h/10);return p===0?l:p<=o?r[p-1]===void 0?Qu(c,1):r[p-1]+Qu(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var Gg=m(()=>{"use strict";var rR=Oe(),iR=Ae(),Ju=me(),Hg=ai(),aR=J(),sR=Tr(),nR=Cg(),Gr=Bg(),oR=ui(),uR=Fg(),lR=qg(),cR=ce(),dR=Qe(),pR=cR("replace"),hR=TypeError,Ku=Ju("".indexOf),fR=Ju("".replace),jg=Ju("".slice),mR=Math.max;rR({target:"String",proto:!0},{replaceAll:function(e,t){var r=Hg(this),i,s,n,o,u,l,c,d,h,p,f=0,b="";if(!sR(e)){if(i=nR(e),i&&(s=Gr(Hg(uR(e))),!~Ku(s,"g")))throw new hR("`.replaceAll` does not allow non-global regexes");if(n=oR(e,pR),n)return iR(n,e,r,t);if(dR&&i)return fR(Gr(r),e,t)}for(o=Gr(r),u=Gr(e),l=aR(t),l||(t=Gr(t)),c=u.length,d=mR(1,c),h=Ku(o,u);h!==-1;)p=l?Gr(t(u,h,o)):lR(u,o,h,[],void 0,t),b+=jg(o,f,h)+p,f=h+c,h=h+d>o.length?-1:Ku(o,u,h+d);return f<o.length&&(b+=jg(o,f)),b}})});var Qg=m((Y_,Wg)=>{"use strict";$g();Lg();Gg();var bR=Rs();Wg.exports=bR("String","replaceAll")});var zg=m((z_,Yg)=>{"use strict";var gR=Qg();Yg.exports=gR});var Jg=m((K_,Kg)=>{"use strict";var SR=zg();Kg.exports=SR});var hc="2.0.117-dev.8d5a23be.0";var fe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(fe||{}),xt=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(xt||{});var Qa=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Qa||{}),Ln=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ln||{});var Mn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Mn||{});import{assertNever as vc,assertNonNullable as Ov,isNonNullable as Ya,ValueSubject as Cn,Subject as Vv,Subscription as _v,merge as Nv,observableFrom as Fv,fromEvent as mc,map as bc,tap as gc,filterChanged as Uv,isNullable as Dn,ErrorCategory as Sc}from"@vkontakte/videoplayer-shared";var fc=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var za=class{constructor(e){this.connection$=new Cn(void 0);this.castState$=new Cn("NOT_AVAILABLE");this.errorEvent$=new Vv;this.realCastState$=new Cn("NOT_AVAILABLE");this.subscription=new _v;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ya((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||fc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Sc.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ya(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Dn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Dn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(mc(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return vc(i.sessionState)}})).add(Nv(mc(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(gc(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),bc(i=>i.castState)),Fv([r.getCastState()])).pipe(Uv(),bc(qv),gc(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ya(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Ov(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Dn(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ya(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Sc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},qv=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return vc(a)}};var XS=Ge(Bo(),1);var ab=Ge($s(),1);import{assertNever as zm}from"@vkontakte/videoplayer-shared";var ne=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:zm(t)}return a},yu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:zm(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as JA,Subject as Ls,merge as Km}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.transitionStarted$=new Ls;this.transitionEnded$=new Ls;this.transitionUpdated$=new Ls;this.forceChanged$=new Ls;this.stateChangeStarted$=Km(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Km(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||JA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as XA}from"@vkontakte/videoplayer-shared";var Jm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return XA(a)}};import{assertNever as Vr,assertNonNullable as Jt,debounce as Xm,ErrorCategory as Zm,fromEvent as Xt,isNonNullable as eb,map as tb,merge as rb,observableFrom as ZA,Subject as ew,Subscription as Tu,timeout as tw,getHighestQuality as rw}from"@vkontakte/videoplayer-shared";var iw=5,aw=5,sw=500,ib=7e3,wi=class{constructor(e){this.subscription=new Tu;this.loadMediaTimeoutSubscription=new Tu;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Vr(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:Vr(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:Vr(e)}break}default:Vr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Jm(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 Tu;this.subscription.add(e),this.subscription.add(rb(this.videoState.stateChangeStarted$.pipe(tb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(tb(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new ew;e.add(i.pipe(Xm(sw)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Xt(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)>iw)&&i.next(o),s=o})),e.add(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<aw&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Vr(n)}}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=rb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ZA(["init"])).pipe(Xm(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];Jt(c);let d=rw(Object.keys(c));Jt(d);let h=c[d];Jt(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Jt(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Jt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Jt(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Jt(c),r=ne(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Zm.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Vr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return eb(o)&&(n.metadata.title=o),eb(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(tw(ib).subscribe(()=>s(`timeout(${ib})`)))});(0,ab.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Zm.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as nb}from"@vkontakte/videoplayer-shared";import{clearVideoElement as nw}from"@vkontakte/videoplayer-shared";var sb=a=>{try{a.pause(),a.playbackRate=0,nw(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as ow,Subscription as uw}from"@vkontakte/videoplayer-shared";var Iu=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)}},Eu=window.WeakMap?new WeakMap:new Iu,xu=window.WeakMap?new WeakMap:new Map,lw=(a,e=20)=>{let t=0;return ow(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},be=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?nb(t):(t=document.createElement("video"),a.appendChild(t)),Eu.set(t,r);let i=new uw;return i.add(lw(t,e)),xu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ge=a=>{let e=xu.get(a);e==null||e.unsubscribe(),xu.delete(a);let t=Eu.get(a);Eu.delete(a),t?nb(a):sb(a)};import{assertNonNullable as ki,isNonNullable as it,isNullable as pw,fromEvent as _r,merge as ob,observableFrom as ub,filterChanged as lb,map as Ri,Subject as cb,Subscription as hw,ValueSubject as fw,ErrorCategory as mw}from"@vkontakte/videoplayer-shared";import{isNonNullable as Pu,isNullable as cw,Subscription as dw}from"@vkontakte/videoplayer-shared";var Ms=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=cw(i),l=new dw;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},rt=(a,e,t)=>Ms(e,()=>a.loop,r=>{Pu(r)&&(a.loop=r)},{onError:t}),Se=(a,e,t,r)=>Ms(e,()=>({muted:a.muted,volume:a.volume}),i=>{Pu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Ve=(a,e,t,r)=>Ms(e,()=>a.playbackRate,i=>{Pu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),At=Ms;var bw=a=>["__",a.language,a.label].join("|"),gw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Au=class a{constructor(){this.available$=new cb;this.current$=new fw(void 0);this.error$=new cb;this.subscription=new hw;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:mw.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(At(t.internalTextTracks,()=>Object.values(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(Ri(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(At(t.externalTextTracks,()=>Object.values(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(Ri(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(At(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(At(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ki(this.video);let{textTracks:e}=this.video;this.subscription.add(_r(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(ob(_r(e,"addtrack"),_r(e,"removetrack"),ub(["init"])).pipe(Ri(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),lb((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(ob(_r(e,"change"),ub(["init"])).pipe(Ri(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ri(r=>r&&this.htmlTextTrackToITextTrack(r).id),lb()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(_r(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(_r(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;it(t.align)&&(i.align=t.align),it(t.position)&&(i.position=t.position),it(t.size)&&(i.size=t.size),it(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){ki(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c;let{language:t,label:r}=e,i=e.id?e.id:bw(e),s=this.externalTracks.has(i),n=(s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)||i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(l=this.externalTracks.get(i))==null?void 0:l.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(c=this.internalTracks.get(i))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){ki(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(pw(e)||!gw(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){ki(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){ki(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},_e=Au;var dt=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 db=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},wu=a=>{let e=db(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},pb=a=>{let e=db(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ne,map as wt,merge as fb,filterChanged as vw,isNonNullable as mb,Subject as yw,filter as bb,mapTo as gb,combine as Tw,once as Iw,ErrorCategory as Ew,ValueSubject as Sb,clientChecker as xw}from"@vkontakte/videoplayer-shared";var Sw=3,hb=(a,e,t=Sw)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var ve=a=>{let e=S=>Ne(a,S).pipe(gb(void 0)),r=fb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>Ne(a,S))).pipe(wt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),vw()),i=fb(Ne(a,"progress"),Ne(a,"timeupdate")).pipe(wt(()=>hb(a.buffered,a.currentTime))),s=xw.isSafari?Tw({play:e("play").pipe(Iw()),playing:e("playing")}).pipe(gb(void 0)):e("playing"),n=Ne(a,"volumechange").pipe(wt(()=>({muted:a.muted,volume:a.volume}))),o=Ne(a,"ratechange").pipe(wt(()=>a.playbackRate)),u=Ne(a,"error").pipe(bb(()=>!!(a.error||a.played.length)),wt(()=>{var I;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:Ew.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=Ne(a,"timeupdate").pipe(wt(()=>a.currentTime)),c=new yw,d=.3,h;l.subscribe(S=>{a.loop&&mb(h)&&mb(S)&&h>=a.duration-d&&S<=d&&c.next(h),h=S});let p=e("pause").pipe(bb(()=>!a.error&&h!==a.duration)),f=Ne(a,"enterpictureinpicture"),b=Ne(a,"leavepictureinpicture"),g=new Sb(pb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let T=new Sb(wu(a));return Ne(a,"fullscreenchange").pipe(wt(()=>wu(a))).subscribe(T),{playing$:s,pause$:p,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ne(a,"durationchange").pipe(wt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:T}};import{VideoQuality as kt}from"@vkontakte/videoplayer-shared";var Rt=a=>{switch(a){case"mobile":return kt.Q_144P;case"lowest":return kt.Q_240P;case"low":return kt.Q_360P;case"sd":case"medium":return kt.Q_480P;case"hd":case"high":return kt.Q_720P;case"fullhd":case"full":return kt.Q_1080P;case"quadhd":case"quad":return kt.Q_1440P;case"ultrahd":case"ultra":return kt.Q_2160P}};var Zt=Ge(Nr(),1);import{isNonNullable as te,isNullable as Ru,now as Mb,isHigher as $u,isHigherOrEqual as kb,isInvariantQuality as Rb,isLower as $b,isLowerOrEqual as Lu,videoSizeToQuality as Cw,assertNotEmptyArray as Cb,assertNonNullable as Dw}from"@vkontakte/videoplayer-shared";var ku=!1,pt={},Pb=a=>{ku=a},Ab=()=>{pt={}},wb=a=>{a(pt)},$i=(a,e)=>{var t;ku&&(pt.meta=(t=pt.meta)!=null?t:{},pt.meta[a]=e)},de=class{constructor(e){this.name=e}next(e){var r,i;if(!ku)return;pt.series=(r=pt.series)!=null?r:{};let t=(i=pt.series[this.name])!=null?i:[];t.push([Date.now(),e]),pt.series[this.name]=t}};var Bw=new de("best_bitrate"),Db=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Mu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Li=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Mb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Bb='Assertion "ABR Tracks is empty array" failed',Cs=(a,e,t,r)=>{var u;let i=[...e].sort(Mu(1)),s=[...t].sort(Mu(1)),n=s.filter(l=>te(l.bitrate)&&te(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Zt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Zt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Zt.default)(n,-1):(0,Zt.default)(s,0)},Lb=a=>"quality"in a,Ob=(a,e,t,r)=>{var n;let i=te((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&te(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Mb()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Lb(o)?"video":"audio",l=Lb(o)?o.quality:o.bitrate;return e({message:`
7
7
  [last ${u} selected] ${l}
8
- `}),o}return r==null||r.recordSwitch(t),t},$t=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var W,V,N,R,q,M;Cb(a,Bb);let p=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let x=window.devicePixelRatio;if(r.pixelRatioMultiplier)p*=r.pixelRatioMultiplier*(x-1)+1;else{let[E=0,C=1,Y=0]=r.pixelRatioPolynome;p*=E*De(x,2)+C*x+Y}}let f=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*p,height:e.height*p}:void 0,b=r.considerPlaybackRate&&te(o)?o:1,g=a.filter(x=>!Rb(x.quality)).sort((x,E)=>$u(x.quality,E.quality)?-1:1),v=(W=(0,er.default)(g,-1))==null?void 0:W.quality,y=(V=(0,er.default)(g,0))==null?void 0:V.quality,S=Ru(i)||te(i.min)&&te(i.max)&&$b(i.max,i.min)||te(i.min)&&y&&$u(i.min,y)||te(i.max)&&v&&$b(i.max,v),T=b*Db(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),I={},L=g.filter(x=>{let E=!0;if(f)if(x.size)E=x.size.width<=f.width&&x.size.height<=f.height;else{let Ft=f&&Cw(f);E=Ft?Lu(x.quality,Ft):!0}if(!E)return I[x.quality]="FitsContainer",!1;if(!(te(t)&&isFinite(t)&&te(x.bitrate)?t-s>=x.bitrate*T:!0))return I[x.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&te(r.minBufferToSwitchUp)&&u&&!Rb(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&$u(x.quality,u.quality))return I[x.quality]="Buffer",!1;if(!!d&&kb(x.quality,d))return I[x.quality]="DroppedFramesLimit",!1;let se=S||(Ru(i.max)||Lu(x.quality,i.max))&&(Ru(i.min)||kb(x.quality,i.min)),He=te(c)&&!c?Lu(x.quality,r.backgroundVideoQualityLimit):!0;return!se||!He?(I[x.quality]="FitsQualityLimits",!1):!0})[0];L&&L.bitrate&&Bw.next(L.bitrate);let _=(N=L!=null?L:g[Math.ceil((g.length-1)/2)])!=null?N:a[0];return _.quality!==((R=l==null?void 0:l.last)==null?void 0:R.quality)&&h({message:`
8
+ `}),o}return r==null||r.recordSwitch(t),t},$t=(a,{container:e,throughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var _,R,U,L,W;Cb(a,Bb);let p=(_=window.devicePixelRatio)!=null?_:1,f=r.usePixelRatio?r.pixelRatioMultiplier*(p-1)+1:1,b=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*f*r.containerSizeFactor,height:e.height*f*r.containerSizeFactor},g=b&&Cw(b),T=r.considerPlaybackRate&&te(o)?o:1,y=a.filter(v=>!Rb(v.quality)).sort((v,$)=>$u(v.quality,$.quality)?-1:1),S=(R=(0,Zt.default)(y,-1))==null?void 0:R.quality,I=(U=(0,Zt.default)(y,0))==null?void 0:U.quality,E=Ru(i)||te(i.min)&&te(i.max)&&$b(i.max,i.min)||te(i.min)&&I&&$u(i.min,I)||te(i.max)&&S&&$b(i.max,S),k=T*Db(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),B={},V=y.filter(v=>{if(!(g?Lu(v.quality,g):!0))return B[v.quality]="FitsContainer",!1;if(!(te(t)&&isFinite(t)&&te(v.bitrate)?t-s>=v.bitrate*k:!0))return B[v.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&te(r.minBufferToSwitchUp)&&u&&!Rb(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&$u(v.quality,u.quality))return B[v.quality]="Buffer",!1;if(!!d&&kb(v.quality,d))return B[v.quality]="DroppedFramesLimit",!1;let qe=E||(Ru(i.max)||Lu(v.quality,i.max))&&(Ru(i.min)||kb(v.quality,i.min)),dr=te(c)&&!c?Lu(v.quality,r.backgroundVideoQualityLimit):!0;return!qe||!dr?(B[v.quality]="FitsQualityLimits",!1):!0})[0];V&&V.bitrate&&Bw.next(V.bitrate);let M=(L=V!=null?V:y[Math.ceil((y.length-1)/2)])!=null?L:a[0];return M.quality!==((W=l==null?void 0:l.last)==null?void 0:W.quality)&&h({message:`
9
9
  [VIDEO TRACKS ABR]
10
10
  [available video tracks]
11
- ${a.map(x=>`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate} }`).join(`
11
+ ${a.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.bitrate} }`).join(`
12
12
  `)}
13
13
 
14
14
  [tuning]
15
- ${Object.entries(r!=null?r:{}).map(([x,E])=>`${x}: ${E}`).join(`
15
+ ${Object.entries(r!=null?r:{}).map(([v,$])=>`${v}: ${$}`).join(`
16
16
  `)}
17
17
 
18
18
  [limit params]
19
- containerSizeLimit: ${(q=f==null?void 0:f.width)!=null?q:0} x ${(M=f==null?void 0:f.width)!=null?M:0},
19
+ containerQualityLimit: ${g},
20
20
  throughput: ${t},
21
21
  reserve: ${s},
22
22
  playbackRate: ${o},
23
- playbackRateFactor: ${b},
23
+ playbackRateFactor: ${T},
24
24
  forwardBufferHealth: ${n},
25
- bitrateFactor: ${T},
25
+ bitrateFactor: ${k},
26
26
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
27
27
  droppedVideoMaxQualityLimit: ${d},
28
- limitsAreInvalid: ${S},
28
+ limitsAreInvalid: ${E},
29
29
  maxQualityLimit: ${i==null?void 0:i.max},
30
30
  minQualityLimit: ${i==null?void 0:i.min},
31
31
 
32
32
  [limited video tracks]
33
- ${Object.entries(I).map(([x,E])=>`${x}: ${E}`).join(`
33
+ ${Object.entries(B).map(([v,$])=>`${v}: ${$}`).join(`
34
34
  `)||"All tracks are available"}
35
35
 
36
- [best video track] ${L==null?void 0:L.quality}
37
- [selected video track] ${_==null?void 0:_.quality}
38
- `}),Ob(r,h,_,l)},Vb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var b;Cb(t,Bb);let l=i.considerPlaybackRate&&te(s)?s:1,c=[...t].sort(Mu(-1)),d=a.bitrate;Dw(d);let h=l*Db(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),p,f=Cs(a,e,t,i.minVideoAudioRatio);return te(r)&&isFinite(r)&&(p=c.find(g=>te(g.bitrate)&&te(f==null?void 0:f.bitrate)?r-d>=g.bitrate*h&&g.bitrate>=f.bitrate:!1)),p||(p=f),(p==null?void 0:p.bitrate)!==((b=o==null?void 0:o.last)==null?void 0:b.bitrate)&&u({message:`
36
+ [best video track] ${V==null?void 0:V.quality}
37
+ [selected video track] ${M==null?void 0:M.quality}
38
+ `}),Ob(r,h,M,l)},Vb=(a,e,t,{throughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var b;Cb(t,Bb);let l=i.considerPlaybackRate&&te(s)?s:1,c=[...t].sort(Mu(-1)),d=a.bitrate;Dw(d);let h=l*Db(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),p,f=Cs(a,e,t,i.minVideoAudioRatio);return te(r)&&isFinite(r)&&(p=c.find(g=>te(g.bitrate)&&te(f==null?void 0:f.bitrate)?r-d>=g.bitrate*h&&g.bitrate>=f.bitrate:!1)),p||(p=f),(p==null?void 0:p.bitrate)!==((b=o==null?void 0:o.last)==null?void 0:b.bitrate)&&u({message:`
39
39
  [AUDIO TRACKS ABR]
40
40
  [available audio tracks]
41
41
  ${t.map(g=>`{ id: ${g.id}, bitrate: ${g.bitrate} }`).join(`
42
42
  `)}
43
43
 
44
44
  [tuning]
45
- ${Object.entries(i!=null?i:{}).map(([g,v])=>`${g}: ${v}`).join(`
45
+ ${Object.entries(i!=null?i:{}).map(([g,T])=>`${g}: ${T}`).join(`
46
46
  `)}
47
47
 
48
48
  [limit params]
@@ -55,14 +55,14 @@ var kv=Object.create;var kn=Object.defineProperty,Rv=Object.defineProperties,$v=
55
55
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
56
56
 
57
57
  [selected audio track] ${p==null?void 0:p.id}
58
- `}),p&&Ob(i,u,p,o)};var re=a=>new URL(a).hostname;import{assertNever as Hb,assertNonNullable as jb,combine as rk,debounce as ik,ErrorCategory as Gb,filter as Wb,filterChanged as ak,isNonNullable as Vu,map as _s,merge as Yb,observableFrom as sk,once as nk,Subscription as ok,ValueSubject as _u,videoQualityToHeight as uk,videoSizeToQuality as lk}from"@vkontakte/videoplayer-shared";var _b=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},ye=(a,e)=>k(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!_b(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return _b(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as Bs,isNullable as _w,assertNonNullable as Di}from"@vkontakte/videoplayer-shared";import{isNonNullable as Nb,assertNonNullable as Ds,now as Ow}from"@vkontakte/videoplayer-shared";function ie(){return Ow()}function Cu(a){return ie()-a}function Du(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Fb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Fr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Ds(c);let R=Cu(c),q;if(R<b){q=b-R,setTimeout(g,q);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},v=R=>(s=R,N),y=R=>(d=R,N),S=()=>(p="json",N),T=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=R=>(h=R,N),$=()=>{c=ie(),n=new i,n.open("get",a);let R=0,q,M=0,x=()=>(Ds(c),Math.max(c,Math.max(q||0,M||0)));if(s&&n.addEventListener("progress",E=>{let C=ie();s.updateChunk&&E.loaded>R&&(s.updateChunk(x(),E.loaded-R),R=E.loaded,q=C)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;Ds(n);let E=n.status;if(E>=200&&E<300){if(n.response.byteLength&&s){let C=n.response.byteLength-R;C&&s.updateChunk&&s.updateChunk(x(),C)}n.responseType==="json"&&!Object.values(n.response).length?T():(d&&d(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),h){let E=()=>{Ds(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(M=ie(),n.removeEventListener("readystatechange",E))};n.addEventListener("readystatechange",E)}return n.responseType=p,n.send(),N},N={withBitrateReporting:v,withParallel:I,withJSONResponse:S,withRetryCount:R=>(l=R,N),withRetryInterval:(R,q)=>(Nb(R)&&(b=R),Nb(q)&&(f=q),N),withTimeout:R=>(o=R,N),withFinally:y,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return N}var Mi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ci=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ie(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ie()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Fr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ie()}_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=ie();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as Nw}from"@vkontakte/videoplayer-shared";var Os=1e4,Bu=3;var Fw=6e4,Uw=10,qw=1,Hw=500,Bi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new Nw,this.chunkRateEstimator=new Mi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Du(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Du(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Bs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Fb(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ci(Bu,Os,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let T=s&&(!c||c===this.rep);return T||t("Not running!"),T},h=(T,I,$)=>{u&&u.abort(),u=Fr(this.urlResolver.resolve(T,!1),I,$,()=>this._retryCallback()).withTimeout(Os).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Bu).withFinally(()=>{u=null}).send()},p=(T,I,$)=>{Di(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),I,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let I=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${I}=>${T}`),r.playbackRate=T)},b=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=ie()-1e4,L=0;for(let W=0;W<this.bufferStates.length;W++){let V=this.bufferStates[W];T=Math.min(T,V.buf),V.ts<$&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${T} drop=${L} jitter=${this.sourceJitter}`);let _=T-qw;this.sourceJitter>=0?_-=this.sourceJitter/2:this.sourceJitter-=1,_>3?f(1.15):_>1?f(1.1):_>.3?f(1.05):f(1)}},v=T=>{let I,$=()=>I&&I.start?I.start.length:0,L=E=>I.start[E]/1e3,_=E=>I.dur[E]/1e3,W=E=>I.fragIndex+E,V=(E,C)=>({chunkIdx:W(E),startTS:L(E),dur:_(E),discontinuity:C}),N=()=>{let E=0;if(I&&I.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,F=C;this.sourceJitter>1&&(F+=this.sourceJitter-1);let se=I.dur.length-1;for(;se>=0&&(F-=I.dur[se],!(F<=0));--se);E=Math.min(se,I.dur.length-1-Y),E=Math.max(E,0)}return V(E,!0)},R=E=>{let C=$();if(!(C<=0)){if(Bs(E)){for(let Y=0;Y<C;Y++)if(L(Y)>E)return V(Y)}return N()}},q=E=>{let C=$(),Y=E?E.chunkIdx+1:0,F=Y-I.fragIndex;if(!(C<=0)){if(!E||F<0||F-C>Uw)return t(`Resync: offset=${F} bChunks=${C} chunk=`+JSON.stringify(E)),N();if(!(F>=C))return V(Y-I.fragIndex,!1)}},M=(E,C,Y)=>{l&&l.abort(),l=Fr(this.urlResolver.resolve(E,!0,this.lowLatency),C,Y,()=>this._retryCallback()).withTimeout(Os).withRetryCount(Bu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(E,C)=>{M(T,Y=>{if(!d())return;I=Y;let F=!!I.lowLatency;F!==this.lowLatency&&b(F);let se=0;for(let He=0;He<I.dur.length;++He)se+=I.dur[He];se>0&&(Di(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,E(R(C))},()=>this._handleNetworkError())},nextChunk:q}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Di(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{let{videoElement:I,logger:$}=this.params,L=v(e.jidxUrl),_,W,V,N,R=0,q,M,x,E=()=>{q&&(clearTimeout(q),q=void 0);let j=Math.max(Hw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=R+j,xe=ie(),Me=Math.min(1e4,he-xe);R=xe;let gt=()=>{l||d()&&L.seek(()=>{d()&&(R=ie(),C(),E())})};Me>0?q=window.setTimeout(()=>{this.paused?E():gt()},Me):gt()},C=()=>{let j;for(;j=L.nextChunk(N);)N=j,Ft(j);let he=L.nextChunk(V);if(he){if(V&&he.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?E():(y(),this._initPlayerWith(e));return}He(he)}else E()},Y=(j,he)=>{if(!d()||!this.sourceBuffer)return;let xe,Me,gt,pr=St=>{window.setTimeout(()=>{d()&&Y(j,he)},St)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),pr(100);else{let St=ie(),Ut=I.currentTime;!this.paused&&I.buffered.length>1&&M===Ut&&St-x>500&&($("Stall suspected; trying to fix"),this._fixupStall()),M!==Ut&&(M=Ut,x=St);let hr=this._getBufferSizeSec();if(hr>30)$(`Buffered ${hr} seconds; delaying appendBuffer`),pr(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:hr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch(Jr){if(Jr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),gt=this.sourceBuffer.buffered.length,gt!==0&&(xe=this.sourceBuffer.buffered.start(0),Me=Ut,Me-xe>4&&this.sourceBuffer.remove(xe,Me-3)),pr(1e3);else throw Jr}}},F=()=>{W&&_&&($([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(V)]),Y(W,function(){W=null,C()}))},se=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),He=j=>{d()&&p(se(j),(he,xe)=>{if(d()){if(xe/=1e3,W=he,V=j,n=j.startTS,xe){let Me=Math.min(10,j.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Me:Me}F()}},()=>this._handleNetworkError())},Ft=j=>{d()&&(Di(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(j),!1)))},Kr=j=>{d()&&(e.cachedHeader=j,Y(j,()=>{_=!0,F()}))};s=!0,L.seek(j=>{if(d()){if(R=ie(),!j){E();return}N=j,!_w(T)||j.startTS>T?He(j):(V=j,C())}},T),e.cachedHeader?Kr(e.cachedHeader):h(e.headerUrl,Kr,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Bs(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Di(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Bs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),f=d/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let f=ie();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Cu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ie();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Fr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Os).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ye(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Fw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as jw,filter as Ub,fromEvent as Gw,interval as Ww,isHigher as Yw,isInvariantQuality as Qw,isLower as zw,merge as Kw,Subject as qb,Subscription as Jw}from"@vkontakte/videoplayer-shared";var Ou=class{constructor(){this.onDroopedVideoFramesLimit$=new qb;this.subscription=new Jw;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==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Qw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Yw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Gw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Ww(this.droppedFramesChecker.checkTime).pipe(Ub(()=>this.playing),Ub(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(jw(this.droppedFramesChecker.checkTime)),r=Kw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>zw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Vs=Ou;import{map as Xw,Observable as Zw}from"@vkontakte/videoplayer-shared";import{fromEvent as ek}from"@vkontakte/videoplayer-shared";var Oi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var tk=(a,e)=>new Zw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Oi()))},w(w({},r),e));i.observe(a);let s=ek(document,"visibilitychange").pipe(Xw(n=>!document.hidden||Oi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ue=tk;var ck=["paused","playing","ready"],dk=["paused","playing","ready"],Vi=class{constructor(e){this.subscription=new ok;this.videoState=new D("stopped");this.representations$=new _u([]);this.textTracksManager=new Ne;this.droppedFramesManager=new Vs;this.maxSeekBackTime$=new _u(1/0);this.zeroTime$=new _u(void 0);this.liveOffset=new dt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Gb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Rt(u.name))!=null?r:lk(u.video),d=u.bitrate/1e3,h=w({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Vu(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(dk.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&ck.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(oe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(oe(this.params.source.url,u))}return;default:return Hb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Gb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Yb(this.videoState.stateChangeStarted$.pipe(_s(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_s(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ve(this.video);this.subscription.add(this.representations$.pipe(_s(i=>i.map(({track:s})=>s)),Wb(i=>!!i.length),nk()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ak(),_s(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(rk({zeroTime:this.zeroTime$.pipe(Wb(Vu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(rt(this.video,this.params.desiredState.isLooped,t)).add(Se(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(_e(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ue(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&uk(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Hb(i.to)}},t)).add(Yb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,sk(["init"])).pipe(ik(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ge(this.video)}createLiveDashPlayer(){let e=new Bi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Vu(t)?t:$t(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;jb(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;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(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(oe(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Qb=Vi;var at=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as qR,assertNonNullable as HR,debounce as jR,ErrorCategory as ml,filter as ES,filterChanged as bl,fromEvent as GR,isNonNullable as WR,map as xS,merge as ln,observableFrom as YR,observeElementSize as QR,once as PS,Subscription as zR,ValueSubject as KR}from"@vkontakte/videoplayer-shared";var Ns=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Ur=class extends Ns{constructor(){super(),this.listeners||Ns.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)}},_i=class{constructor(){Object.defineProperty(this,"signal",{value:new Ur,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(_i.prototype[Symbol.toStringTag]="AbortController",Ur.prototype[Symbol.toStringTag]="AbortSignal");function Fs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Nu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Fs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Ni=Fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zb=Ni?Nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Ni?zb.fetch:window.fetch,iO=Ni?zb.Request:window.Request,ke=Ni?_i:window.AbortController,aO=Ni?Ur:window.AbortSignal;var zs=We(Nr(),1);var ft=()=>window.ManagedMediaSource||window.MediaSource,Us=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Kb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Jb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Js,clientChecker as Ks}from"@vkontakte/videoplayer-shared";var qe=document.createElement("video"),fk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',mk='video/mp4; codecs="hev1.1.6.L93.B0"',ug='video/webm; codecs="vp09.00.10.08"',lg='video/webm; codecs="av01.0.00M.08"',bk='audio/mp4; codecs="mp4a.40.2"',gk='audio/webm; codecs="opus"',Xb,Zb,Fi={mms:Us(),mse:Kb(),hls:!!((Xb=qe.canPlayType)!=null&&Xb.call(qe,"application/x-mpegurl")||(Zb=qe.canPlayType)!=null&&Zb.call(qe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},eg,tg,Te={mp4:!!((eg=qe.canPlayType)!=null&&eg.call(qe,"video/mp4")),webm:!!((tg=qe.canPlayType)!=null&&tg.call(qe,"video/webm")),cmaf:!0},Hs,rg,js,ig,Gs,ag,Ws,sg,Ys,ng,Qs,og,Ie={h264:!!((rg=(Hs=ft())==null?void 0:Hs.isTypeSupported)!=null&&rg.call(Hs,fk)),h265:!!((ig=(js=ft())==null?void 0:js.isTypeSupported)!=null&&ig.call(js,mk)),vp9:!!((ag=(Gs=ft())==null?void 0:Gs.isTypeSupported)!=null&&ag.call(Gs,ug)),av1:!!((sg=(Ws=ft())==null?void 0:Ws.isTypeSupported)!=null&&sg.call(Ws,lg)),aac:!!((ng=(Ys=ft())==null?void 0:Ys.isTypeSupported)!=null&&ng.call(Ys,bk)),opus:!!((og=(Qs=ft())==null?void 0:Qs.isTypeSupported)!=null&&og.call(Qs,gk))},qr=(Ie.h264||Ie.h265)&&Ie.aac,tr,Sk=()=>k(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(B(w({},a),{video:B(w({},a.video),{contentType:lg})})),window.navigator.mediaCapabilities.decodingInfo(B(w({},a),{video:B(w({},a.video),{contentType:ug})}))]);tr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Sk()}catch(a){console.error(a)}var Hr=Fi.hls&&Te.mp4,cg=()=>Object.keys(Ie).filter(a=>Ie[a]),dg=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Fi.mse&&(!r||!!window.MediaStreamTrack)||Fi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Te.mp4&&qr;case"DASH_WEBM":return i&&Te.webm&&Ie.vp9&&Ie.opus;case"DASH_WEBM_AV1":return i&&Te.webm&&Ie.av1&&Ie.opus;case"DASH_STREAMS":return i&&(Te.mp4&&qr||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return i&&Te.mp4&&qr;case"DASH_LIVE_CMAF":return i&&Te.mp4&&qr&&Te.cmaf;case"DASH_ONDEMAND":return i&&Te.mp4&&qr;case"HLS":case"HLS_ONDEMAND":return Hr||e&&i&&Te.mp4&&qr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Hr;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Fi.webrtc&&Fi.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return Js(s)}})},qs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return tr?tr[t].smooth?[t,e]:tr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return tr?tr[t].powerEfficient?[t,e]:tr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Js(a)}return[e,t]},pg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...qs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ks.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...qs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...qs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...qs(a),...i,"HLS","HLS_ONDEMAND"];default:Js(e)}return Hr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},hg=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=Ks.isMac&&Ks.isSafari;if(Ks.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Js(a)}else Hr&&!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"]},Fu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],fg=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,zs.default)(t.value.split("."),0)}for(let t of a){let r=(0,zs.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,zs.default)(e.value.split("."),0)};import{ErrorCategory as Ui}from"@vkontakte/videoplayer-shared";var mg=a=>{if(!a)return{id:"EmptyResponse",category:Ui.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ui.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ui.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ui.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ui.PARSER,message:"Response is valid XML, but parser failed"}};var Lt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as dl,assertNonNullable as ur,clientChecker as LR,combine as an,ErrorCategory as Bt,filter as pl,filterChanged as gS,flattenObject as va,fromEvent as lr,getTraceSubscriptionMethod as MR,interval as hl,isNonNullable as SS,map as fl,merge as cr,now as CR,Subject as vS,Subscription as yS,tap as DR,throttle as BR,ValueSubject as ue}from"@vkontakte/videoplayer-shared";var Wr=We(Nr(),1);var vk=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},yk=a=>window.clearTimeout(a),bg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),gg=!bg(window.requestIdleCallback)||!bg(window.cancelIdleCallback),Uu=gg?vk:window.requestIdleCallback,vO=gg?yk:window.cancelIdleCallback;var lS=We($s(),1);import{assertNever as Tk,ErrorCategory as Sg,clientChecker as qu,Subject as vg}from"@vkontakte/videoplayer-shared";var Ik=18,yg=!1;try{yg=qu.isSafari&&!!qu.macVersion&&qu.macVersion<=Ik}catch(a){console.error(a)}var Hu=class{constructor(e){this.bufferFull$=new vg;this.error$=new vg;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Sg.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return k(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return k(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return k(this,null,function*(){return new Promise(t=>{let r;yg&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Sg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Tk(t)}}},Tg=Hu;var ju=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as sr,assertNonNullable as ae,ErrorCategory as Ct,fromEvent as nl,getExponentialDelay as ol,isNonNullable as da,isNullable as $e,now as Xs,once as TR,Subject as IR,Subscription as ER,ValueSubject as pa}from"@vkontakte/videoplayer-shared";var G=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var jr=class extends G{};var qi=class extends G{};var Hi=class extends G{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ji=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var K=class extends G{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Gi=class extends K{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 Wi=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends G{constructor(e,t){super(e,t),this.data=this.content}};var rr=class extends K{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Qi=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ki=class extends K{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 Ji=class extends K{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Xi=class extends K{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Zi=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends K{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ta=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=class extends K{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var aa=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends K{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 na=class extends K{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var oa=class extends K{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var xk={ftyp:Hi,moov:ji,mvhd:Gi,moof:Wi,mdat:Yi,sidx:rr,trak:Qi,mdia:Zi,mfhd:ia,tkhd:ea,traf:aa,tfhd:sa,tfdt:na,trun:oa,minf:ta,sv3d:zi,st3d:Ki,prhd:Ji,proj:ra,equi:Xi,uuid:qi,unknown:jr},Mt=class a{constructor(e={}){this.options=w({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=xk[e];return r?new r(t,new a):new jr(t,new a)}};var ir=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Ak=new TextDecoder("ascii"),wk=a=>Ak.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",kk=a=>{let e=new rr(a,new Mt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Rk=(a,e)=>{let r=new Mt().parse(a),i=new ir(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},$k=a=>{var i;let t=new Mt().parse(a);return(i=new ir(t).find("sidx"))==null?void 0:i.timescale},Lk=(a,e)=>{let r=new Mt().parse(a),s=new ir(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Mk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Mt().parse(a),i=new ir(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Ig={validateData:wk,parseInit:Mk,getIndexRange:()=>{},parseSegments:kk,parseFeedableSegmentChunk:Rk,getChunkEndTime:Lk,getTimescaleFromIndex:$k};import{assertNonNullable as Wu,isNonNullable as Ag,isNullable as Dk}from"@vkontakte/videoplayer-shared";import{assertNever as Ck}from"@vkontakte/videoplayer-shared";var Eg={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"}},xg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=ua(a,t),i=r in Eg,s=i?Eg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ua(u),d=l*De(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},ua=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*De(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*De(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*De(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Je=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ua(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:Ck(e)}},ar=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=xg(r);if(!e(i))return;i.type==="master"&&ar(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Pg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=xg(a);return ar(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Je(o,n):s===17026?t=Je(o,n):s===17029&&(r=Je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var wg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Bk=[231,22612,22743,167,171,163,160,175],Ok=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ar(a,({tag:h,type:p,value:f,valueSize:b})=>{if(h===21419){let g=Je(f,p);l=ua(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Je(f,p):h===17545?i=Je(f,p):h===21420&&l===475249515?u=Je(f,p):h===374648427?ar(f,({tag:g,type:v,value:y})=>g===30321?(c=Je(y,v)===1,!1):!0):s&&n&&wg.includes(h)&&(o=!0),!o}),Wu(e,"Failed to parse webm Segment start"),Wu(t,"Failed to parse webm Segment end"),Wu(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Vk=a=>{if(Dk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},_k=(a,e)=>{let t=!1,r=!1,i=o=>Ag(o.time)&&Ag(o.position),s=[],n;return ar(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Je(l,u));break;case 183:break;case 241:n&&(n.position=Je(l,u));break;default:t&&wg.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Nk=a=>{let e=0,t=!1;try{ar(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Bk.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},kg={validateData:Pg,parseInit:Ok,getIndexRange:Vk,parseSegments:_k,parseFeedableSegmentChunk:Nk};var la=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return kg;case"mp4":return Ig}}throw new ReferenceError(`Unsupported mime type ${a}`)},Rg=a=>"getChunkEndTime"in a;var Zu=We(Jg(),1),iS=We(Nr(),1);var Xu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as eS,isNullable as tS}from"@vkontakte/videoplayer-shared";var Xg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Zg=a=>{var e;try{let t=vR(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function vR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
58
+ `}),p&&Ob(i,u,p,o)};var re=a=>new URL(a).hostname;import{assertNever as Hb,assertNonNullable as jb,combine as rk,debounce as ik,ErrorCategory as Gb,filter as Wb,filterChanged as ak,isNonNullable as Vu,map as _s,merge as Qb,observableFrom as sk,once as nk,Subscription as ok,ValueSubject as _u,videoQualityToHeight as uk,videoSizeToQuality as lk}from"@vkontakte/videoplayer-shared";var _b=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},ye=(a,e)=>w(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!_b(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return _b(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as Bs,isNullable as _w,assertNonNullable as Di}from"@vkontakte/videoplayer-shared";import{isNonNullable as Nb,assertNonNullable as Ds,now as Ow}from"@vkontakte/videoplayer-shared";function ie(){return Ow()}function Cu(a){return ie()-a}function Du(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Fb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Fr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Ds(c);let R=Cu(c),U;if(R<b){U=b-R,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,k()},T=R=>(s=R,_),y=R=>(d=R,_),S=()=>(p="json",_),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=R=>(h=R,_),k=()=>{c=ie(),n=new i,n.open("get",a);let R=0,U,L=0,W=()=>(Ds(c),Math.max(c,Math.max(U||0,L||0)));if(s&&n.addEventListener("progress",v=>{let $=ie();s.updateChunk&&v.loaded>R&&(s.updateChunk(W(),v.loaded-R),R=v.loaded,U=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Ds(n);let v=n.status;if(v>=200&&v<300){if(n.response.byteLength&&s){let $=n.response.byteLength-R;$&&s.updateChunk&&s.updateChunk(W(),$)}n.responseType==="json"&&!Object.values(n.response).length?I():(d&&d(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),h){let v=()=>{Ds(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(L=ie(),n.removeEventListener("readystatechange",v))};n.addEventListener("readystatechange",v)}return n.responseType=p,n.send(),_},_={withBitrateReporting:T,withParallel:E,withJSONResponse:S,withRetryCount:R=>(l=R,_),withRetryInterval:(R,U)=>(Nb(R)&&(b=R),Nb(U)&&(f=U),_),withTimeout:R=>(o=R,_),withFinally:y,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return _}var Mi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ci=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ie(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ie()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Fr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ie()}_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=ie();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as Nw}from"@vkontakte/videoplayer-shared";var Os=1e4,Bu=3;var Fw=6e4,Uw=10,qw=1,Hw=500,Bi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new Nw,this.chunkRateEstimator=new Mi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Du(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Du(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Bs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Fb(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ci(Bu,Os,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},h=(I,E,k)=>{u&&u.abort(),u=Fr(this.urlResolver.resolve(I,!1),E,k,()=>this._retryCallback()).withTimeout(Os).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Bu).withFinally(()=>{u=null}).send()},p=(I,E,k)=>{Di(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let k=ie()-1e4,B=0;for(let V=0;V<this.bufferStates.length;V++){let M=this.bufferStates[V];I=Math.min(I,M.buf),M.ts<k&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${I} drop=${B} jitter=${this.sourceJitter}`);let G=I-qw;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)}},T=I=>{let E,k=()=>E&&E.start?E.start.length:0,B=v=>E.start[v]/1e3,G=v=>E.dur[v]/1e3,V=v=>E.fragIndex+v,M=(v,$)=>({chunkIdx:V(v),startTS:B(v),dur:G(v),discontinuity:$}),_=()=>{let v=0;if(E&&E.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,N=$;this.sourceJitter>1&&(N+=this.sourceJitter-1);let ue=E.dur.length-1;for(;ue>=0&&(N-=E.dur[ue],!(N<=0));--ue);v=Math.min(ue,E.dur.length-1-Y),v=Math.max(v,0)}return M(v,!0)},R=v=>{let $=k();if(!($<=0)){if(Bs(v)){for(let Y=0;Y<$;Y++)if(B(Y)>v)return M(Y)}return _()}},U=v=>{let $=k(),Y=v?v.chunkIdx+1:0,N=Y-E.fragIndex;if(!($<=0)){if(!v||N<0||N-$>Uw)return t(`Resync: offset=${N} bChunks=${$} chunk=`+JSON.stringify(v)),_();if(!(N>=$))return M(Y-E.fragIndex,!1)}},L=(v,$,Y)=>{l&&l.abort(),l=Fr(this.urlResolver.resolve(v,!0,this.lowLatency),$,Y,()=>this._retryCallback()).withTimeout(Os).withRetryCount(Bu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(v,$)=>{L(I,Y=>{if(!d())return;E=Y;let N=!!E.lowLatency;N!==this.lowLatency&&b(N);let ue=0;for(let qe=0;qe<E.dur.length;++qe)ue+=E.dur[qe];ue>0&&(Di(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ue/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,v(R($))},()=>this._handleNetworkError())},nextChunk:U}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Di(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:k}=this.params,B=T(e.jidxUrl),G,V,M,_,R=0,U,L,W,v=()=>{U&&(clearTimeout(U),U=void 0);let H=Math.max(Hw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=R+H,xe=ie(),Me=Math.min(1e4,he-xe);R=xe;let gt=()=>{l||d()&&B.seek(()=>{d()&&(R=ie(),$(),v())})};Me>0?U=window.setTimeout(()=>{this.paused?v():gt()},Me):gt()},$=()=>{let H;for(;H=B.nextChunk(_);)_=H,dr(H);let he=B.nextChunk(M);if(he){if(M&&he.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?v():(y(),this._initPlayerWith(e));return}qe(he)}else v()},Y=(H,he)=>{if(!d()||!this.sourceBuffer)return;let xe,Me,gt,pr=St=>{window.setTimeout(()=>{d()&&Y(H,he)},St)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),pr(100);else{let St=ie(),Ft=E.currentTime;!this.paused&&E.buffered.length>1&&L===Ft&&St-W>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),L!==Ft&&(L=Ft,W=St);let hr=this._getBufferSizeSec();if(hr>30)k(`Buffered ${hr} seconds; delaying appendBuffer`),pr(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:hr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch(Jr){if(Jr.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),gt=this.sourceBuffer.buffered.length,gt!==0&&(xe=this.sourceBuffer.buffered.start(0),Me=Ft,Me-xe>4&&this.sourceBuffer.remove(xe,Me-3)),pr(1e3);else throw Jr}}},N=()=>{V&&G&&(k([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(M)]),Y(V,function(){V=null,$()}))},ue=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),qe=H=>{d()&&p(ue(H),(he,xe)=>{if(d()){if(xe/=1e3,V=he,M=H,n=H.startTS,xe){let Me=Math.min(10,H.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Me:Me}N()}},()=>this._handleNetworkError())},dr=H=>{d()&&(Di(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ue(H),!1)))},Kr=H=>{d()&&(e.cachedHeader=H,Y(H,()=>{G=!0,N()}))};s=!0,B.seek(H=>{if(d()){if(R=ie(),!H){v();return}_=H,!_w(I)||H.startTS>I?qe(H):(M=H,$())}},I),e.cachedHeader?Kr(e.cachedHeader):h(e.headerUrl,Kr,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Bs(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Di(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Bs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),f=d/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let f=ie();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Cu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ie();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Fr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Os).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;ye(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Fw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as jw,filter as Ub,fromEvent as Gw,interval as Ww,isHigher as Qw,isInvariantQuality as Yw,isLower as zw,merge as Kw,Subject as qb,Subscription as Jw}from"@vkontakte/videoplayer-shared";var Ou=class{constructor(){this.onDroopedVideoFramesLimit$=new qb;this.subscription=new Jw;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==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!Yw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Qw(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(Gw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Ww(this.droppedFramesChecker.checkTime).pipe(Ub(()=>this.playing),Ub(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(jw(this.droppedFramesChecker.checkTime)),r=Kw(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>zw(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Vs=Ou;import{map as Xw,Observable as Zw}from"@vkontakte/videoplayer-shared";import{fromEvent as ek}from"@vkontakte/videoplayer-shared";var Oi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var tk=(a,e)=>new Zw(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Oi()))},A(A({},r),e));i.observe(a);let s=ek(document,"visibilitychange").pipe(Xw(n=>!document.hidden||Oi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Fe=tk;var ck=["paused","playing","ready"],dk=["paused","playing","ready"],Vi=class{constructor(e){this.subscription=new ok;this.videoState=new C("stopped");this.representations$=new _u([]);this.textTracksManager=new _e;this.droppedFramesManager=new Vs;this.maxSeekBackTime$=new _u(1/0);this.zeroTime$=new _u(void 0);this.liveOffset=new dt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Gb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Rt(u.name))!=null?r:lk(u.video),d=u.bitrate/1e3,h=A({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Vu(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(dk.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&ck.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ne(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ne(this.params.source.url,u))}return;default:return Hb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Gb.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Qb(this.videoState.stateChangeStarted$.pipe(_s(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_s(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ve(this.video);this.subscription.add(this.representations$.pipe(_s(i=>i.map(({track:s})=>s)),Wb(i=>!!i.length),nk()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ak(),_s(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(rk({zeroTime:this.zeroTime$.pipe(Wb(Vu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(rt(this.video,this.params.desiredState.isLooped,t)).add(Se(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ve(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Fe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&uk(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Hb(i.to)}},t)).add(Qb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,sk(["init"])).pipe(ik(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ge(this.video)}createLiveDashPlayer(){let e=new Bi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Vu(t)?t:$t(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;jb(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;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(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ne(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Yb=Vi;var at=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as qR,assertNonNullable as HR,debounce as jR,ErrorCategory as ml,filter as ES,filterChanged as bl,fromEvent as GR,isNonNullable as WR,map as xS,merge as ln,observableFrom as QR,observeElementSize as YR,once as PS,Subscription as zR,ValueSubject as KR}from"@vkontakte/videoplayer-shared";var Ns=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Ur=class extends Ns{constructor(){super(),this.listeners||Ns.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)}},_i=class{constructor(){Object.defineProperty(this,"signal",{value:new Ur,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(_i.prototype[Symbol.toStringTag]="AbortController",Ur.prototype[Symbol.toStringTag]="AbortSignal");function Fs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Nu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Fs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Ni=Fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zb=Ni?Nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Ni?zb.fetch:window.fetch,rO=Ni?zb.Request:window.Request,ke=Ni?_i:window.AbortController,iO=Ni?Ur:window.AbortSignal;var zs=Ge(Nr(),1);var ft=()=>window.ManagedMediaSource||window.MediaSource,Us=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Kb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Jb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Js,clientChecker as Ks}from"@vkontakte/videoplayer-shared";var Ue=document.createElement("video"),fk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',mk='video/mp4; codecs="hev1.1.6.L93.B0"',ug='video/webm; codecs="vp09.00.10.08"',lg='video/webm; codecs="av01.0.00M.08"',bk='audio/mp4; codecs="mp4a.40.2"',gk='audio/webm; codecs="opus"',Xb,Zb,Fi={mms:Us(),mse:Kb(),hls:!!((Xb=Ue.canPlayType)!=null&&Xb.call(Ue,"application/x-mpegurl")||(Zb=Ue.canPlayType)!=null&&Zb.call(Ue,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},eg,tg,Te={mp4:!!((eg=Ue.canPlayType)!=null&&eg.call(Ue,"video/mp4")),webm:!!((tg=Ue.canPlayType)!=null&&tg.call(Ue,"video/webm")),cmaf:!0},Hs,rg,js,ig,Gs,ag,Ws,sg,Qs,ng,Ys,og,Ie={h264:!!((rg=(Hs=ft())==null?void 0:Hs.isTypeSupported)!=null&&rg.call(Hs,fk)),h265:!!((ig=(js=ft())==null?void 0:js.isTypeSupported)!=null&&ig.call(js,mk)),vp9:!!((ag=(Gs=ft())==null?void 0:Gs.isTypeSupported)!=null&&ag.call(Gs,ug)),av1:!!((sg=(Ws=ft())==null?void 0:Ws.isTypeSupported)!=null&&sg.call(Ws,lg)),aac:!!((ng=(Qs=ft())==null?void 0:Qs.isTypeSupported)!=null&&ng.call(Qs,bk)),opus:!!((og=(Ys=ft())==null?void 0:Ys.isTypeSupported)!=null&&og.call(Ys,gk))},qr=(Ie.h264||Ie.h265)&&Ie.aac,er,Sk=()=>w(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(D(A({},a),{video:D(A({},a.video),{contentType:lg})})),window.navigator.mediaCapabilities.decodingInfo(D(A({},a),{video:D(A({},a.video),{contentType:ug})}))]);er={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Sk()}catch(a){console.error(a)}var Hr=Fi.hls&&Te.mp4,cg=()=>Object.keys(Ie).filter(a=>Ie[a]),dg=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Fi.mse&&(!r||!!window.MediaStreamTrack)||Fi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Te.mp4&&qr;case"DASH_WEBM":return i&&Te.webm&&Ie.vp9&&Ie.opus;case"DASH_WEBM_AV1":return i&&Te.webm&&Ie.av1&&Ie.opus;case"DASH_STREAMS":return i&&(Te.mp4&&qr||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return i&&Te.mp4&&qr;case"DASH_LIVE_CMAF":return i&&Te.mp4&&qr&&Te.cmaf;case"DASH_ONDEMAND":return i&&Te.mp4&&qr;case"HLS":case"HLS_ONDEMAND":return Hr||e&&i&&Te.mp4&&qr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Hr;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Fi.webrtc&&Fi.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return Js(s)}})},qs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return er?er[t].smooth?[t,e]:er[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return er?er[t].powerEfficient?[t,e]:er[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Js(a)}return[e,t]},pg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...qs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Ks.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...qs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...qs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...qs(a),...i,"HLS","HLS_ONDEMAND"];default:Js(e)}return Hr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},hg=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=Ks.isMac&&Ks.isSafari;if(Ks.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Js(a)}else Hr&&!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"]},Fu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],fg=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,zs.default)(t.value.split("."),0)}for(let t of a){let r=(0,zs.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,zs.default)(e.value.split("."),0)};import{ErrorCategory as Ui}from"@vkontakte/videoplayer-shared";var mg=a=>{if(!a)return{id:"EmptyResponse",category:Ui.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ui.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ui.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ui.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ui.PARSER,message:"Response is valid XML, but parser failed"}};var Lt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as dl,assertNonNullable as or,clientChecker as LR,combine as an,ErrorCategory as Bt,filter as pl,filterChanged as gS,flattenObject as va,fromEvent as ur,getTraceSubscriptionMethod as MR,interval as hl,isNonNullable as SS,map as fl,merge as lr,now as CR,Subject as vS,Subscription as yS,tap as DR,throttle as BR,ValueSubject as oe}from"@vkontakte/videoplayer-shared";var Wr=Ge(Nr(),1);var vk=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},yk=a=>window.clearTimeout(a),bg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),gg=!bg(window.requestIdleCallback)||!bg(window.cancelIdleCallback),Uu=gg?vk:window.requestIdleCallback,SO=gg?yk:window.cancelIdleCallback;var lS=Ge($s(),1);import{assertNever as Tk,ErrorCategory as Sg,clientChecker as qu,Subject as vg}from"@vkontakte/videoplayer-shared";var Ik=18,yg=!1;try{yg=qu.isSafari&&!!qu.macVersion&&qu.macVersion<=Ik}catch(a){console.error(a)}var Hu=class{constructor(e){this.bufferFull$=new vg;this.error$=new vg;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Sg.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return w(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return w(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return w(this,null,function*(){return new Promise(t=>{let r;yg&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Sg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:Tk(t)}}},Tg=Hu;var ju=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as ar,assertNonNullable as ae,ErrorCategory as Ct,fromEvent as nl,getExponentialDelay as ol,isNonNullable as da,isNullable as $e,now as Xs,once as TR,Subject as IR,Subscription as ER,ValueSubject as pa}from"@vkontakte/videoplayer-shared";var j=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var jr=class extends j{};var qi=class extends j{};var Hi=class extends j{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ji=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var K=class extends j{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Gi=class extends K{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 Wi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Qi=class extends j{constructor(e,t){super(e,t),this.data=this.content}};var tr=class extends K{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Yi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ki=class extends K{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 Ji=class extends K{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Xi=class extends K{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Zi=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends K{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ta=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=class extends K{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var aa=class extends j{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends K{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 na=class extends K{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var oa=class extends K{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var xk={ftyp:Hi,moov:ji,mvhd:Gi,moof:Wi,mdat:Qi,sidx:tr,trak:Yi,mdia:Zi,mfhd:ia,tkhd:ea,traf:aa,tfhd:sa,tfdt:na,trun:oa,minf:ta,sv3d:zi,st3d:Ki,prhd:Ji,proj:ra,equi:Xi,uuid:qi,unknown:jr},Mt=class a{constructor(e={}){this.options=A({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=xk[e];return r?new r(t,new a):new jr(t,new a)}};var rr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Ak=new TextDecoder("ascii"),wk=a=>Ak.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",kk=a=>{let e=new tr(a,new Mt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Rk=(a,e)=>{let r=new Mt().parse(a),i=new rr(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},$k=a=>{var i;let t=new Mt().parse(a);return(i=new rr(t).find("sidx"))==null?void 0:i.timescale},Lk=(a,e)=>{let r=new Mt().parse(a),s=new rr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Mk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Mt().parse(a),i=new rr(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Ig={validateData:wk,parseInit:Mk,getIndexRange:()=>{},parseSegments:kk,parseFeedableSegmentChunk:Rk,getChunkEndTime:Lk,getTimescaleFromIndex:$k};import{assertNonNullable as Wu,isNonNullable as Ag,isNullable as Dk}from"@vkontakte/videoplayer-shared";import{assertNever as Ck}from"@vkontakte/videoplayer-shared";var Eg={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"}},xg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=ua(a,t),i=r in Eg,s=i?Eg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ua(u),d=l*et(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},ua=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*et(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*et(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*et(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ke=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ua(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:Ck(e)}},ir=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=xg(r);if(!e(i))return;i.type==="master"&&ir(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Pg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=xg(a);return ir(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ke(o,n):s===17026?t=Ke(o,n):s===17029&&(r=Ke(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var wg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Bk=[231,22612,22743,167,171,163,160,175],Ok=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ir(a,({tag:h,type:p,value:f,valueSize:b})=>{if(h===21419){let g=Ke(f,p);l=ua(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Ke(f,p):h===17545?i=Ke(f,p):h===21420&&l===475249515?u=Ke(f,p):h===374648427?ir(f,({tag:g,type:T,value:y})=>g===30321?(c=Ke(y,T)===1,!1):!0):s&&n&&wg.includes(h)&&(o=!0),!o}),Wu(e,"Failed to parse webm Segment start"),Wu(t,"Failed to parse webm Segment end"),Wu(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Vk=a=>{if(Dk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},_k=(a,e)=>{let t=!1,r=!1,i=o=>Ag(o.time)&&Ag(o.position),s=[],n;return ir(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ke(l,u));break;case 183:break;case 241:n&&(n.position=Ke(l,u));break;default:t&&wg.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Nk=a=>{let e=0,t=!1;try{ir(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Bk.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},kg={validateData:Pg,parseInit:Ok,getIndexRange:Vk,parseSegments:_k,parseFeedableSegmentChunk:Nk};var la=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return kg;case"mp4":return Ig}}throw new ReferenceError(`Unsupported mime type ${a}`)},Rg=a=>"getChunkEndTime"in a;var Zu=Ge(Jg(),1),iS=Ge(Nr(),1);var Xu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as eS,isNullable as tS}from"@vkontakte/videoplayer-shared";var Xg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Zg=a=>{var e;try{let t=vR(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function vR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
59
59
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
60
60
  (-(?<script>[a-z]{4}))?
61
61
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
62
62
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
63
63
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
64
64
  (?:-(?<privateuse>(?:${e})))?
65
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var rS=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},mt=(a,e)=>{let t=a;t=(0,Zu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Zu.default)(t,n,(o,u)=>tS(s)?o:tS(u)?s:s.padStart(parseInt(u,10),"0"))}return t},aS=(a,e)=>{var I,$,L,_,W,V,N,R,q,M,x,E,C,Y,F,se,He,Ft,Kr,j,he,xe,Me,gt,pr,St,Ut,hr,Jr,Ll,Ml,Cl,Dl,Bl,Ol,Vl,_l,Nl,Fl,Ul,ql,Hl,jl,Gl,Wl,Yl,Ql,zl,Kl,Jl,Xl,Zl,ec,tc,rc,ic,ac,sc,nc,oc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(ne=>{var Ca,vt;return(vt=(Ca=ne.textContent)==null?void 0:Ca.trim())!=null?vt:""}),u=(I=(0,iS.default)(o,0))!=null?I:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],v=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=rS(f);else if(b){let ne=rS(b);eS(ne)&&(p=ne)}else v&&(p=parseInt(v,10));let y=0,S=(L=($=s.getAttribute("profiles"))==null?void 0:$.split(","))!=null?L:[];for(let ne of l){let Ca=(_=ne.getAttribute("id"))!=null?_:"id"+(y++).toString(10),vt=(W=ne.getAttribute("mimeType"))!=null?W:"",En=(V=ne.getAttribute("codecs"))!=null?V:"",xn=(N=ne.getAttribute("contentType"))!=null?N:vt==null?void 0:vt.split("/")[0],gv=(q=(R=ne.getAttribute("profiles"))==null?void 0:R.split(","))!=null?q:[],uc=(x=Zg((M=ne.getAttribute("lang"))!=null?M:""))!=null?x:{},Sv=(Y=(C=(E=ne.querySelector("Label"))==null?void 0:E.textContent)==null?void 0:C.trim())!=null?Y:void 0,vv=ne.querySelectorAll("Representation"),yv=ne.querySelector("SegmentTemplate"),Tv=(se=(F=ne.querySelector("Role"))==null?void 0:F.getAttribute("value"))!=null?se:void 0,Xr=xn,ee={id:Ca,language:uc.language,isDefault:Tv==="main",label:Sv,codecs:En,hdr:Xr==="video"&&Xu(En),mime:vt,representations:[]};for(let z of vv){let Iv=(He=z.getAttribute("lang"))!=null?He:void 0,Ev=(Ft=z.getAttribute("label"))!=null?Ft:void 0,xv=(he=(j=(Kr=z.querySelector("BaseURL"))==null?void 0:Kr.textContent)==null?void 0:j.trim())!=null?he:"",Da=new URL(xv||u,e).toString(),fr=(xe=z.getAttribute("mimeType"))!=null?xe:vt,Ba=(gt=(Me=z.getAttribute("codecs"))!=null?Me:En)!=null?gt:"",Oa;if(xn==="text"){let yt=z.getAttribute("id")||"",Va=((pr=uc.privateuse)==null?void 0:pr.includes("x-auto"))||yt.includes("_auto"),qt=z.querySelector("SegmentTemplate");if(qt){let Zr={representationId:(St=z.getAttribute("id"))!=null?St:void 0,bandwidth:(Ut=z.getAttribute("bandwidth"))!=null?Ut:void 0},_a=parseInt((hr=z.getAttribute("bandwidth"))!=null?hr:"",10)/1e3,Na=(Ll=parseInt((Jr=qt.getAttribute("startNumber"))!=null?Jr:"",10))!=null?Ll:1,mr=parseInt((Ml=qt.getAttribute("timescale"))!=null?Ml:"",10),Pn=(Cl=qt.querySelectorAll("SegmentTimeline S"))!=null?Cl:[],br=qt.getAttribute("media");if(!br)continue;let Fa=[],Ua=0,qa="",gr=0,ei=Na,le=0;for(let je of Pn){let Ht=parseInt((Dl=je.getAttribute("d"))!=null?Dl:"",10),Ce=parseInt((Bl=je.getAttribute("r"))!=null?Bl:"",10)||0,Tt=parseInt((Ol=je.getAttribute("t"))!=null?Ol:"",10);le=Number.isFinite(Tt)?Tt:le;let jt=Ht/mr*1e3,It=le/mr*1e3;for(let Ze=0;Ze<Ce+1;Ze++){let Et=mt(br,B(w({},Zr),{segmentNumber:ei.toString(10),segmentTime:(le+Ze*Ht).toString(10)})),Sr=(It!=null?It:0)+Ze*jt,ri=Sr+jt;ei++,Fa.push({time:{from:Sr,to:ri},url:Et})}le+=(Ce+1)*Ht,Ua+=(Ce+1)*jt}gr=le/mr*1e3,qa=mt(br,B(w({},Zr),{segmentNumber:ei.toString(10),segmentTime:le.toString(10)}));let ti={time:{from:gr,to:1/0},url:qa},nt={type:"template",baseUrl:Da,segmentTemplateUrl:br,initUrl:"",totalSegmentsDurationMs:Ua,segments:Fa,nextSegmentBeyondManifest:ti,timescale:mr};Oa={id:yt,kind:"text",segmentReference:nt,profiles:[],duration:p,bitrate:_a,mime:"",codecs:"",width:0,height:0,isAuto:Va}}else Oa={id:yt,isAuto:Va,kind:"text",url:Da}}else{let yt=(_l=(Vl=z.getAttribute("contentType"))!=null?Vl:fr==null?void 0:fr.split("/")[0])!=null?_l:xn,Va=(Fl=(Nl=ne.getAttribute("profiles"))==null?void 0:Nl.split(","))!=null?Fl:[],qt=parseInt((Ul=z.getAttribute("width"))!=null?Ul:"",10),Zr=parseInt((ql=z.getAttribute("height"))!=null?ql:"",10),_a=parseInt((Hl=z.getAttribute("bandwidth"))!=null?Hl:"",10)/1e3,Na=(jl=z.getAttribute("frameRate"))!=null?jl:"",mr=(Gl=z.getAttribute("quality"))!=null?Gl:void 0,Pn=Na?Xg(Na):void 0,br=(Wl=z.getAttribute("id"))!=null?Wl:"id"+(y++).toString(10),Fa=yt==="video"?`${Zr}p`:yt==="audio"?`${_a}Kbps`:Ba,Ua=`${br}@${Fa}`,qa=[...S,...gv,...Va],gr,ei=z.querySelector("SegmentBase"),le=(Yl=z.querySelector("SegmentTemplate"))!=null?Yl:yv;if(ei){let nt=(zl=(Ql=z.querySelector("SegmentBase Initialization"))==null?void 0:Ql.getAttribute("range"))!=null?zl:"",[je,Ht]=nt.split("-").map(Et=>parseInt(Et,10)),Ce={from:je,to:Ht},Tt=(Kl=z.querySelector("SegmentBase"))==null?void 0:Kl.getAttribute("indexRange"),[jt,It]=Tt?Tt.split("-").map(Et=>parseInt(Et,10)):[],Ze=Tt?{from:jt,to:It}:void 0;gr={type:"byteRange",url:Da,initRange:Ce,indexRange:Ze}}else if(le){let nt={representationId:(Jl=z.getAttribute("id"))!=null?Jl:void 0,bandwidth:(Xl=z.getAttribute("bandwidth"))!=null?Xl:void 0},je=parseInt((Zl=le.getAttribute("timescale"))!=null?Zl:"",10),Ht=(ec=le.getAttribute("initialization"))!=null?ec:"",Ce=le.getAttribute("media"),Tt=(rc=parseInt((tc=le.getAttribute("startNumber"))!=null?tc:"",10))!=null?rc:1,jt=mt(Ht,nt);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");let It=(ic=le.querySelectorAll("SegmentTimeline S"))!=null?ic:[],Ze=[],Et=0,Sr="",ri=0;if(It.length){let Ha=Tt,Ge=0;for(let vr of It){let et=parseInt((ac=vr.getAttribute("d"))!=null?ac:"",10),Gt=parseInt((sc=vr.getAttribute("r"))!=null?sc:"",10)||0,ja=parseInt((nc=vr.getAttribute("t"))!=null?nc:"",10);Ge=Number.isFinite(ja)?ja:Ge;let An=et/je*1e3,wn=Ge/je*1e3;for(let Ga=0;Ga<Gt+1;Ga++){let Av=mt(Ce,B(w({},nt),{segmentNumber:Ha.toString(10),segmentTime:(Ge+Ga*et).toString(10)})),lc=(wn!=null?wn:0)+Ga*An,wv=lc+An;Ha++,Ze.push({time:{from:lc,to:wv},url:Av})}Ge+=(Gt+1)*et,Et+=(Gt+1)*An}ri=Ge/je*1e3,Sr=mt(Ce,B(w({},nt),{segmentNumber:Ha.toString(10),segmentTime:Ge.toString(10)}))}else if(eS(p)){let Ge=parseInt((oc=le.getAttribute("duration"))!=null?oc:"",10)/je*1e3,vr=Math.ceil(p/Ge),et=0;for(let Gt=1;Gt<vr;Gt++){let ja=mt(Ce,B(w({},nt),{segmentNumber:Gt.toString(10),segmentTime:et.toString(10)}));Ze.push({time:{from:et,to:et+Ge},url:ja}),et+=Ge}ri=et,Sr=mt(Ce,B(w({},nt),{segmentNumber:vr.toString(10),segmentTime:et.toString(10)}))}let Pv={time:{from:ri,to:1/0},url:Sr};gr={type:"template",baseUrl:Da,segmentTemplateUrl:Ce,initUrl:jt,totalSegmentsDurationMs:Et,segments:Ze,nextSegmentBeyondManifest:Pv,timescale:je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!yt||!fr)continue;let ti={video:"video",audio:"audio",text:"text"}[yt];if(!ti)continue;Xr||(Xr=ti),Oa={id:Ua,kind:ti,segmentReference:gr,profiles:qa,duration:p,bitrate:_a,mime:fr,codecs:Ba,width:qt,height:Zr,fps:Pn,quality:mr}}ee.language||(ee.language=Iv),ee.label||(ee.label=Ev),ee.mime||(ee.mime=fr),ee.codecs||(ee.codecs=Ba),ee.hdr||(ee.hdr=Xr==="video"&&Xu(Ba)),ee.representations.push(Oa)}Xr&&i[Xr].push(ee)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var rl=We(Nr(),1);import{videoSizeToQuality as yR}from"@vkontakte/videoplayer-shared";var sS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Rt(s):void 0)!=null?o:yR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},nS=({id:a,bitrate:e})=>({id:a,bitrate:e}),oS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),uS=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),il=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,rl.default)(r.split("."),0),isDefault:i}),al=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,rl.default)(i.split("."),0)}),sl=a=>"url"in a,Re=a=>a.type==="template",ca=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ha=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new pa(0);this.onLastSegment$=new pa(!1);this.fullyBuffered$=new pa(!1);this.playingRepresentation$=new pa(void 0);this.playingRepresentationInit$=new pa(void 0);this.error$=new IR;this.gaps=[];this.subscription=new ER;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ke;this.switchAbortController=new ke;this.destroyAbortController=new ke;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=sr(this.destroyAbortController.signal,function(e){return Z(this,null,function*(){let t=this.representations.get(e);ae(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Tg(this.sourceBuffer),this.subscription.add(nl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(nl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ct.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,ju(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=at(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ae(r,"No init buffer for starting representation"),ae(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=sr(this.destroyAbortController.signal,function(e,t=!1){return Z(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);ae(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if($e(s)||$e(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ae(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();da(n)&&(this.isLive||(this.bufferLimit=1/0,yield new $n(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=sr(this.destroyAbortController.signal,function(e){return Z(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Re(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);ae(i);let s=this.segments.get(r);ae(s,"No segments for starting representation");let n=this.initData.get(r);if(ae(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ke,sr(this.switchAbortController.signal,function(r,i=!1){return Z(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);ae(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if($e(o)||$e(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),ae(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();da(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ke,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if($e(e)||$e(this.downloadingRepresentationId)||$e(this.playingRepresentationId)||$e(this.sourceBuffer)||da(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ae(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=at(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&ju(this.sourceBuffer.buffered)>=this.bufferLimit){let d=at(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let h=(0,Wr.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&at(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Wr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;da(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Re(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>B(w({},h),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Wr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ae(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){var s;ae(this.playingRepresentationId);let e=(s=this.representations.get(this.playingRepresentationId))==null?void 0:s.duration;ae(e);let{shortVideoDuration:t,shortVideoBufferStallSizeMs:r,longVideoBufferStallSizeMs:i}=this.tuning.dash.accumulationBufferStallSize;this.bufferAccumulation={enabled:!1,targetBufferSizeMs:e<=t?r:i,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Re(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=mt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:h,to:p}},f)=>{let b=h<=r&&p>=r,g=h>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=r+v||p<=r+v;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&!(Lt(this.sourceBuffer.buffered,h)&&Lt(this.sourceBuffer.buffered,p)))&&g&&y});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,r="auto"){return k(this,null,function*(){Re(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return k(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield sr(o,function(){return Z(this,null,function*(){let c=ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Xs(),!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let h=t.segmentReference.timescale,p=la(t.mime);i.segment.time.to=p.getChunkEndTime(d,h)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),ca(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return k(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield sr(n,function(){return Z(this,null,function*(){let u=ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),nl(window,"online").pipe(TR()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=Xs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ca(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Re(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Wr.default)(e,0).byte.from,to:(0,Wr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Xs(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Re(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Xs();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return k(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=la(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return k(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,h=c.byte.to-r,p=h-d+1,f=d<i,b=h<=i;if(!f)continue;let g=la(u.mime),v=this.tuning.dash.enableSubSegmentBufferFeeding&&(Rg(g)||this.bufferAccumulation.targetBufferSizeMs===0);if(c.status==="downloading"&&b){c.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+d,p),S=this.getCurrentPosition();da(S)&&(this.bufferAccumulation.accumulatedBufferSizeMs=c.time.to-S,this.bufferAccumulation.accumulated.push({dataView:y,segmentProgress:l}),this.activeSegments.delete(l));let T=L=>k(this,[L],function*({dataView:I,segmentProgress:$}){(yield this.sourceBufferTaskQueue.append(I,s))&&!s.aborted?this.onSegmentFullyAppended($,t):n()});this.bufferAccumulation.enabled&&this.bufferAccumulation.accumulatedBufferSizeMs>this.bufferAccumulation.targetBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||$e(S))&&(T({dataView:y,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(v&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,i-d),l.loadedBytes>l.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?y:g.parseFeedableSegmentChunk(y);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&(ae(this.sourceBuffer),Lt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Lt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Ct.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",sl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");ae(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment]),this.tuning.useNewPruneBufferStrategy&&this.pruneBuffer(this.getCurrentPosition(),1/0,!1)}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Uu(()=>(0,lS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return k(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?sr(this.destroyAbortController.signal,function(){return Z(this,null,function*(){let o=ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,la(e.mime),i)).then(o=>k(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Re(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ct.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return k(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return k(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||$e(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(w({},u.time)),i=n(i);let l=sl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||$e(e)?0:at(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){ae(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Uu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ct.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if($e(this.sourceBuffer)||$e(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var fa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var cS=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as ma,assertNever as pS,fromEvent as hS,merge as xR,now as ba,Subscription as PR,ValueSubject as ul,flattenObject as Yr}from"@vkontakte/videoplayer-shared";var dS=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Zs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new ul(void 0);this.lastConnectionReused$=new ul(void 0);this.lastRequestFirstBytes$=new ul(void 0);this.abortAllController=new ke;this.subscription=new PR;this.fetchManifest=ma(this.abortAllController.signal,function(e){return Z(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=fa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=dS(r));let i=yield ht(r,{signal:this.abortAllController.signal}).catch(ga);return i?(t.log("success",Yr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Yr({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=ma(this.abortAllController.signal,function(l){return Z(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,q;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let M=new URL(c,location.href);M.searchParams.append("bytes",`${r.from}-${r.to}`),c=M.toString();break}default:pS(t)}this.requestQuic&&(c=fa(c));let p=this.abortAllController.signal,f;if(n){let M=new ke;if(f=xR(hS(this.abortAllController.signal,"abort"),hS(n,"abort")).subscribe(()=>{try{M.abort()}catch(x){ga(x)}}),this.abortAllController.signal.aborted||n.aborted)try{M.abort()}catch(x){ga(x)}p=M.signal}let b=ba();h.log("startRequest",Yr({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield ht(c,{priority:s,headers:d,signal:p}).catch(ga),v=ba();if(!g)return h.error("error",{message:"No response in request"}),h.end(),f==null||f.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(v-b),!g.ok||!g.body){f==null||f.unsubscribe();let M=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:M}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let M=ba(),x={requestStartedAt:b,requestEndedAt:M,duration:M-b};return h.log("endRequest",Yr(x)),h.end(),g.arrayBuffer()}let[y,S]=g.body.tee(),T=y.getReader();o&&((q=this.throughputEstimator)==null||q.trackStream(S,u));let I=0,$=new Uint8Array(0),L=!1,_=M=>{f==null||f.unsubscribe(),L=!0,ga(M)},W=ma(p,function(E){return Z(this,arguments,function*({done:M,value:x}){if(I===0&&this.lastRequestFirstBytes$.next(ba()-b),p.aborted){f==null||f.unsubscribe();return}if(!M&&x){let C=new Uint8Array($.length+x.length);C.set($),C.set(x,$.length),$=C,I+=x.byteLength,i==null||i(new DataView($.buffer),I),yield T==null?void 0:T.read().then(W,_)}})}.bind(this));yield T==null?void 0:T.read().then(W,_),f==null||f.unsubscribe();let V=ba(),N={failed:L,requestStartedAt:b,requestEndedAt:V,duration:V-b};return L?(h.error("endRequest",Yr(N)),h.end(),null):(h.log("endRequest",Yr(N)),h.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=ma(this.abortAllController.signal,function(e,t,r){return Z(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(v=e.indexRange)!=null?v:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let y=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let g=t.parseSegments(b,p,f);return{init:p,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=ma(this.abortAllController.signal,function(e,t){return Z(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>B(w({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=cS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return k(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:pS(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ga=a=>{if(!ca(a))throw a};var nr=(a,e,t)=>t*e+(1-t)*a,ll=(a,e)=>a.reduce((t,r)=>t+r,0)/e,fS=(a,e,t,r)=>{let i=0,s=t,n=ll(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as AR,ValueSubject as mS}from"@vkontakte/videoplayer-shared";var Dt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new mS(e.initial),this.debounced$=new mS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new de(`raw_${t}`),this.smoothedSeries$=new de(`smoothed_${t}`),this.reportedSeries$=new de(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=De(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(AR(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 en=class extends Dt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=nr(this.slow,e,this.params.emaAlphaSlow),this.fast=nr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var tn=class extends Dt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ll(this.pastMeasures,this.takenMeasures);this.emaSmoothed=nr(this.emaSmoothed,e,this.params.emaAlpha);let r=fS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var rn=class extends Dt{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?nr(this.smoothed,t,this.params.emaAlpha):t}};var or=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new en({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new tn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new rn(w({initial:e,label:"liveEdgeDelay"},t))}};var cl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as wR,ValueSubject as kR}from"@vkontakte/videoplayer-shared";var Sa=class a{constructor(e,t){this.currentRepresentation$=new kR(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!wR(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(B(w({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Re(t.segmentReference))}};var OR=["timeupdate","progress","play","seeked","stalled","waiting"],VR=["timeupdate","progress","loadeddata","playing","seeked"];var sn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new yS;this.representationSubscription=new yS;this.state$=new D("none");this.currentVideoRepresentation$=new ue(void 0);this.currentVideoRepresentationInit$=new ue(void 0);this.currentAudioRepresentation$=new ue(void 0);this.currentVideoSegmentLength$=new ue(0);this.currentAudioSegmentLength$=new ue(0);this.error$=new vS;this.lastConnectionType$=new ue(void 0);this.lastConnectionReused$=new ue(void 0);this.lastRequestFirstBytes$=new ue(void 0);this.currentLiveTextRepresentation$=new ue(null);this.isLive$=new ue(!1);this.liveDuration$=new ue(0);this.liveAvailabilityStartTime$=new ue(void 0);this.bufferLength$=new ue(0);this.liveLoadBufferLength$=new ue(0);this.livePositionFromPlayer$=new ue(0);this.isActiveLowLatency$=new ue(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new vS;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=dl(this.destroyController.signal,function(e,t,r){return Z(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=oe(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Bt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=dl(this.destroyController.signal,function(){return Z(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Bt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=aS(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=mg(e))!=null?n:{id:"ManifestParsing",category:Bt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,h,p,f;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((f=(p=ft())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:f})=>r(u,p,f)),d=new Set(c.map(({codecs:p})=>p)),h=fg(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);LR.isHDR&&p&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=B(w({},t),{streams:i});return this.tracer.log("updateManifestEnd",va(s)),s})}.bind(this));this.initRepresentations=dl(this.destroyController.signal,function(e,t,r){return Z(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",va({initialVideo:e,initialAudio:t,sourceHls:r})),ur(this.manifest),ur(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(lr(p,"error").pipe(pl(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Bt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Jb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Us())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new ha("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],SS(t)){let p=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new ha("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Sa.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(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(hl(1e3).subscribe(p=>{var f;if((f=this.element)!=null&&f.paused){let b=yu(this.manifestUrlString,2);this.manifestUrlString=oe(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.timeInWaiting=0};if(this.representationSubscription.add(cr(...VR.map(p=>lr(this.element,p))).pipe(fl(p=>this.element?at(this.element.buffered,this.element.currentTime*1e3):0),gS(),DR(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(cr(lr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(gS()).subscribe(f=>cl(this.element,1))),this.representationSubscription.add(an({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(pl(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveEstimatedDelay.next(f))),this.representationSubscription.add(an({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=f-g,T=1;Math.abs(S)>v&&(T=1+Math.sign(S)*y),cl(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,v;let b=0;if(f){let y=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(T=>{var I,$;return($=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?$:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(an({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(BR(1e3)).subscribe(g=>k(this,[g],function*({liveLoadBufferLength:f,bufferLength:b}){if(ur(this.element),this.isUpdatingLive)return;let v=this.element.playbackRate,y=yu(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,L=isFinite(f)?f:b,_=this.isActiveLowLatency$.getValue(),W=S<=this.tuning.live.activeLiveDelay&&y===0;this.isActiveLowLatency$.next(_&&W);let V="none";if(_?V="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&W?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(N=>N.proceedLowLatencyLive()),V="active_low_latency"):y!==0&&L<T?V="live_forward_buffering":L<T+$&&(V="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),V==="live_forward_buffering"||V==="live_with_target_offset"){let N=p-(T+I),R=this.normolizeLiveOffset(Math.trunc(y+N/v)),q=Math.abs(R-y),M;!f||q<=this.tuning.dashCmafLive.offsetCalculationError?M=y:R>0&&q>this.tuning.dashCmafLive.offsetCalculationError?M=R:M=0,this.manifestUrlString=oe(this.manifestUrlString,M,2)}V!=="none"&&V!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=cr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(fl(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=cr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(fl(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(cr(this.forceEnded$,an({allBuffersFull:l,someBufferEnded:c}).pipe(pl(({allBuffersFull:p,someBufferEnded:f})=>p&&f))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Bt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(cr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let f=[];return p.duration&&f.push(p.duration),Re(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&SS(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=hl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Bt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Zs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveEstimatedDelay=or.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,w({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return k(this,null,function*(){var r,i,s;ur(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=oe(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){ur(this.element),this.state$.setState("running"),this.subscription.add(cr(...OR.map(e=>lr(this.element,e)),lr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Bt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(lr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(lr(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Lt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var f,b,g,v,y,S,T,I,$,L;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=CR(),o=100,u=(b=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?b:0,l=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,c=(S=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?S:0,d=(I=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?I:0,h=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&this.timeInWaiting>this.tuning.dash.crashOnStallTWithoutDataTimeout||this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.timeInWaiting} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s.liveLastSeekOffset=this.liveLastSeekOffset;else{let _=this.element.currentTime*1e3;($=this.videoBufferManager)==null||$.maintain(_),(L=this.audioBufferManager)==null||L.maintain(_),s.position=_}this.tracer.log("stallIntervalCallback",va(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=hl(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Bt.NETWORK,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return k(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u,l;ur(this.element),ur(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Lt(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",va({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=MR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return k(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=B(w({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",va(t)))}}};var nn=class{constructor(e,t){this.fov=e,this.orientation=t}};var on=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/De(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=w({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*De(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var TS=`attribute vec2 a_vertex;
65
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var rS=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},mt=(a,e)=>{let t=a;t=(0,Zu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Zu.default)(t,n,(o,u)=>tS(s)?o:tS(u)?s:s.padStart(parseInt(u,10),"0"))}return t},aS=(a,e)=>{var E,k,B,G,V,M,_,R,U,L,W,v,$,Y,N,ue,qe,dr,Kr,H,he,xe,Me,gt,pr,St,Ft,hr,Jr,Ll,Ml,Cl,Dl,Bl,Ol,Vl,_l,Nl,Fl,Ul,ql,Hl,jl,Gl,Wl,Ql,Yl,zl,Kl,Jl,Xl,Zl,ec,tc,rc,ic,ac,sc,nc,oc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(se=>{var Ca,vt;return(vt=(Ca=se.textContent)==null?void 0:Ca.trim())!=null?vt:""}),u=(E=(0,iS.default)(o,0))!=null?E:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],T=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=rS(f);else if(b){let se=rS(b);eS(se)&&(p=se)}else T&&(p=parseInt(T,10));let y=0,S=(B=(k=s.getAttribute("profiles"))==null?void 0:k.split(","))!=null?B:[];for(let se of l){let Ca=(G=se.getAttribute("id"))!=null?G:"id"+(y++).toString(10),vt=(V=se.getAttribute("mimeType"))!=null?V:"",En=(M=se.getAttribute("codecs"))!=null?M:"",xn=(_=se.getAttribute("contentType"))!=null?_:vt==null?void 0:vt.split("/")[0],gv=(U=(R=se.getAttribute("profiles"))==null?void 0:R.split(","))!=null?U:[],uc=(W=Zg((L=se.getAttribute("lang"))!=null?L:""))!=null?W:{},Sv=(Y=($=(v=se.querySelector("Label"))==null?void 0:v.textContent)==null?void 0:$.trim())!=null?Y:void 0,vv=se.querySelectorAll("Representation"),yv=se.querySelector("SegmentTemplate"),Tv=(ue=(N=se.querySelector("Role"))==null?void 0:N.getAttribute("value"))!=null?ue:void 0,Xr=xn,ee={id:Ca,language:uc.language,isDefault:Tv==="main",label:Sv,codecs:En,hdr:Xr==="video"&&Xu(En),mime:vt,representations:[]};for(let z of vv){let Iv=(qe=z.getAttribute("lang"))!=null?qe:void 0,Ev=(dr=z.getAttribute("label"))!=null?dr:void 0,xv=(he=(H=(Kr=z.querySelector("BaseURL"))==null?void 0:Kr.textContent)==null?void 0:H.trim())!=null?he:"",Da=new URL(xv||u,e).toString(),fr=(xe=z.getAttribute("mimeType"))!=null?xe:vt,Ba=(gt=(Me=z.getAttribute("codecs"))!=null?Me:En)!=null?gt:"",Oa;if(xn==="text"){let yt=z.getAttribute("id")||"",Va=((pr=uc.privateuse)==null?void 0:pr.includes("x-auto"))||yt.includes("_auto"),Ut=z.querySelector("SegmentTemplate");if(Ut){let Zr={representationId:(St=z.getAttribute("id"))!=null?St:void 0,bandwidth:(Ft=z.getAttribute("bandwidth"))!=null?Ft:void 0},_a=parseInt((hr=z.getAttribute("bandwidth"))!=null?hr:"",10)/1e3,Na=(Ll=parseInt((Jr=Ut.getAttribute("startNumber"))!=null?Jr:"",10))!=null?Ll:1,mr=parseInt((Ml=Ut.getAttribute("timescale"))!=null?Ml:"",10),Pn=(Cl=Ut.querySelectorAll("SegmentTimeline S"))!=null?Cl:[],br=Ut.getAttribute("media");if(!br)continue;let Fa=[],Ua=0,qa="",gr=0,ei=Na,le=0;for(let He of Pn){let qt=parseInt((Dl=He.getAttribute("d"))!=null?Dl:"",10),Ce=parseInt((Bl=He.getAttribute("r"))!=null?Bl:"",10)||0,Tt=parseInt((Ol=He.getAttribute("t"))!=null?Ol:"",10);le=Number.isFinite(Tt)?Tt:le;let Ht=qt/mr*1e3,It=le/mr*1e3;for(let Xe=0;Xe<Ce+1;Xe++){let Et=mt(br,D(A({},Zr),{segmentNumber:ei.toString(10),segmentTime:(le+Xe*qt).toString(10)})),Sr=(It!=null?It:0)+Xe*Ht,ri=Sr+Ht;ei++,Fa.push({time:{from:Sr,to:ri},url:Et})}le+=(Ce+1)*qt,Ua+=(Ce+1)*Ht}gr=le/mr*1e3,qa=mt(br,D(A({},Zr),{segmentNumber:ei.toString(10),segmentTime:le.toString(10)}));let ti={time:{from:gr,to:1/0},url:qa},nt={type:"template",baseUrl:Da,segmentTemplateUrl:br,initUrl:"",totalSegmentsDurationMs:Ua,segments:Fa,nextSegmentBeyondManifest:ti,timescale:mr};Oa={id:yt,kind:"text",segmentReference:nt,profiles:[],duration:p,bitrate:_a,mime:"",codecs:"",width:0,height:0,isAuto:Va}}else Oa={id:yt,isAuto:Va,kind:"text",url:Da}}else{let yt=(_l=(Vl=z.getAttribute("contentType"))!=null?Vl:fr==null?void 0:fr.split("/")[0])!=null?_l:xn,Va=(Fl=(Nl=se.getAttribute("profiles"))==null?void 0:Nl.split(","))!=null?Fl:[],Ut=parseInt((Ul=z.getAttribute("width"))!=null?Ul:"",10),Zr=parseInt((ql=z.getAttribute("height"))!=null?ql:"",10),_a=parseInt((Hl=z.getAttribute("bandwidth"))!=null?Hl:"",10)/1e3,Na=(jl=z.getAttribute("frameRate"))!=null?jl:"",mr=(Gl=z.getAttribute("quality"))!=null?Gl:void 0,Pn=Na?Xg(Na):void 0,br=(Wl=z.getAttribute("id"))!=null?Wl:"id"+(y++).toString(10),Fa=yt==="video"?`${Zr}p`:yt==="audio"?`${_a}Kbps`:Ba,Ua=`${br}@${Fa}`,qa=[...S,...gv,...Va],gr,ei=z.querySelector("SegmentBase"),le=(Ql=z.querySelector("SegmentTemplate"))!=null?Ql:yv;if(ei){let nt=(zl=(Yl=z.querySelector("SegmentBase Initialization"))==null?void 0:Yl.getAttribute("range"))!=null?zl:"",[He,qt]=nt.split("-").map(Et=>parseInt(Et,10)),Ce={from:He,to:qt},Tt=(Kl=z.querySelector("SegmentBase"))==null?void 0:Kl.getAttribute("indexRange"),[Ht,It]=Tt?Tt.split("-").map(Et=>parseInt(Et,10)):[],Xe=Tt?{from:Ht,to:It}:void 0;gr={type:"byteRange",url:Da,initRange:Ce,indexRange:Xe}}else if(le){let nt={representationId:(Jl=z.getAttribute("id"))!=null?Jl:void 0,bandwidth:(Xl=z.getAttribute("bandwidth"))!=null?Xl:void 0},He=parseInt((Zl=le.getAttribute("timescale"))!=null?Zl:"",10),qt=(ec=le.getAttribute("initialization"))!=null?ec:"",Ce=le.getAttribute("media"),Tt=(rc=parseInt((tc=le.getAttribute("startNumber"))!=null?tc:"",10))!=null?rc:1,Ht=mt(qt,nt);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");let It=(ic=le.querySelectorAll("SegmentTimeline S"))!=null?ic:[],Xe=[],Et=0,Sr="",ri=0;if(It.length){let Ha=Tt,je=0;for(let vr of It){let Ze=parseInt((ac=vr.getAttribute("d"))!=null?ac:"",10),jt=parseInt((sc=vr.getAttribute("r"))!=null?sc:"",10)||0,ja=parseInt((nc=vr.getAttribute("t"))!=null?nc:"",10);je=Number.isFinite(ja)?ja:je;let An=Ze/He*1e3,wn=je/He*1e3;for(let Ga=0;Ga<jt+1;Ga++){let Av=mt(Ce,D(A({},nt),{segmentNumber:Ha.toString(10),segmentTime:(je+Ga*Ze).toString(10)})),lc=(wn!=null?wn:0)+Ga*An,wv=lc+An;Ha++,Xe.push({time:{from:lc,to:wv},url:Av})}je+=(jt+1)*Ze,Et+=(jt+1)*An}ri=je/He*1e3,Sr=mt(Ce,D(A({},nt),{segmentNumber:Ha.toString(10),segmentTime:je.toString(10)}))}else if(eS(p)){let je=parseInt((oc=le.getAttribute("duration"))!=null?oc:"",10)/He*1e3,vr=Math.ceil(p/je),Ze=0;for(let jt=1;jt<vr;jt++){let ja=mt(Ce,D(A({},nt),{segmentNumber:jt.toString(10),segmentTime:Ze.toString(10)}));Xe.push({time:{from:Ze,to:Ze+je},url:ja}),Ze+=je}ri=Ze,Sr=mt(Ce,D(A({},nt),{segmentNumber:vr.toString(10),segmentTime:Ze.toString(10)}))}let Pv={time:{from:ri,to:1/0},url:Sr};gr={type:"template",baseUrl:Da,segmentTemplateUrl:Ce,initUrl:Ht,totalSegmentsDurationMs:Et,segments:Xe,nextSegmentBeyondManifest:Pv,timescale:He}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!yt||!fr)continue;let ti={video:"video",audio:"audio",text:"text"}[yt];if(!ti)continue;Xr||(Xr=ti),Oa={id:Ua,kind:ti,segmentReference:gr,profiles:qa,duration:p,bitrate:_a,mime:fr,codecs:Ba,width:Ut,height:Zr,fps:Pn,quality:mr}}ee.language||(ee.language=Iv),ee.label||(ee.label=Ev),ee.mime||(ee.mime=fr),ee.codecs||(ee.codecs=Ba),ee.hdr||(ee.hdr=Xr==="video"&&Xu(Ba)),ee.representations.push(Oa)}Xr&&i[Xr].push(ee)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var rl=Ge(Nr(),1);import{videoSizeToQuality as yR}from"@vkontakte/videoplayer-shared";var sS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Rt(s):void 0)!=null?o:yR({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},nS=({id:a,bitrate:e})=>({id:a,bitrate:e}),oS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),uS=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),il=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,rl.default)(r.split("."),0),isDefault:i}),al=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,rl.default)(i.split("."),0)}),sl=a=>"url"in a,Re=a=>a.type==="template",ca=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ha=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new pa(0);this.onLastSegment$=new pa(!1);this.fullyBuffered$=new pa(!1);this.playingRepresentation$=new pa(void 0);this.playingRepresentationInit$=new pa(void 0);this.error$=new IR;this.gaps=[];this.subscription=new ER;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ke;this.switchAbortController=new ke;this.destroyAbortController=new ke;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=ar(this.destroyAbortController.signal,function(e){return Z(this,null,function*(){let t=this.representations.get(e);ae(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Tg(this.sourceBuffer),this.subscription.add(nl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ct.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(nl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ct.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,ju(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=at(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ae(r,"No init buffer for starting representation"),ae(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=ar(this.destroyAbortController.signal,function(e,t=!1){return Z(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);ae(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if($e(s)||$e(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ae(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();da(n)&&(this.isLive||(this.bufferLimit=1/0,yield new $n(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=ar(this.destroyAbortController.signal,function(e){return Z(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Re(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);ae(i);let s=this.segments.get(r);ae(s,"No segments for starting representation");let n=this.initData.get(r);if(ae(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ke,ar(this.switchAbortController.signal,function(r,i=!1){return Z(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);ae(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if($e(o)||$e(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),ae(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();da(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ke,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if($e(e)||$e(this.downloadingRepresentationId)||$e(this.playingRepresentationId)||$e(this.sourceBuffer)||da(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ae(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=at(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&ju(this.sourceBuffer.buffered)>=this.bufferLimit){let d=at(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let h=(0,Wr.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&at(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Wr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;da(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Re(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>D(A({},h),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,Wr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ae(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){var s;ae(this.playingRepresentationId);let e=(s=this.representations.get(this.playingRepresentationId))==null?void 0:s.duration;ae(e);let{shortVideoDuration:t,shortVideoBufferStallSizeMs:r,longVideoBufferStallSizeMs:i}=this.tuning.dash.accumulationBufferStallSize;this.bufferAccumulation={enabled:!1,targetBufferSizeMs:e<=t?r:i,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Re(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=mt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:h,to:p}},f)=>{let b=h<=r&&p>=r,g=h>r||b||f===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=r+T||p<=r+T;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&!(Lt(this.sourceBuffer.buffered,h)&&Lt(this.sourceBuffer.buffered,p)))&&g&&y});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,r="auto"){return w(this,null,function*(){Re(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return w(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield ar(o,function(){return Z(this,null,function*(){let c=ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Xs(),!c)return;let d=new DataView(c);if(!isFinite(i.segment.time.to)){let h=t.segmentReference.timescale,p=la(t.mime);i.segment.time.to=p.getChunkEndTime(d,h)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),ca(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return w(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield ar(n,function(){return Z(this,null,function*(){let u=ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),nl(window,"online").pipe(TR()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=Xs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ca(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Re(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Wr.default)(e,0).byte.from,to:(0,Wr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Xs(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Re(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Xs();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Ct.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return w(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=la(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return w(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,h=c.byte.to-r,p=h-d+1,f=d<i,b=h<=i;if(!f)continue;let g=la(u.mime),T=this.tuning.dash.enableSubSegmentBufferFeeding&&(Rg(g)||this.bufferAccumulation.targetBufferSizeMs===0);if(c.status==="downloading"&&b){c.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+d,p),S=this.getCurrentPosition();da(S)&&(this.bufferAccumulation.accumulatedBufferSizeMs=c.time.to-S,this.bufferAccumulation.accumulated.push({dataView:y,segmentProgress:l}),this.activeSegments.delete(l));let I=B=>w(this,[B],function*({dataView:E,segmentProgress:k}){(yield this.sourceBufferTaskQueue.append(E,s))&&!s.aborted?this.onSegmentFullyAppended(k,t):n()});this.bufferAccumulation.enabled&&this.bufferAccumulation.accumulatedBufferSizeMs>this.bufferAccumulation.targetBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(I),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||$e(S))&&(I({dataView:y,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(T&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,i-d),l.loadedBytes>l.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?y:g.parseFeedableSegmentChunk(y);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&(ae(this.sourceBuffer),Lt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Lt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Ct.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",sl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");ae(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment]),this.tuning.useNewPruneBufferStrategy&&this.pruneBuffer(this.getCurrentPosition(),1/0,!1)}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Uu(()=>(0,lS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return w(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?ar(this.destroyAbortController.signal,function(){return Z(this,null,function*(){let o=ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,la(e.mime),i)).then(o=>w(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Re(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ct.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return w(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return w(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||$e(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(A({},u.time)),i=n(i);let l=sl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)["none","partially_ejected"].includes(p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||$e(e)?0:at(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){ae(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Uu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ct.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if($e(this.sourceBuffer)||$e(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var fa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var cS=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as ma,assertNever as pS,fromEvent as hS,merge as xR,now as ba,Subscription as PR,ValueSubject as ul,flattenObject as Qr}from"@vkontakte/videoplayer-shared";var dS=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Zs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new ul(void 0);this.lastConnectionReused$=new ul(void 0);this.lastRequestFirstBytes$=new ul(void 0);this.abortAllController=new ke;this.subscription=new PR;this.fetchManifest=ma(this.abortAllController.signal,function(e){return Z(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=fa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=dS(r));let i=yield ht(r,{signal:this.abortAllController.signal}).catch(ga);return i?(t.log("success",Qr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Qr({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=ma(this.abortAllController.signal,function(l){return Z(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,U;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:pS(t)}this.requestQuic&&(c=fa(c));let p=this.abortAllController.signal,f;if(n){let L=new ke;if(f=xR(hS(this.abortAllController.signal,"abort"),hS(n,"abort")).subscribe(()=>{try{L.abort()}catch(W){ga(W)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(W){ga(W)}p=L.signal}let b=ba();h.log("startRequest",Qr({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield ht(c,{priority:s,headers:d,signal:p}).catch(ga),T=ba();if(!g)return h.error("error",{message:"No response in request"}),h.end(),f==null||f.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(T-b),!g.ok||!g.body){f==null||f.unsubscribe();let L=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:L}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let L=ba(),W={requestStartedAt:b,requestEndedAt:L,duration:L-b};return h.log("endRequest",Qr(W)),h.end(),g.arrayBuffer()}let[y,S]=g.body.tee(),I=y.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(S,u));let E=0,k=new Uint8Array(0),B=!1,G=L=>{f==null||f.unsubscribe(),B=!0,ga(L)},V=ma(p,function(v){return Z(this,arguments,function*({done:L,value:W}){if(E===0&&this.lastRequestFirstBytes$.next(ba()-b),p.aborted){f==null||f.unsubscribe();return}if(!L&&W){let $=new Uint8Array(k.length+W.length);$.set(k),$.set(W,k.length),k=$,E+=W.byteLength,i==null||i(new DataView(k.buffer),E),yield I==null?void 0:I.read().then(V,G)}})}.bind(this));yield I==null?void 0:I.read().then(V,G),f==null||f.unsubscribe();let M=ba(),_={failed:B,requestStartedAt:b,requestEndedAt:M,duration:M-b};return B?(h.error("endRequest",Qr(_)),h.end(),null):(h.log("endRequest",Qr(_)),h.end(),k.buffer)})}.bind(this));this.fetchByteRangeRepresentation=ma(this.abortAllController.signal,function(e,t,r){return Z(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(T=e.indexRange)!=null?T:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let y=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let g=t.parseSegments(b,p,f);return{init:p,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=ma(this.abortAllController.signal,function(e,t){return Z(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>D(A({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=cS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return w(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:pS(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ga=a=>{if(!ca(a))throw a};var sr=(a,e,t)=>t*e+(1-t)*a,ll=(a,e)=>a.reduce((t,r)=>t+r,0)/e,fS=(a,e,t,r)=>{let i=0,s=t,n=ll(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as AR,ValueSubject as mS}from"@vkontakte/videoplayer-shared";var Dt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new mS(e.initial),this.debounced$=new mS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new de(`raw_${t}`),this.smoothedSeries$=new de(`smoothed_${t}`),this.reportedSeries$=new de(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=et(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(AR(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 en=class extends Dt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=sr(this.slow,e,this.params.emaAlphaSlow),this.fast=sr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var tn=class extends Dt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ll(this.pastMeasures,this.takenMeasures);this.emaSmoothed=sr(this.emaSmoothed,e,this.params.emaAlpha);let r=fS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var rn=class extends Dt{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?sr(this.smoothed,t,this.params.emaAlpha):t}};var nr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new en({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new tn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new rn(A({initial:e,label:"liveEdgeDelay"},t))}};var cl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as wR,ValueSubject as kR}from"@vkontakte/videoplayer-shared";var Sa=class a{constructor(e,t){this.currentRepresentation$=new kR(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!wR(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(D(A({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Re(t.segmentReference))}};var OR=["timeupdate","progress","play","seeked","stalled","waiting"],VR=["timeupdate","progress","loadeddata","playing","seeked"];var sn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new yS;this.representationSubscription=new yS;this.state$=new C("none");this.currentVideoRepresentation$=new oe(void 0);this.currentVideoRepresentationInit$=new oe(void 0);this.currentAudioRepresentation$=new oe(void 0);this.currentVideoSegmentLength$=new oe(0);this.currentAudioSegmentLength$=new oe(0);this.error$=new vS;this.lastConnectionType$=new oe(void 0);this.lastConnectionReused$=new oe(void 0);this.lastRequestFirstBytes$=new oe(void 0);this.currentLiveTextRepresentation$=new oe(null);this.isLive$=new oe(!1);this.liveDuration$=new oe(0);this.liveAvailabilityStartTime$=new oe(void 0);this.bufferLength$=new oe(0);this.liveLoadBufferLength$=new oe(0);this.livePositionFromPlayer$=new oe(0);this.isActiveLowLatency$=new oe(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new vS;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=dl(this.destroyController.signal,function(e,t,r){return Z(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Bt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=dl(this.destroyController.signal,function(){return Z(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Bt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=aS(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=mg(e))!=null?n:{id:"ManifestParsing",category:Bt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,h,p,f;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((f=(p=ft())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:f})=>r(u,p,f)),d=new Set(c.map(({codecs:p})=>p)),h=fg(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);LR.isHDR&&p&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=D(A({},t),{streams:i});return this.tracer.log("updateManifestEnd",va(s)),s})}.bind(this));this.initRepresentations=dl(this.destroyController.signal,function(e,t,r){return Z(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",va({initialVideo:e,initialAudio:t,sourceHls:r})),or(this.manifest),or(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(ur(p,"error").pipe(pl(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Bt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Jb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Us())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new ha("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],SS(t)){let p=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new ha("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Sa.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(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(hl(1e3).subscribe(p=>{var f;if((f=this.element)!=null&&f.paused){let b=yu(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.timeInWaiting=0};if(this.representationSubscription.add(lr(...VR.map(p=>ur(this.element,p))).pipe(fl(p=>this.element?at(this.element.buffered,this.element.currentTime*1e3):0),gS(),DR(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(lr(ur(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(gS()).subscribe(f=>cl(this.element,1))),this.representationSubscription.add(an({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(pl(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveEstimatedDelay.next(f))),this.representationSubscription.add(an({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=f-g,I=1;Math.abs(S)>T&&(I=1+Math.sign(S)*y),cl(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,T;let b=0;if(f){let y=((T=(g=this.element)==null?void 0:g.currentTime)!=null?T:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var E,k;return(k=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?k:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(an({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(BR(1e3)).subscribe(g=>w(this,[g],function*({liveLoadBufferLength:f,bufferLength:b}){if(or(this.element),this.isUpdatingLive)return;let T=this.element.playbackRate,y=yu(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*T),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*T,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*T,B=isFinite(f)?f:b,G=this.isActiveLowLatency$.getValue(),V=S<=this.tuning.live.activeLiveDelay&&y===0;this.isActiveLowLatency$.next(G&&V);let M="none";if(G?M="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&V?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),M="active_low_latency"):y!==0&&B<I?M="live_forward_buffering":B<I+k&&(M="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let _=p-(I+E),R=this.normolizeLiveOffset(Math.trunc(y+_/T)),U=Math.abs(R-y),L;!f||U<=this.tuning.dashCmafLive.offsetCalculationError?L=y:R>0&&U>this.tuning.dashCmafLive.offsetCalculationError?L=R:L=0,this.manifestUrlString=ne(this.manifestUrlString,L,2)}M!=="none"&&M!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=lr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(fl(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=lr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(fl(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(lr(this.forceEnded$,an({allBuffersFull:l,someBufferEnded:c}).pipe(pl(({allBuffersFull:p,someBufferEnded:f})=>p&&f))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Bt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(lr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let f=[];return p.duration&&f.push(p.duration),Re(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&SS(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=hl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Bt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Zs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveEstimatedDelay=nr.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,A({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return w(this,null,function*(){var r,i,s;or(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ne(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){or(this.element),this.state$.setState("running"),this.subscription.add(lr(...OR.map(e=>ur(this.element,e)),ur(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Bt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ur(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ur(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Lt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var f,b,g,T,y,S,I,E,k,B;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=CR(),o=100,u=(b=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?b:0,l=(T=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?T:0,c=(S=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?S:0,d=(E=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,h=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&this.timeInWaiting>this.tuning.dash.crashOnStallTWithoutDataTimeout||this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.timeInWaiting} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s.liveLastSeekOffset=this.liveLastSeekOffset;else{let G=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(G),(B=this.audioBufferManager)==null||B.maintain(G),s.position=G}this.tracer.log("stallIntervalCallback",va(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=hl(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Bt.NETWORK,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return w(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u,l;or(this.element),or(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Lt(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",va({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=MR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return w(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=D(A({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",va(t)))}}};var nn=class{constructor(e,t){this.fov=e,this.orientation=t}};var on=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/et(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=A({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*et(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var TS=`attribute vec2 a_vertex;
66
66
  attribute vec2 a_texel;
67
67
 
68
68
  varying vec2 v_texel;
@@ -116,5 +116,5 @@ void main(void) {
116
116
  // sample using new coordinates
117
117
  gl_FragColor = texture2D(u_texture, tc);
118
118
  }
119
- `;var un=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new nn(this.params.fov,this.params.orientation),this.cameraRotationManager=new on(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(TS,this.gl.VERTEX_SHADER),r=this.createShader(IS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,h=t+i;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var dr=class{constructor(e){this.subscription=new zR;this.videoState=new D("stopped");this.elementSize$=new KR(void 0);this.textTracksManager=new Ne;this.droppedFramesManager=new Vs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Li;this.audioTrackSwitchHistory=new Li;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return qR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new un(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=be(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(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 sn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ve(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:ml.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var l;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ES(c=>!!c.length),PS()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ES(WR),PS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(xS(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),s(QR(this.video),this.elementSize$),s(Ue(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(HR(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(il(f));let b=[];for(let g of f.representations){let v=nS(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(al(p));let f=[];for(let b of p.representations){let g=sS(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let p of d.text)for(let f of p.representations){let b=oS(p,f);this.textTracksMap.set(b,{stream:p,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=c=>e.error$.next({id:"RepresentationSwitch",category:ml.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(ln(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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,GR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,f]=h,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),f){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,g).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(bl()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(al(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(bl()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(il(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),(l=this.textTracksManager)==null||l.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(xS(({to:c})=>c==="ready"),bl());this.subscription.add(ln(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(ln(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ln(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,YR(["init"])).pipe(jR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var $,L,_,W,V,N,R,q,M,x,E,C,Y;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=($=e.videoTrack.getState())==null?void 0:$.id,n=[...this.videoTracksMap.keys()].find(({id:F})=>F===i),o=t.currentVideoTrack$.getValue(),u=((W=(_=e.videoStream.getState())!=null?_:n&&((L=this.videoTracksMap.get(n))==null?void 0:L.stream))!=null?W:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:F})=>F===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=at(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(V=e.audioStream.getState())!=null?V:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(N=[...this.audioStreamsMap.keys()].find(({id:F})=>F===(f==null?void 0:f.id)))!=null?N:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let F=Cs(n,c,(R=this.audioStreamsMap.get(b))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(q=F==null?void 0:F.bitrate)!=null?q:-1/0)}if(o){let F=Cs(o,c,(M=this.audioStreamsMap.get(b))!=null?M:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(x=F==null?void 0:F.bitrate)!=null?x:-1/0)}}let v=$t(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),y=r?v!=null?v:n:n!=null?n:v,S=b&&Vb(y,c,(E=this.audioStreamsMap.get(b))!=null?E:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),T=(C=this.videoTracksMap.get(y))==null?void 0:C.representation,I=S&&((Y=this.audioTracksMap.get(S))==null?void 0:Y.representation);if(T&&I)return[T,I];if(T&&!I&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(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}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ge(this.video),this.tracer.end()}};var Ta=class extends dr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as AS,interval as JR,map as XR}from"@vkontakte/videoplayer-shared";var Ia=class extends dr{constructor(e){super(e),this.liveOffset=new dt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(AS({interval:JR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(AS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(XR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(i=>{if(i){let s=uS(i);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var kS=We($s(),1);import{assertNever as Ea,assertNonNullable as wS,debounce as ZR,ErrorCategory as cn,filter as e$,isNonNullable as t$,isNullable as r$,map as dn,merge as i$,Observable as a$,observableFrom as s$,Subscription as n$,videoSizeToQuality as o$}from"@vkontakte/videoplayer-shared";var Xe={};var Qr=(a,e)=>new a$(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),xa=class{constructor(e){this.subscription=new n$;this.videoState=new D("initializing");this.textTracksManager=new Ne;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ea(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ea(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ea(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ea(e)}break;default:Ea(t)}};this.video=be(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ge(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:cn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,kS.default)(import("hls.js").then(i=>{e||(Xe.Hls=i.default,Xe.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){wS(Xe.Hls,"hls.js not loaded"),this.hls=new Xe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){wS(Xe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:cn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=ve(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(rt(this.video,e.isLooped,r)),this.subscription.add(Se(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(_e(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(dn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Qr(this.hls,Xe.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:cn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Qr(this.hls,Xe.Events.MANIFEST_PARSED).pipe(dn(({levels:l})=>l.reduce((c,d)=>{var y,S;let h=d.name||d.height.toString(10),{width:p,height:f}=d,b=(S=Rt((y=d.attrs.QUALITY)!=null?y:""))!=null?S:o$({width:p,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(Qr(this.hls,Xe.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",f=d.lang;c.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Qr(this.hls,Xe.Events.LEVEL_LOADING).pipe(dn(({url:l})=>re(l))),t.hostname$),s(Qr(this.hls,Xe.Events.FRAG_CHANGED),l=>{var h,p,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(At(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Qr(this.hls,Xe.Events.LEVEL_SWITCHED).pipe(dn(({level:l})=>n(this.hls.levels[l])));o.pipe(e$(t$)).subscribe(t.currentVideoTrack$,r),this.subscription.add(At(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(r$(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=i$(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s$(["init"])).pipe(ZR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return k(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cn.DOM,thrown:t})))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0)}};var RS="X-Playback-Duration",gl=a=>k(void 0,null,function*(){var i;let e=yield ht(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(RS)?parseInt(e.headers.get(RS),10):void 0});import{assertNever as h$,combine as f$,debounce as m$,ErrorCategory as hn,filter as b$,filterChanged as g$,isNonNullable as LS,isNullable as fn,map as MS,merge as S$,observableFrom as v$,Subscription as y$,ValueSubject as yl,VideoQuality as T$}from"@vkontakte/videoplayer-shared";var vl=We(Bo(),1);import{videoSizeToQuality as u$,getExponentialDelay as l$}from"@vkontakte/videoplayer-shared";var c$=a=>{let e=null;if(a.QUALITY&&(e=Rt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=u$({width:t,height:r})}return e!=null?e:null},d$=(a,e)=>{var s,n;let t=a.split(`
120
- `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,vl.default)(l[1].split(",").map(y=>y.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=c$(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[y,S]=d.RESOLUTION.split("x").map(T=>parseInt(T,10));y&&S&&(g={width:y,height:S})}let v=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:v,bandwidth:f,size:g,fps:b})}if(c){let d=(0,vl.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,f=d.NAME;h&&p&&i.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},p$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Sl=0,$S=(r,...i)=>k(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield ht(a)).text();Sl+=1;try{let{qualityManifests:o,textTracks:u}=d$(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Sl<=t.manifestRetryMaxCount)return yield p$(l$(Sl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),$S(a,e,t)}return{qualityManifests:[],textTracks:[]}}),pn=$S;var Pa=class{constructor(e){this.subscription=new y$;this.videoState=new D("stopped");this.textTracksManager=new Ne;this.manifests$=new yl([]);this.liveOffset=new dt;this.manifestStartTime$=new yl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return h$(t)}};var t;this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:T$.INVARIANT,url:this.params.source.url},pn(oe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:hn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:hn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new yl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:hn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(g$(),MS(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&LS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(re(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(f$({startTime:this.manifestStartTime$.pipe(b$(LS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(MS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=S$(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,v$(["init"])).pipe(m$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var o,u;let e=this.selectManifest();if(fn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&i.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=oe(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),gl(n).then(l=>{var c;if(!fn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(fn(d)||!isFinite(d))try{ht(n).then(h=>h.text()).then(h=>{var f;let p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(p){let b=new URL(p,n).toString();gl(b).then(g=>{fn(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as I$,debounce as E$,ErrorCategory as Tl,fromEvent as Il,isNonNullable as x$,isNullable as P$,map as CS,merge as DS,observableFrom as BS,Subscription as A$,ValueSubject as w$,VideoQuality as k$,clientChecker as R$}from"@vkontakte/videoplayer-shared";var Aa=class{constructor(e){this.subscription=new A$;this.videoState=new D("stopped");this.textTracksManager=new Ne;this.manifests$=new w$([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return I$(t)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:k$.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(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),pn(oe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Tl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Tl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(CS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&x$(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(f=>f.id===h);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(CS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!R$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(DS(Il(o,"addtrack"),Il(o,"removetrack"),Il(o,"change"),BS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=DS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,BS(["init"])).pipe(E$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var s,n;let e=this.selectManifest();if(P$(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as $$,assertNonNullable as OS,debounce as L$,ErrorCategory as VS,isHigher as M$,isHigherOrEqual as C$,isInvariantQuality as _S,isLowerOrEqual as D$,isNonNullable as B$,merge as O$,observableFrom as V$,Subscription as _$,map as N$}from"@vkontakte/videoplayer-shared";var wa=class{constructor(e){this.subscription=new _$;this.videoState=new D("stopped");this.trackUrls={};this.textTracksManager=new Ne;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return $$(e)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:VS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(N$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&B$(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=O$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,V$(["init"])).pipe(L$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ge(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;OS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];OS(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(re(t))}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:VS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!_S(d.track.quality)&&D$(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&C$(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(p=>!_S(p.track.quality)&&M$(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=$t(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as FS,debounce as H$,merge as US,observableFrom as j$,Subscription as G$,map as qS,ValueSubject as W$,ErrorCategory as xl,VideoQuality as Y$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as F$}from"@vkontakte/videoplayer-shared";var NS=["stun:videostun.mycdn.me:80"],U$=1e3,q$=3,El=()=>null,mn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=El;this.externalStopCallback=El;this.externalErrorCallback=El;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return k(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return k(this,null,function*(){try{let e={iceServers:[{urls:NS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return k(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return k(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:F$.WTF,message:e.message})}onPeerConnectionStream(e){return k(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return k(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),U$)}normalizeOptions(e={}){let t={stunServerList:NS,maxRetryNumber:q$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ka=class{constructor(e){this.videoState=new D("stopped");this.maxSeekBackTime$=new W$(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return FS(e)}};this.subscription=new G$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=be(e.container,e.tuning),this.liveStreamClient=new mn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:xl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};US(this.videoState.stateChangeStarted$.pipe(qS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(qS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ve(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Ue(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Se(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return FS(n.to)}},r)).add(US(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,j$(["init"])).pipe(H$(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(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:Y$.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:xl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ra=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 La,assertNonNullable as Ot,ErrorCategory as bn,filter as QS,isNonNullable as zS,isNullable as tL,map as rL,merge as iL,once as aL,Subject as Ee,Subscription as KS,ValueSubject as O,flattenObject as JS}from"@vkontakte/videoplayer-shared";import{Observable as Q$,map as HS,Subscription as z$,Subject as K$}from"@vkontakte/videoplayer-shared";var jS=a=>new Q$(e=>{let t=new z$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(HS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(HS(({type:l})=>l!==void 0)),n=new K$,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as J$,Subscription as X$,combine as Z$,filter as WS,once as YS}from"@vkontakte/videoplayer-shared";function GS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as eL}from"@vkontakte/videoplayer-shared";var $a=class $a{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ke;this.subscriptions=new X$;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)))}subscribe(e){eL.isSafari&&e!=="MPEG"||this.subscriptions.add(Z$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(WS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),YS()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return k(this,null,function*(){let{volumeMultiplier:t}=this,r=GS();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:$a.errorId,category:J$.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${$a.errorId} exception`,thrown:e})}};$a.errorId="VolumeMultiplierManager";var zr=$a;var sL={chunkDuration:5e3,maxParallelRequests:5},Ma=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableVideoTracks$:new O([]),currentVideoTrack$:new O(void 0),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new Ee,warning$:new Ee,willSeekEvent$:new Ee,soundProhibitedEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1),playbackState$:new O("")};this.subscription=new KS;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=dg([...hg(this.params.tuning),...pg(this.params.tuning)],this.params.tuning).filter(l=>zS(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!i.includes(l)),...t.filter(l=>i.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",JS(s)),this.screenFormatsIterator=new Ra(s);let n=[...Fu(!0),...Fu(!1)];this.chromecastFormatsIterator=new Ra(n.filter(l=>zS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&zr.isSupported()&&(this.volumeMultiplierManager=new zr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(tL(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:bn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return La(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ot(o),new Ta(B(w({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Ia(B(w({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ot(o),Hr||!this.params.tuning.useHlsJs?new Aa(B(w({},n),{source:o})):new xa(B(w({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Pa(B(w({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ot(o),new wa(B(w({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Qb(B(w({},n),{source:o,config:B(w({},sL),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new ka({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return La(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ot(o),new wi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return La(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return La(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 La(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return B(w({},e),{url:r(e.url)})}return(0,XS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new KS,t=!1,r=0;return e.add(iL(this.providerOutput.error$.pipe(QS(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),jS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(rL(i=>({id:`ProviderHangup:${i}`,category:bn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(QS(({to:s})=>s==="playing"),aL()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===bn.NETWORK,u=i.category===bn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=B(w({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",JS(n))})),e}};import{fromEvent as gn,once as nL,combine as oL,Subscription as ZS,ValueSubject as Pl,map as uL,filter as lL,isNonNullable as Sn,now as Le,safeStorage as Al}from"@vkontakte/videoplayer-shared";var cL=5e3,ev="one_video_throughput",tv="one_video_rtt",bt=window.navigator.connection,rv=()=>{let a=bt==null?void 0:bt.downlink;if(Sn(a)&&a!==10)return a*1e3},iv=()=>{let a=bt==null?void 0:bt.rtt;if(Sn(a)&&a!==3e3)return a},av=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wl=class a{constructor(e){this.subscription=new ZS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(ev)||(e.useBrowserEstimation?rv():void 0)||cL,r=(s=(i=a.load(tv))!=null?i:e.useBrowserEstimation?iv():void 0)!=null?s:0;if(this.throughput$=new Pl(t),this.rtt$=new Pl(r),this.rttAdjustedThroughput$=new Pl(av(t,r,e.rttPenaltyRequestSize)),this.throughput=or.getSmoothedValue(t,-1,e),this.rtt=or.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=rv();u&&this.throughput.next(u);let l=iv();Sn(l)&&this.rtt.next(l)};bt&&"onchange"in bt&&this.subscription.add(gn(bt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Al.set(ev,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Al.set(tv,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(oL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(uL(({throughput:n,rtt:o})=>av(n,o,e.rttPenaltyRequestSize)),lL(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Le(),i=new ZS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(gn(e,"progress").pipe(nL()).subscribe(s=>{t=s.loaded,r=Le()}));break;case 1:case 0:i.add(gn(e,"loadstart").subscribe(()=>{t=0,r=Le()}));break}i.add(gn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Le(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Le(),n=0,o=Le(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>k(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Le()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Le();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Le()}else n+=d.byteLength;o=Le()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Le()-o,this.concurrentDownloads.size),n=0,o=Le());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Al.get(e);if(Sn(t))return(r=parseInt(t,10))!=null?r:void 0}},sv=wl;import{fillWithDefault as dL,VideoQuality as nv}from"@vkontakte/videoplayer-shared";var ov={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:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioPolynome:[0,.5,.5],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:nv.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:nv.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,accumulationBufferStallSize:{shortVideoDuration:2*6e4,shortVideoBufferStallSizeMs:0,longVideoBufferStallSizeMs:0},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",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:!1,useNewPruneBufferStrategy:!1,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!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},uv=a=>{var e;return B(w({},dL(a,ov)),{configName:[...(e=a.configName)!=null?e:[],...ov.configName]})};import{assertNonNullable as vn,combine as Vt,ErrorCategory as yn,filter as pe,filterChanged as H,fromEvent as Rl,isNonNullable as SL,isNullable as vL,Logger as yL,map as U,mapTo as pv,merge as _t,now as Tn,once as st,Subject as Q,Subscription as hv,tap as fv,ValueSubject as A,isHigher as TL,isInvariantQuality as mv,flattenObject as Nt,throttle as $l,getTraceSubscriptionMethod as bv,Tracer as IL}from"@vkontakte/videoplayer-shared";import{merge as pL,map as hL,filter as lv,isNonNullable as fL}from"@vkontakte/videoplayer-shared";var kl=({seekState:a,position$:e})=>pL(a.stateChangeEnded$.pipe(hL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),lv(fL)),e.pipe(lv(()=>a.getState().state==="none")));import{assertNonNullable as mL}from"@vkontakte/videoplayer-shared";var cv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return mL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as bL,once as gL}from"@vkontakte/videoplayer-shared";var dv=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(bL(i=>i.length>0),gL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var In=class{constructor(e={configName:[]},t=IL.createRootTracer(!1)){this.subscription=new hv;this.logger=new yL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new D("stopped"),seekState:new D({state:"none"}),volume:new D({volume:1,muted:!1}),videoTrack:new D(void 0),videoStream:new D(void 0),audioStream:new D(void 0),autoVideoTrackSwitching:new D(!0),autoVideoTrackLimits:new D({}),isLooped:new D(!1),playbackRate:new D(1),externalTextTracks:new D([]),internalTextTracks:new D([]),currentTextTrack:new D(void 0),textTrackCuesSettings:new D({}),cameraOrientation:new D({x:0,y:0})};this.info={playbackState$:new A("stopped"),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:wb};if(this.initLogs(),this.tuning=uv(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 sv(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:yn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let i=e,{container:t}=i,r=pc(i,["container"]);return this.tracer.log("initVideo",Nt(r)),this.domContainer=cv(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Ma({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}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&&!Oi()?(this.tracer.log("request play from hidden tab"),Rl(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 r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){vn(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.providerContainer.providerOutput.availableVideoTracks$.pipe(pe(r=>r.length>0),st()).subscribe(r=>{this.setVideoTrackIdByQuality(r,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}setPlaybackRate(e){var r;vn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Nt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>w({type:"external"},t))),this}selectTextTrack(e){var t;return dv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",w({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(vL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return SL(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pe(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=Tn(),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(B(w({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:yn.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(U(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(U(n=>n.destination),H()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(U(n=>n.map(({quality:o})=>o).sort((o,u)=>mv(o)?1:mv(u)?-1:TL(u,o)?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(H()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(H((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(H((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(H()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(H()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(H()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(U(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(Vt({hasLiveOffsetByPaused:_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(n=>n.to),H(),U(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:kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(U(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),H(),fv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(U(({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(U(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),H(),fv(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(U(n=>n.muted),H()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(U(n=>n.volume),H()).subscribe(this.info.volume$)).add(kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(_t(e.providerOutput.endedEvent$.pipe(pv(!0)),e.providerOutput.seekedEvent$.pipe(pv(!1))).pipe(H()).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(U(n=>({id:n?`No${n}`:"NoProviders",category:yn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(st(),U(n=>n!=null?n:Tn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),U(()=>Tn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),U(()=>Tn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new A(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(pe(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let i=0,s=_t(e.providerOutput.isBuffering$,t,r).pipe(U(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),H());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(_t(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(_t(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(U(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new hv;this.subscription.add(t),this.subscription.add(e.current$.pipe(H((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pe(r=>r.length>0),st()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=$t(e,{container:this.domContainer.getBoundingClientRect(),throughput: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(U(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(U(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;vn(this.providerContainer),vn(e),Ab(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Pb(r)),this.providerContainer.current$.subscribe(({type:r})=>$i("provider",r)),e.duration$.subscribe(r=>$i("duration",r)),e.availableVideoTracks$.pipe(pe(r=>!!r.length),st()).subscribe(r=>$i("tracks",r)),this.events.fatalError$.subscribe(new de("fatalError")),this.events.managedError$.subscribe(new de("managedError")),e.position$.subscribe(new de("position")),e.currentVideoTrack$.pipe(U(r=>r==null?void 0:r.quality)).subscribe(new de("quality")),this.info.currentBuffer$.subscribe(new de("buffer")),e.isBuffering$.subscribe(new de("isBuffering"))].forEach(r=>this.subscription.add(r)),$i("codecs",cg())}initTracerSubscription(){let e=bv(this.tracer.log.bind(this.tracer)),t=bv(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(H()).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:r,videoBitrate:i})=>!!r&&!!i),H((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(pe(r=>r>0),H()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(pe(r=>r>0),H()).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(r=>r.end>0),H((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(H())}).pipe($l(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(H()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(H()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(H()).subscribe(e("canChangePlaybackSpeed"))).add(Vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(pe(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),$l(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(H(),pe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(H(),pe(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(H()).subscribe(e("muted"))).add(this.info.volume$.pipe(H()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(H(),pe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(pe(({throughputEstimation:r,rtt:i})=>!!r&&!!i),$l(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(H(),pe(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>k(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:yn.DOM,message:String(i)})})});this.subscription.add(_t(Rl(document,"visibilitychange"),Rl(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Nt({quality:t,availableTracks:Nt(e),track:Nt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as t2,Observable as r2,Subject as i2,ValueSubject as a2,VideoQuality as s2}from"@vkontakte/videoplayer-shared";var n2=`@vkontakte/videoplayer-core@${hc}`;export{Ya as ChromecastState,Ln as HttpConnectionType,r2 as Observable,fe as PlaybackState,In as Player,n2 as SDK_VERSION,i2 as Subject,t2 as Subscription,Mn as Surface,hc as VERSION,a2 as ValueSubject,xt as VideoFormat,s2 as VideoQuality};
119
+ `;var un=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new nn(this.params.fov,this.params.orientation),this.cameraRotationManager=new on(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(TS,this.gl.VERTEX_SHADER),r=this.createShader(IS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,h=t+i;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var cr=class{constructor(e){this.subscription=new zR;this.videoState=new C("stopped");this.elementSize$=new KR(void 0);this.textTracksManager=new _e;this.droppedFramesManager=new Vs;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Li;this.audioTrackSwitchHistory=new Li;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return qR(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new un(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=be(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(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 sn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ve(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:ml.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var l;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ES(c=>!!c.length),PS()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})})),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ES(WR),PS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(xS(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Se(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ve(this.video,t.playbackRate,r.playbackRateState$,i)),s(YR(this.video),this.elementSize$),s(Fe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(HR(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(il(f));let b=[];for(let g of f.representations){let T=nS(g);b.push(T),this.audioTracksMap.set(T,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(al(p));let f=[];for(let b of p.representations){let g=sS(b);g&&(f.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let p of d.text)for(let f of p.representations){let b=oS(p,f);this.textTracksMap.set(b,{stream:p,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=c=>e.error$.next({id:"RepresentationSwitch",category:ml.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(ln(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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,GR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,f]=h,b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),c==="manifest_ready")this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),f){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,g).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(bl()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(al(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(bl()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(il(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),(l=this.textTracksManager)==null||l.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(xS(({to:c})=>c==="ready"),bl());this.subscription.add(ln(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(ln(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ln(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,QR(["init"])).pipe(jR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var k,B,G,V,M,_,R,U,L,W,v,$,Y;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(k=e.videoTrack.getState())==null?void 0:k.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===i),o=t.currentVideoTrack$.getValue(),u=((V=(G=e.videoStream.getState())!=null?G:n&&((B=this.videoTracksMap.get(n))==null?void 0:B.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=at(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(M=e.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(_=[...this.audioStreamsMap.keys()].find(({id:N})=>N===(f==null?void 0:f.id)))!=null?_:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let N=Cs(n,c,(R=this.audioStreamsMap.get(b))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(U=N==null?void 0:N.bitrate)!=null?U:-1/0)}if(o){let N=Cs(o,c,(L=this.audioStreamsMap.get(b))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(W=N==null?void 0:N.bitrate)!=null?W:-1/0)}}let T=$t(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),y=r?T!=null?T:n:n!=null?n:T,S=b&&Vb(y,c,(v=this.audioStreamsMap.get(b))!=null?v:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=($=this.videoTracksMap.get(y))==null?void 0:$.representation,E=S&&((Y=this.audioTracksMap.get(S))==null?void 0:Y.representation);if(I&&E)return[I,E];if(I&&!E&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ml.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ge(this.video),this.tracer.end()}};var Ta=class extends cr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as AS,interval as JR,map as XR}from"@vkontakte/videoplayer-shared";var Ia=class extends cr{constructor(e){super(e),this.liveOffset=new dt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(AS({interval:JR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(AS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(XR(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(i=>{if(i){let s=uS(i);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var kS=Ge($s(),1);import{assertNever as Ea,assertNonNullable as wS,debounce as ZR,ErrorCategory as cn,filter as e$,isNonNullable as t$,isNullable as r$,map as dn,merge as i$,Observable as a$,observableFrom as s$,Subscription as n$,videoSizeToQuality as o$}from"@vkontakte/videoplayer-shared";var Je={};var Yr=(a,e)=>new a$(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),xa=class{constructor(e){this.subscription=new n$;this.videoState=new C("initializing");this.textTracksManager=new _e;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ea(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ea(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ea(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ea(e)}break;default:Ea(t)}};this.video=be(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ge(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:cn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,kS.default)(import("hls.js").then(i=>{e||(Je.Hls=i.default,Je.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){wS(Je.Hls,"hls.js not loaded"),this.hls=new Je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){wS(Je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:cn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=ve(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(rt(this.video,e.isLooped,r)),this.subscription.add(Se(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ve(this.video,e.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(dn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Yr(this.hls,Je.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:cn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Yr(this.hls,Je.Events.MANIFEST_PARSED).pipe(dn(({levels:l})=>l.reduce((c,d)=>{var y,S;let h=d.name||d.height.toString(10),{width:p,height:f}=d,b=(S=Rt((y=d.attrs.QUALITY)!=null?y:""))!=null?S:o$({width:p,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(Yr(this.hls,Je.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",f=d.lang;c.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Yr(this.hls,Je.Events.LEVEL_LOADING).pipe(dn(({url:l})=>re(l))),t.hostname$),s(Yr(this.hls,Je.Events.FRAG_CHANGED),l=>{var h,p,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(At(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Yr(this.hls,Je.Events.LEVEL_SWITCHED).pipe(dn(({level:l})=>n(this.hls.levels[l])));o.pipe(e$(t$)).subscribe(t.currentVideoTrack$,r),this.subscription.add(At(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(r$(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=i$(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,s$(["init"])).pipe(ZR(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return w(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cn.DOM,thrown:t})))||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0)}};var RS="X-Playback-Duration",gl=a=>w(void 0,null,function*(){var i;let e=yield ht(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(RS)?parseInt(e.headers.get(RS),10):void 0});import{assertNever as h$,combine as f$,debounce as m$,ErrorCategory as hn,filter as b$,filterChanged as g$,isNonNullable as LS,isNullable as fn,map as MS,merge as S$,observableFrom as v$,Subscription as y$,ValueSubject as yl,VideoQuality as T$}from"@vkontakte/videoplayer-shared";var vl=Ge(Bo(),1);import{videoSizeToQuality as u$,getExponentialDelay as l$}from"@vkontakte/videoplayer-shared";var c$=a=>{let e=null;if(a.QUALITY&&(e=Rt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=u$({width:t,height:r})}return e!=null?e:null},d$=(a,e)=>{var s,n;let t=a.split(`
120
+ `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,vl.default)(l[1].split(",").map(y=>y.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=c$(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[y,S]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));y&&S&&(g={width:y,height:S})}let T=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:T,bandwidth:f,size:g,fps:b})}if(c){let d=(0,vl.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,f=d.NAME;h&&p&&i.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},p$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Sl=0,$S=(r,...i)=>w(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield ht(a)).text();Sl+=1;try{let{qualityManifests:o,textTracks:u}=d$(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Sl<=t.manifestRetryMaxCount)return yield p$(l$(Sl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),$S(a,e,t)}return{qualityManifests:[],textTracks:[]}}),pn=$S;var Pa=class{constructor(e){this.subscription=new y$;this.videoState=new C("stopped");this.textTracksManager=new _e;this.manifests$=new yl([]);this.liveOffset=new dt;this.manifestStartTime$=new yl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return h$(t)}};var t;this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:T$.INVARIANT,url:this.params.source.url},pn(ne(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:hn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:hn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(re(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new yl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:hn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ve(this.video,t.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(g$(),MS(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&LS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(re(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(f$({startTime:this.manifestStartTime$.pipe(b$(LS)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(MS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=S$(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,v$(["init"])).pipe(m$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var o,u;let e=this.selectManifest();if(fn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&i.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ne(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),gl(n).then(l=>{var c;if(!fn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(fn(d)||!isFinite(d))try{ht(n).then(h=>h.text()).then(h=>{var f;let p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(p){let b=new URL(p,n).toString();gl(b).then(g=>{fn(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as I$,debounce as E$,ErrorCategory as Tl,fromEvent as Il,isNonNullable as x$,isNullable as P$,map as CS,merge as DS,observableFrom as BS,Subscription as A$,ValueSubject as w$,VideoQuality as k$,clientChecker as R$}from"@vkontakte/videoplayer-shared";var Aa=class{constructor(e){this.subscription=new A$;this.videoState=new C("stopped");this.textTracksManager=new _e;this.manifests$=new w$([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return I$(t)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:k$.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(re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),pn(ne(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Tl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Tl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(CS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ve(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&x$(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(f=>f.id===h);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(re(p.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(f),g.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(CS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!R$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(DS(Il(o,"addtrack"),Il(o,"removetrack"),Il(o,"change"),BS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=DS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,BS(["init"])).pipe(E$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var s,n;let e=this.selectManifest();if(P$(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as $$,assertNonNullable as OS,debounce as L$,ErrorCategory as VS,isHigher as M$,isHigherOrEqual as C$,isInvariantQuality as _S,isLowerOrEqual as D$,isNonNullable as B$,merge as O$,observableFrom as V$,Subscription as _$,map as N$}from"@vkontakte/videoplayer-shared";var wa=class{constructor(e){this.subscription=new _$;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new _e;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return $$(e)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:VS.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(N$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(rt(this.video,t.isLooped,r)),this.subscription.add(Se(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ve(this.video,t.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&B$(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=O$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,V$(["init"])).pipe(L$(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ge(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;OS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];OS(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(re(t))}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:VS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!_S(d.track.quality)&&D$(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&C$(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(p=>!_S(p.track.quality)&&M$(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=$t(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as FS,debounce as H$,merge as US,observableFrom as j$,Subscription as G$,map as qS,ValueSubject as W$,ErrorCategory as xl,VideoQuality as Q$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as F$}from"@vkontakte/videoplayer-shared";var NS=["stun:videostun.mycdn.me:80"],U$=1e3,q$=3,El=()=>null,mn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=El;this.externalStopCallback=El;this.externalErrorCallback=El;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return w(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return w(this,null,function*(){try{let e={iceServers:[{urls:NS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return w(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return w(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:F$.WTF,message:e.message})}onPeerConnectionStream(e){return w(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return w(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),U$)}normalizeOptions(e={}){let t={stunServerList:NS,maxRetryNumber:q$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ka=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new W$(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return FS(e)}};this.subscription=new G$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=be(e.container,e.tuning),this.liveStreamClient=new mn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:xl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};US(this.videoState.stateChangeStarted$.pipe(qS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(qS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ve(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Fe(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Se(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return FS(n.to)}},r)).add(US(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,j$(["init"])).pipe(H$(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(re(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:Q$.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:xl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ra=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 La,assertNonNullable as Ot,ErrorCategory as bn,filter as YS,isNonNullable as zS,isNullable as tL,map as rL,merge as iL,once as aL,Subject as Ee,Subscription as KS,ValueSubject as O,flattenObject as JS}from"@vkontakte/videoplayer-shared";import{Observable as Y$,map as HS,Subscription as z$,Subject as K$}from"@vkontakte/videoplayer-shared";var jS=a=>new Y$(e=>{let t=new z$,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(HS(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(HS(({type:l})=>l!==void 0)),n=new K$,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as J$,Subscription as X$,combine as Z$,filter as WS,once as QS}from"@vkontakte/videoplayer-shared";function GS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as eL}from"@vkontakte/videoplayer-shared";var $a=class $a{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ke;this.subscriptions=new X$;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(WS(s=>!!s.type),QS()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){eL.isSafari&&e!=="MPEG"||this.subscriptions.add(Z$({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(WS(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),QS()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return w(this,null,function*(){let{volumeMultiplier:t}=this,r=GS();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:$a.errorId,category:J$.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${$a.errorId} exception`,thrown:e})}};$a.errorId="VolumeMultiplierManager";var zr=$a;var sL={chunkDuration:5e3,maxParallelRequests:5},Ma=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableVideoTracks$:new O([]),currentVideoTrack$:new O(void 0),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new Ee,warning$:new Ee,willSeekEvent$:new Ee,soundProhibitedEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1),playbackState$:new O("")};this.subscription=new KS;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=dg([...hg(this.params.tuning),...pg(this.params.tuning)],this.params.tuning).filter(l=>zS(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!i.includes(l)),...t.filter(l=>i.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",JS(s)),this.screenFormatsIterator=new Ra(s);let n=[...Fu(!0),...Fu(!1)];this.chromecastFormatsIterator=new Ra(n.filter(l=>zS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&zr.isSupported()&&(this.volumeMultiplierManager=new zr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(tL(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:bn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return La(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ot(o),new Ta(D(A({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Ia(D(A({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ot(o),Hr||!this.params.tuning.useHlsJs?new Aa(D(A({},n),{source:o})):new xa(D(A({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Pa(D(A({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ot(o),new wa(D(A({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Yb(D(A({},n),{source:o,config:D(A({},sL),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new ka({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return La(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ot(o),new wi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return La(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return La(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 La(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return D(A({},e),{url:r(e.url)})}return(0,XS.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new KS,t=!1,r=0;return e.add(iL(this.providerOutput.error$.pipe(YS(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),jS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(rL(i=>({id:`ProviderHangup:${i}`,category:bn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(YS(({to:s})=>s==="playing"),aL()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===bn.NETWORK,u=i.category===bn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=D(A({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",JS(n))})),e}};import{fromEvent as gn,once as nL,combine as oL,Subscription as ZS,ValueSubject as Pl,map as uL,filter as lL,isNonNullable as Sn,now as Le,safeStorage as Al}from"@vkontakte/videoplayer-shared";var cL=5e3,ev="one_video_throughput",tv="one_video_rtt",bt=window.navigator.connection,rv=()=>{let a=bt==null?void 0:bt.downlink;if(Sn(a)&&a!==10)return a*1e3},iv=()=>{let a=bt==null?void 0:bt.rtt;if(Sn(a)&&a!==3e3)return a},av=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wl=class a{constructor(e){this.subscription=new ZS;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(ev)||(e.useBrowserEstimation?rv():void 0)||cL,r=(s=(i=a.load(tv))!=null?i:e.useBrowserEstimation?iv():void 0)!=null?s:0;if(this.throughput$=new Pl(t),this.rtt$=new Pl(r),this.rttAdjustedThroughput$=new Pl(av(t,r,e.rttPenaltyRequestSize)),this.throughput=nr.getSmoothedValue(t,-1,e),this.rtt=nr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=rv();u&&this.throughput.next(u);let l=iv();Sn(l)&&this.rtt.next(l)};bt&&"onchange"in bt&&this.subscription.add(gn(bt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Al.set(ev,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Al.set(tv,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(oL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(uL(({throughput:n,rtt:o})=>av(n,o,e.rttPenaltyRequestSize)),lL(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Le(),i=new ZS;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(gn(e,"progress").pipe(nL()).subscribe(s=>{t=s.loaded,r=Le()}));break;case 1:case 0:i.add(gn(e,"loadstart").subscribe(()=>{t=0,r=Le()}));break}i.add(gn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Le(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Le(),n=0,o=Le(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>w(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Le()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Le();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Le()}else n+=d.byteLength;o=Le()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Le()-o,this.concurrentDownloads.size),n=0,o=Le());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Al.get(e);if(Sn(t))return(r=parseInt(t,10))!=null?r:void 0}},sv=wl;import{fillWithDefault as dL,VideoQuality as nv}from"@vkontakte/videoplayer-shared";var ov={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:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:1,limitByContainer:!0,containerSizeFactor:1.5,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:nv.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:nv.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,accumulationBufferStallSize:{shortVideoDuration:2*6e4,shortVideoBufferStallSizeMs:0,longVideoBufferStallSizeMs:0},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",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:!1,useNewPruneBufferStrategy:!1,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!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},uv=a=>{var e;return D(A({},dL(a,ov)),{configName:[...(e=a.configName)!=null?e:[],...ov.configName]})};import{assertNonNullable as vn,combine as Vt,ErrorCategory as yn,filter as pe,filterChanged as q,fromEvent as Rl,isNonNullable as SL,isNullable as vL,Logger as yL,map as F,mapTo as pv,merge as _t,now as Tn,once as st,Subject as Q,Subscription as hv,tap as fv,ValueSubject as P,isHigher as TL,isInvariantQuality as mv,flattenObject as Nt,throttle as $l,getTraceSubscriptionMethod as bv,Tracer as IL}from"@vkontakte/videoplayer-shared";import{merge as pL,map as hL,filter as lv,isNonNullable as fL}from"@vkontakte/videoplayer-shared";var kl=({seekState:a,position$:e})=>pL(a.stateChangeEnded$.pipe(hL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),lv(fL)),e.pipe(lv(()=>a.getState().state==="none")));import{assertNonNullable as mL}from"@vkontakte/videoplayer-shared";var cv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return mL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as bL,once as gL}from"@vkontakte/videoplayer-shared";var dv=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(bL(i=>i.length>0),gL()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var In=class{constructor(e={configName:[]},t=IL.createRootTracer(!1)){this.subscription=new hv;this.logger=new yL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:wb};if(this.initLogs(),this.tuning=uv(e),this.tracer=t,e.initialPlaybackRate&&this.info.currentPlaybackRate$.next(e.initialPlaybackRate),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new za({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new sv(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let b=typeof f;return["number","string","boolean"].includes(b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:yn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let i=e,{container:t}=i,r=pc(i,["container"]);return this.tracer.log("initVideo",Nt(r)),this.domContainer=cv(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Ma({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.setPlaybackRate(this.info.currentPlaybackRate$.getValue()),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}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&&!Oi()?(this.tracer.log("request play from hidden tab"),Rl(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 r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){vn(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(r=>r.length>0),st()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Nt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;vn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Nt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>A({type:"external"},t))),this}selectTextTrack(e){var t;return dv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",A({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(vL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return SL(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(F(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pe(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=Tn(),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(D(A({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:yn.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(F(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(F(n=>n.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(F(n=>n.map(({quality:o})=>o).sort((o,u)=>mv(o)?1:mv(u)?-1:TL(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(F(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(Vt({hasLiveOffsetByPaused:_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(F(n=>n.to),q(),F(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:kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(F(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),q(),fv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(F(({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(F(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),fv(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(F(n=>n.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(F(n=>n.volume),q()).subscribe(this.info.volume$)).add(kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(_t(e.providerOutput.endedEvent$.pipe(pv(!0)),e.providerOutput.seekedEvent$.pipe(pv(!1))).pipe(q()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(F(n=>({id:n?`No${n}`:"NoProviders",category:yn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(st(),F(n=>n!=null?n:Tn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),F(()=>Tn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),F(()=>Tn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(pe(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let i=0,s=_t(e.providerOutput.isBuffering$,t,r).pipe(F(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),q());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(_t(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(_t(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(F(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new hv;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pe(r=>r.length>0),st()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=$t(e,{container:this.domContainer.getBoundingClientRect(),throughput: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(F(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(F(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;vn(this.providerContainer),vn(e),Ab(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Pb(r)),this.providerContainer.current$.subscribe(({type:r})=>$i("provider",r)),e.duration$.subscribe(r=>$i("duration",r)),e.availableVideoTracks$.pipe(pe(r=>!!r.length),st()).subscribe(r=>$i("tracks",r)),this.events.fatalError$.subscribe(new de("fatalError")),this.events.managedError$.subscribe(new de("managedError")),e.position$.subscribe(new de("position")),e.currentVideoTrack$.pipe(F(r=>r==null?void 0:r.quality)).subscribe(new de("quality")),this.info.currentBuffer$.subscribe(new de("buffer")),e.isBuffering$.subscribe(new de("isBuffering"))].forEach(r=>this.subscription.add(r)),$i("codecs",cg())}initTracerSubscription(){let e=bv(this.tracer.log.bind(this.tracer)),t=bv(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(pe(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(pe(r=>r>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(pe(r=>r>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Vt({currentBuffer:this.info.currentBuffer$.pipe(pe(r=>r.end>0),q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(q())}).pipe($l(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(Vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(pe(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),$l(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),pe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),pe(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),pe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(pe(({throughputEstimation:r,rtt:i})=>!!r&&!!i),$l(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),pe(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>w(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:yn.DOM,message:String(i)})})});this.subscription.add(_t(Rl(document,"visibilitychange"),Rl(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Nt({quality:t,availableTracks:Nt(e),track:Nt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as eQ,Observable as tQ,Subject as rQ,ValueSubject as iQ,VideoQuality as aQ}from"@vkontakte/videoplayer-shared";var sQ=`@vkontakte/videoplayer-core@${hc}`;export{Qa as ChromecastState,Ln as HttpConnectionType,tQ as Observable,fe as PlaybackState,In as Player,sQ as SDK_VERSION,rQ as Subject,eQ as Subscription,Mn as Surface,hc as VERSION,iQ as ValueSubject,xt as VideoFormat,aQ as VideoQuality};